diff --git a/config.yml b/config.yml index ce95b111..9aa9f960 100644 --- a/config.yml +++ b/config.yml @@ -12,9 +12,9 @@ development: offline_eb: 'eb/en/edge/export/offline/' offline_eb_mapping: 'eb/en/edge/export/offline/offlineDocs/docs/docs.js' - index: 'rhodocs_edge' + index: 'rhodocs' pdfkithost: 'localhost:9393' - current_version: '4.1.0' + current_version: '5.5' jenkins: api_sources: - '../../rhodes/workspace/lib/commonAPI/' @@ -28,9 +28,9 @@ jenkins: launchpad_eb_mapping: 'index.hash' offline_eb: 'eb/en/edge/export/offline/' offline_eb_mapping: 'index.json' - index: 'rhodocs_edge' + index: 'rhodocs' pdfkithost: 'localhost:9393' - current_version: '4.1.0' + current_version: '5.5' edge: api: 'docs/en/edge/api/' api_eb: 'eb/en/edge/api/' @@ -39,9 +39,9 @@ edge: launchpad_eb_mapping: 'index.hash' offline_eb: 'eb/en/edge/export/offline/' offline_eb_mapping: 'index.json' - index: 'rhodocs_edge' + index: 'rhodocs' pdfkithost: 'edgedocs.rhomobile.com' - current_version: '4.1.0' + current_version: '5.5' production: api: 'docs/en/edge/api/' api_eb: 'eb/en/edge/api/' @@ -52,4 +52,4 @@ production: offline_eb_mapping: 'index.json' index: 'rhodocs' pdfkithost: 'docs.rhomobile.com' - current_version: '4.1.0' + current_version: '5.5' diff --git a/docs/en/5.5/api/Adapter.md b/docs/en/5.5/api/Adapter.md new file mode 100644 index 00000000..c5169f1f --- /dev/null +++ b/docs/en/5.5/api/Adapter.md @@ -0,0 +1,49 @@ +#Adapter +
Methods 9  
Properties 5
+

NFC Adapter

+

NFC Adapter provides access to the NFC device to perform device related operations.

+ +
    All properties and methods should be used after activate. Besides supported and isActive.
+## Enabling the API
+In order to use this API you must include the following extension in your `build.yml`
+    :::ruby
+    extensions: ["nfc"]
+
+NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings).
+
+ + + +

Methods

+ +

activate()

Activates the NFC device so that all the NFC operations will be executed.

+

Synchronous Return:

  • Void

Method Access:

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

btConnect(CallBackHandler callback)

Connects the Bluetooth device to obtain device properties.

+

Parameters

  • callback : CallBackHandler Mandatory

Async Callback Returning Parameters: HASH

    • btName : STRING

      Device name.

      +

    • btAddress : STRING

      Device MAC address.

      +

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.Adapter.btConnect(CallBackHandler callback)
    • Ruby: Rho::Adapter.btConnect(CallBackHandler callback)

btDisconnect()

Disconnects the Bluetooth device.

+

Synchronous Return:

  • Void

Method Access:

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

getDeviceInfo()

Gets the NFC device capabilities.

+

Synchronous Return:

  • HASH :

    Return hash with capabilities.

    +
    • operatingModesSupported : ARRAY

      • Object : STRING

        Possible Values :

        Constant: Rho::Adapter.NFC_P2P (For Ruby use "::" for all "." when referencing constants)
        String: 1
        Constant: Rho::Adapter.NFC_Reader_Writer (For Ruby use "::" for all "." when referencing constants)
        String: 2
        Constant: Rho::Adapter.NFC_CE (For Ruby use "::" for all "." when referencing constants)
        String: 3
        Constant: Rho::Adapter.NFC_CE_UICC (For Ruby use "::" for all "." when referencing constants)
        String: 4
        Constant: Rho::Adapter.NFC_CE_SE (For Ruby use "::" for all "." when referencing constants)
        String: 5
        Constant: Rho::Adapter.NFC_CE_Host (For Ruby use "::" for all "." when referencing constants)
        String: 6
        Constant: Rho::Adapter.Multiple_NDEFMessages (For Ruby use "::" for all "." when referencing constants)
        String: 7
        Constant: Rho::Adapter.NFC_LLCP (For Ruby use "::" for all "." when referencing constants)
        String: 8
        Constant: Rho::Adapter.NFC_SNEP (For Ruby use "::" for all "." when referencing constants)
        String: 9
        Constant: Rho::Adapter.NFC_NPP (For Ruby use "::" for all "." when referencing constants)
        String: 10
        Constant: Rho::Adapter.NFC_BT_StaticHandover (For Ruby use "::" for all "." when referencing constants)
        String: 11
        Constant: Rho::Adapter.NFC_BT_DynamicHandover (For Ruby use "::" for all "." when referencing constants)
        String: 12
    • tagsSupported : ARRAY

      Array with tag types – only those tags will be detected.

      +

      • Object : STRING

        Possible Values :

        Constant: Rho::Adapter.MiFareUL (For Ruby use "::" for all "." when referencing constants)
        String: 1
        Constant: Rho::Adapter.MiFareStd (For Ruby use "::" for all "." when referencing constants)
        String: 2
        Constant: Rho::Adapter.MifareULC (For Ruby use "::" for all "." when referencing constants)
        String: 3
        Constant: Rho::Adapter.ISO14443_4A (For Ruby use "::" for all "." when referencing constants)
        String: 4
        Constant: Rho::Adapter.ISO14443_4B (For Ruby use "::" for all "." when referencing constants)
        String: 5
        Constant: Rho::Adapter.ISO15693 (For Ruby use "::" for all "." when referencing constants)
        String: 6
        Constant: Rho::Adapter.FeliCa (For Ruby use "::" for all "." when referencing constants)
        String: 7
        Constant: Rho::Adapter.Jewel (For Ruby use "::" for all "." when referencing constants)
        String: 8
        Constant: Rho::Adapter.Desfire (For Ruby use "::" for all "." when referencing constants)
        String: 9
        Constant: Rho::Adapter.MiFarePlus (For Ruby use "::" for all "." when referencing constants)
        String: 10
        Constant: Rho::Adapter.NXPIcode (For Ruby use "::" for all "." when referencing constants)
        String: 11
        Constant: Rho::Adapter.Topaz (For Ruby use "::" for all "." when referencing constants)
        String: 12
        Constant: Rho::Adapter.Calypso (For Ruby use "::" for all "." when referencing constants)
        String: 13
        Constant: Rho::Adapter.TITagIt (For Ruby use "::" for all "." when referencing constants)
        String: 14
    • formattingTagsSupported : ARRAY

      Array with tag types – only those tags will be detected. See above tagsSupported parameter.

      +

      • Object : STRING

    • writeProtectedTagsSupported : ARRAY

      Array with tag types – only those tags will be detected. See see above tagsSupported parameter.

      +

      • Object : STRING

    • firmwareVersion : STRING

      This array has only one element.

      +

      • Object : STRING

Method Access:

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

reset()

Resets the NFC device to default configuration. Pollingtime will set to 90, passkey to empty string.

+

Synchronous Return:

  • Void

Method Access:

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

setConfigChangeHandler(CallBackHandler callback)

Register callback for config change. If you change properties like pollingTimeout, passkey then callback will fire.

+

Parameters

  • callback : CallBackHandler Mandatory

Async Callback Returning Parameters: HASH

    • passKey : STRING

      Bluetooth device pass key.

      +

    • pollingTimeout : INTEGER

      Polling timeout in seconds of the NFC device.

      +

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.Adapter.setConfigChangeHandler(CallBackHandler callback)
    • Ruby: Rho::Adapter.setConfigChangeHandler(CallBackHandler callback)

setMessageHandler(CallBackHandler callback)

Register callback for Message receive.

+

Parameters

  • callback : CallBackHandler Mandatory

Async Callback Returning Parameters: HASH

    • messageId : STRING

      Message Id.

      +

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.Adapter.setMessageHandler(CallBackHandler callback)
    • Ruby: Rho::Adapter.setMessageHandler(CallBackHandler callback)

setTagDetectionHandler(ARRAY tagsToBeDetected, CallBackHandler callback)

Register callback for Tag detection.

+

Parameters

  • tagsToBeDetected : ARRAY

    Array with tag types – only those tags will be detected. If empty array – all types. See below tagsSupported parameter in getDeviceInfo method.

    +

    • Object : INTEGER

  • callback : CallBackHandler Mandatory

Async Callback Returning Parameters: HASH

    • tagId : STRING

      Tag Id.

      +

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.Adapter.setTagDetectionHandler(ARRAY tagsToBeDetected, CallBackHandler callback)
    • Ruby: Rho::Adapter.setTagDetectionHandler(ARRAY tagsToBeDetected, CallBackHandler callback)

stop(CallBackHandler callback)

Stops the NFC device.

+

Parameters

  • callback : CallBackHandler Optional

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.Adapter.stop(CallBackHandler callback)
    • Ruby: Rho::Adapter.stop(CallBackHandler callback)
+ +

Properties

+ +

isActive : BOOLEAN Read Only

Gets a value indicating whether or not the NFC device is currently active.

+

Property Access:

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

passkey : STRING

Bluetooth device pass key. Max of 6 characters, empty string is no Passkey (Default is No Passkey). The property is enabled after NFC engine activation.

+

Property Access:

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

pollingTimeout : INTEGER

Polling timeout in seconds of the NFC device. 0 – timeout disabled, default: 90. The property is enabled after NFC engine activation.

+

Property Access:

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

supported : BOOLEAN Read Only

Return true if NFC supported on this device.

+

Property Access:

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

version : STRING Read Only

Gets the version of the NFC stack.

+

Property Access:

  • Instance: This property can be accessed via an instance object of this class:
    • myObject.version
\ No newline at end of file diff --git a/docs/en/5.5/api/Adapter.xml b/docs/en/5.5/api/Adapter.xml new file mode 100644 index 00000000..0b2a1db6 --- /dev/null +++ b/docs/en/5.5/api/Adapter.xml @@ -0,0 +1,273 @@ + + + + + NFC Adapter + NFC Adapter provides access to the NFC device to perform device related operations. + All properties and methods should be used after activate. Besides supported and isActive. + ## Enabling the API + In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["nfc"] + + NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + + + +## Enabling the API +There are two methods of enabling the Adapter API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Adapter API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.adapter.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + List of properties supported by class. + + Return true if NFC supported on this device. + WM + + + Gets a value indicating whether or not the NFC device is currently active. + WM + + + Gets the version of the NFC stack. + WM + + + Polling timeout in seconds of the NFC device. 0 - timeout disabled, default: 90. The property is enabled after NFC engine activation. + WM + + + Bluetooth device pass key. Max of 6 characters, empty string is no Passkey (Default is No Passkey). The property is enabled after NFC engine activation. + WM + + + + + + Activates the NFC device so that all the NFC operations will be executed. + WM + + + Resets the NFC device to default configuration. Pollingtime will set to 90, passkey to empty string. + WM + + + Stops the NFC device. + WM + + + Register callback for Tag detection. + + + Array with tag types - only those tags will be detected. If empty array - all types. See below tagsSupported parameter in getDeviceInfo method. + + + + + + + + + Tag Id. + + + + WM + + + Register callback for Message receive. + + + + + Message Id. + + + + WM + + + Register callback for config change. If you change properties like pollingTimeout, passkey then callback will fire. + + + + + Bluetooth device pass key. + + + Polling timeout in seconds of the NFC device. + + + + WM + + + Connects the Bluetooth device to obtain device properties. + + + + + Device name. + + + Device MAC address. + + + + WM + + + Disconnects the Bluetooth device. + WM + + + Gets the NFC device capabilities. + + Return hash with capabilities. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Array with tag types - only those tags will be detected. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Array with tag types - only those tags will be detected. See above tagsSupported parameter. + + + + Array with tag types - only those tags will be detected. See see above tagsSupported parameter. + + + + This array has only one element. + + + + + WM + + + + + + + 1.0.0 + + + + \ No newline at end of file diff --git a/docs/en/5.5/api/Application.md b/docs/en/5.5/api/Application.md new file mode 100644 index 00000000..eaa02af3 --- /dev/null +++ b/docs/en/5.5/api/Application.md @@ -0,0 +1,147 @@ +#Application +
+

The Application class is used for accessing or setting application level configuration settings.

+

Enabling the API

+ +

This API is part of the coreapi extension that is included automatically.

+ +
:::ruby
+extensions: ["coreapi"]
+
+ +

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

+ +

databaseFilePath(STRING partitionName)

Path to the ORM database file by partition name. Please note that this function does not create a database file. This function only generates the file path based on the application path and partition name.

+

Parameters

  • partitionName : STRING

    Partition name.

    +

Synchronous Return:

  • STRING :

    Full path to the database file for given partition.

    +

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Application.databaseFilePath(STRING partitionName)
    • Ruby: Rho::Application.databaseFilePath(STRING partitionName)

expandDatabaseBlobFilePath(STRING relativePath)

Generates the absolute path to database blob file. Please note that this function does not the create database file. This function only generates the file path based on application path and partition name.

+

Parameters

  • relativePath : STRING

    Relative path to the blob file, as it is stored in the database.

    +

Synchronous Return:

  • STRING :

    Full path to the database blob.

    +

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Application.expandDatabaseBlobFilePath(STRING relativePath)
    • Ruby: Rho::Application.expandDatabaseBlobFilePath(STRING relativePath)

minimize()

Minimize or move the application to background. When running in RhoSimulator this method is supported only for Windows OS.

+

Synchronous Return:

  • Void

Method Access:

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

modelFolderPath(STRING name)

Folder of the model by name.

+

Parameters

  • name : STRING

    Model name.

    +

Synchronous Return:

  • STRING

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Application.modelFolderPath(STRING name)
    • Ruby: Rho::Application.modelFolderPath(STRING name)

processApplicationEvent(STRING applicationEvent, HASH eventData)

Ruby applications must use this method for processing of the application Event. May be called from setApplicationNotify callback.This method should be called for each event. The only exception is SyncUserChanged, where you can choose your own reset database logic.

+

Parameters

  • applicationEvent : STRING

    See setApplicationNotify for applicationEvent values.

    +

  • eventData : HASH

    This will only contain values for the APP_EVENT_CONFIGCONFLICT event. This event may be triggered after an application was upgraded. If your rhoconfig.txt file contains custom properties that are different then what is being provided in the application upgrade package. By default local values are kept in place but you may overwrite configuration with new values and any other steps required for your application upgrade. eventData will be a hash. It will look like {“conflicting key” : [“new value”,“old value”].. }

    +

Synchronous Return:

  • Void

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • Ruby: Rho::Application.processApplicationEvent(STRING applicationEvent, HASH eventData)

quit()

Quit the application. Quitting the application while license screen is shown will be slightly delayed.

+

Synchronous Return:

  • Void

Method Access:

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

relativeDatabaseBlobFilePath(STRING absolutePath)

Generates the relative path to database blob file. Please note that this function does not create a database file. This function only generates the file path based on the application path and partition name.

+

Parameters

  • absolutePath : STRING

    Absolute path to database blob file.

    +

Synchronous Return:

  • STRING

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Application.relativeDatabaseBlobFilePath(STRING absolutePath)
    • Ruby: Rho::Application.relativeDatabaseBlobFilePath(STRING absolutePath)

restore()

Restores the application to be in the foreground. When running in RhoSimulator the method is supported only for Windows OS.

+

Synchronous Return:

  • Void

Method Access:

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

setApplicationNotify(CallBackHandler callback)

This method allows your application to register for application specific events like application activation/deactivation, UI creation/destruction as well as others. Check the Callback section for details.

+

Parameters

  • callback : CallBackHandler Mandatory

Async Callback Returning Parameters: HASH

    • applicationEvent : STRING

      Possible Values :

      Constant: Rho.Application.APP_EVENT_ACTIVATED (For Ruby use "::" for all "." when referencing constants)
      String:Activated

      The application has been activated.

      +
      Constant: Rho.Application.APP_EVENT_DEACTIVATED (For Ruby use "::" for all "." when referencing constants)
      String:Deactivated

      The application has been deactivated. Not supported on iOS.

      +
      Constant: Rho.Application.APP_EVENT_UICREATED (For Ruby use "::" for all "." when referencing constants)
      String:UICreated

      Generated before the start page is loaded. There are no means to set callback and catch event in JavaScript. Ruby Application class descendant can set callback and process this event.

      +
      Constant: Rho.Application.APP_EVENT_UIDESTROYED (For Ruby use "::" for all "." when referencing constants)
      String:UIDestroyed

      This event is triggered when the application is closing and the UI has been cleared.

      +
      Constant: Rho.Application.APP_EVENT_SCREEN_OFF (For Ruby use "::" for all "." when referencing constants)
      String:ScreenOff

      Device screen was turned off when power button was pressed or due to idle timeout. Note: On iOS application is also deactivated (APP_EVENT_DEACTIVATED is fired). On Android the application is not deactivated.Not supported on Windows CE.

      + Platforms:

      Android, iOS, WM

      +
      Constant: Rho.Application.APP_EVENT_SCREEN_ON (For Ruby use "::" for all "." when referencing constants)
      String:ScreenOn

      Device screen was turned on and unlocked.Not supported on Windows CE.

      + Platforms:

      Android, iOS, WM

      +
      Constant: Rho.Application.APP_EVENT_SYNCUSERCHANGED (For Ruby use "::" for all "." when referencing constants)
      String:SyncUserChanged

      Event when the current RhoConnect user has changed. This is available under Ruby Only.

      +
      Constant: Rho.Application.APP_EVENT_CONFIGCONFLICT (For Ruby use "::" for all "." when referencing constants)
      String:ConfigConflict

      This is available under Ruby Only.

      +
      Constant: Rho.Application.APP_EVENT_DBMIGRATESOURCE (For Ruby use "::" for all "." when referencing constants)
      String:DBMigrateSource

      This is available under Ruby Only.

      +
    • eventData : HASH

      This will only contain values for the APP_EVENT_CONFIGCONFLICT event. This event may be triggered after an application was upgraded. If your rhoconfig.txt file contains custom properties that are different then what is being provided in the application upgrade package. By default local values are kept in place but you may overwrite configuration with new values and any other steps required for your application upgrade. eventData will be a hash. It will look like {“conflicting key” : [“new value”,“old value”].. }

      +

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.Application.setApplicationNotify(CallBackHandler callback)
    • Ruby: Rho::Application.setApplicationNotify(CallBackHandler callback)
+ +

Properties

+ +

appBundleFolder : STRING Read Only

Path to apps/app folder inside the application bundle.

+

Property Access:

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

appName : STRING Read Only

Application name.

+

Property Access:

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

appsBundleFolder : STRING Read Only

Path to apps folder inside the application bundle.

+

Property Access:

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

badLinkURI : STRING Read Only

Bad link URI to navigate in browser. This is defined in config.xml: Navigation\BadLinkURI.

+

Property Access:

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

bundleFolder : STRING Read Only

Path to application bundle folder.

+

Property Access:

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

configPath : STRING Read Only

Path to the configuration file.

+

Property Access:

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

country : STRING Read Only

Current application country code.

+

Property Access:

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

databaseBlobFolder : STRING Read Only

Path to folder where the database blob files are stored. Blobs are usually images or binary files. In the ORM Model you would specify that the attribute is of type blob Ex. When capturing an image, the actual file is saved in the databaseBlobFolder.

+

Property Access:

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

defaultNativeMenu : ARRAY Read Only

Native Menu items.

+

  • Object : HASH

    Same values as nativeMenu.

    +

  • Property Access:

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

    invalidSecurityTokenStartPath : STRING Read Only

    Page to navigate to in case of check of SecurityToken failed. Can be set in rhoconfig.txt: invalid_security_token_start_path;

    +

    Property Access:

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

    locale : STRING Read Only

    Current application locale.Like ‘en’, ‘ru’ etc.

    +

    Property Access:

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

    modelsManifestPath : STRING Read Only

    Path to file with the model list.

    +

    Property Access:

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

    nativeMenu : ARRAY

    Native Menu items. To customise the native application menu and controller menu items in ruby follow Application Menu API

    +

  • Object : HASH

    • label : STRING

      Visible label.

      +

    • action : STRING

      URL to page which will be loaded into tab. It may be path to Ruby controller action; i.e. ‘/app/Account’ would load the Account index action. For ruby callback use ‘callback:/app/Account’ Or JavaScript method to call: ‘javascript: methodOnTab();’. Or path to html page to load.

      +

    Property Access:

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

    publicFolder : STRING Read Only

    Path to the application’s public folder.

    +

    Property Access:

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

    securityTokenNotPassed : BOOLEAN Read Only

    Indicates if the security token check was failed. Security token can be set in build.yml: security_token. Same security token should be passed as command line parameter ‘-security_token=token_value’ to application. If security token check failed : if this page exist then application navigate to it, otherwise application will exit.

    +

    Property Access:

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

    settingsPageURI : STRING

    Settings page URI. Will be used when Options menu or toolbar item is chosen by user.

    +

    Property Access:

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

    splash : STRING Read Only

    Splash screen image display options. This a string with several parameters divided by ‘;’: delay=5;center;hcenter;vcenter;vzoom;hzoom;zoom.

    +

    Property Access:

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

    startURI : STRING

    Startup page for your application.

    +

    Property Access:

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

    title : STRING

    Define Window caption text. If missed – caption from page used. Not supported on Windows CE devices.

    +

    Property Access:

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

    userFolder : STRING Read Only

    Path to folder where the application can write files and create subfolders.

    +

    Property Access:

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

    version : STRING Read Only

    Version from build time configuration file (build.yml).

    +

    Property Access:

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

    Examples

    + +
    Get folders where items are stored
    +

    There are times where you need access to files bundled with your application, or to write files to a safe folder. These examples show how to retrieve each of the several important folders available.

    +
    :::javascript
    +
    +           
    +     // Get and show the various app folders
    +     var appFolder = Rho.Application.appBundleFolder;
    +     var appsBundleFolder = Rho.Application.appsBundleFolder;
    +     var databaseBlobFolder = Rho.Application.databaseBlobFolder;
    +     var publicFolder = Rho.Application.publicFolder;
    +     var userFolder = Rho.Application.userFolder;
    +
    +     var message = "App bundle folder: "+appFolder+"\n"+
    +     "Apps bundle folder: "+appsBundleFolder+"\n"+
    +     "Database blob folder: "+databaseBlobFolder+"\n"+
    +     "Public folder: "+publicFolder+"\n"+
    +     "User folder: "+userFolder;
    +
    +     alert(message);
    +                   
    +                 
    :::ruby
    +
    +           
    +# Get and show the various app folders
    +appFolder = Rho::Application.appBundleFolder
    +appsBundleFolder = Rho::Application.appsBundleFolder
    +databaseBlobFolder = Rho::Application.databaseBlobFolder
    +publicFolder = Rho::Application.publicFolder
    +userFolder = Rho::Application.userFolder
    +
    +message = "App bundle folder: "+appFolder+"\n"+
    +"Apps bundle folder: "+appsBundleFolder+"\n"+
    +"Database blob folder: "+databaseBlobFolder+"\n"+
    +"Public folder: "+publicFolder+"\n"+
    +"User folder: "+userFolder
    +
    +Alert.show_popup(message)
    +                   
    +                 
    Minimize your application
    +

    This will minimize your application.

    +
    :::javascript
    +
    +Rho.Application.minimize();
    +                 
    :::ruby
    +
    +Rho::Application.minimize
    +                 
    Quit your application
    +

    This will exit your application.

    +
    :::javascript
    +
    +Rho.Application.quit();
    +                 
    :::ruby
    +
    +Rho::Application.quit
    +                 
    Restore your application
    +

    This will restore you application.

    +
    :::javascript
    +
    +Rho.Application.restore();
    +                 
    :::ruby
    +
    +Rho::Application.restore
    +                 
    \ No newline at end of file diff --git a/docs/en/5.5/api/Application.xml b/docs/en/5.5/api/Application.xml new file mode 100644 index 00000000..e7d179af --- /dev/null +++ b/docs/en/5.5/api/Application.xml @@ -0,0 +1,421 @@ + + + + + The Application class is used for accessing or setting application level configuration settings. + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + +## Enabling the API +There are two methods of enabling the Application API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Application API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.application.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + Path to apps/app folder inside the application bundle. + + + Path to apps folder inside the application bundle. + + + Path to application bundle folder. + Path to the Enterprise Browser folder on the device. + + + Path to folder where the application can write files and create subfolders. + + + Path to the configuration file. + + + Path to file with the model list. + + + Path to folder where the database blob files are stored. Blobs are usually images or binary files. In the ORM Model you would specify that the attribute is of type blob Ex. When capturing an image, the actual file is saved in the databaseBlobFolder. + + + Path to the application's public folder. + + + + Startup page for your application. + + + Settings page URI. Will be used when Options menu or toolbar item is chosen by user. + + + Splash screen image display options. This a string with several parameters divided by ';': delay=5;center;hcenter;vcenter;vzoom;hzoom;zoom. + + + Version from build time configuration file (build.yml). + Version of Enterprise Browser. + + + Define Window caption text. If missed - caption from page used. Not supported on Windows CE devices. + WM, Win32 + + + Application name. + + + Current application locale.Like 'en', 'ru' etc. + + + + Current application country code. + + + + + + + Visible label. + + + URL to page which will be loaded into tab. It may be path to Ruby controller action; i.e. '/app/Account' would load the Account index action. For ruby callback use 'callback:/app/Account' Or JavaScript method to call: 'javascript: methodOnTab();'. Or path to html page to load. + URL to page which will be loaded. Or it can be a JavaScript method to call: 'javascript: methodOnTab();'. Or path to html page to load. + + + + Native Menu items. To customise the native application menu and controller menu items in ruby follow [Application Menu API](http://docs.rhomobile.com/en/2.2.0/rhodesapi/menu-apis) + WM, CE, Android, Win32, WP8 + WM, CE, Android, Win32 + + + Native Menu items. + + Same values as nativeMenu. + + WM, CE, Android, Win32, WP8 + WM, CE, Android, Win32 + + + Indicates if the security token check was failed. Security token can be set in build.yml: security_token. Same security token should be passed as command line parameter '-security_token=token_value' to application. If security token check failed : if this page exist then application navigate to it, otherwise application will exit. + Indicates if the security token check was failed. Security token can be passed as command line parameter '-security_token=token_value' to the application. If security token check failed : if this page exist then application navigate to it, otherwise application will exit. + WM, CE, Win32, Android, iOS + WM, CE, Win32, Android + + + Page to navigate to in case of check of SecurityToken failed. Can be set in rhoconfig.txt: invalid_security_token_start_path; + Page to navigate to in case of check of SecurityToken failed. Can be set in rhoconfig.txt: invalid_security_token_start_path; This file is located in the installation folder of the EnetrpriseBrowser application installed on the device. + WM, CE, Win32, Android, iOS + WM, CE, Win32, Android + + + + The version of RhoMobile platform, which was used to build the application. + The version of Enteprise Browser platform, which was used to build the application. + + + + Bad link URI to navigate in browser. This is defined in config.xml: Navigation\\BadLinkURI. + WM + WebKit + + + + + + + + + + Folder of the model by name. + + + Model name. + + + + + + Path to the ORM database file by partition name. Please note that this function does not create a database file. This function only generates the file path based on the application path and partition name. + + + Partition name. + + + + Full path to the database file for given partition. + + + + Generates the absolute path to database blob file. Please note that this function does not the create database file. This function only generates the file path based on application path and partition name. + + + Relative path to the blob file, as it is stored in the database. + + + + Full path to the database blob. + + + + Generates the relative path to database blob file. Please note that this function does not create a database file. This function only generates the file path based on the application path and partition name. + + + Absolute path to database blob file. + + + + + + Quit the application. Quitting the application while license screen is shown will be slightly delayed. + + + Minimize or move the application to background. When running in RhoSimulator this method is supported only for Windows OS. + Minimize or move the application to background. + WM, CE, Win32 + + + Restores the application to be in the foreground. When running in RhoSimulator the method is supported only for Windows OS. + Restores the application to be in the foreground. + WM, CE, Win32 + + + This method allows your application to register for application specific events like application activation/deactivation, UI creation/destruction as well as others. Check the Callback section for details. + WM, CE, Win32, Android, iOS + WM, CE, Win32, Android + + Application events are fired to inform about application state changes. Most of the events are handled only if application is in the foreground mode (activated). You should monitor APP_EVENT_ACTIVATED and APP_EVENT_DEACTIVATED to save application state and start up/shut down activities. Events APP_EVENT_SCREEN_ON and APP_EVENT_SCREEN_OFF should be used to put app into suspend mode without deactivation. Note: Event firing behavior depends on platform. + + + + + + The application has been activated. + + + The application has been deactivated. Not supported on iOS. + The application has been deactivated. + + + Generated before the start page is loaded. There are no means to set callback and catch event in JavaScript. Ruby Application class descendant can set callback and process this event. + + + This event is triggered when the application is closing and the UI has been cleared. + + + Device screen was turned off when power button was pressed or due to idle timeout. Note: On iOS application is also deactivated (APP_EVENT_DEACTIVATED is fired). On Android the application is not deactivated.Not supported on Windows CE. + Device screen was turned off when power button was pressed or due to idle timeout. On Android the application is not deactivated.Not supported on Windows CE. + Android, iOS, WM + Android, WM + + + Device screen was turned on and unlocked.Not supported on Windows CE. + Android, iOS, WM + Android, WM + + + Event when the current RhoConnect user has changed. This is available under Ruby Only. + + + This is available under Ruby Only. + + + + This is available under Ruby Only. + + + + + + This will only contain values for the `APP_EVENT_CONFIGCONFLICT` event. This event may be triggered after an application was upgraded. If your rhoconfig.txt file contains custom properties that are different then what is being provided in the application upgrade package. By default local values are kept in place but you may overwrite configuration with new values and any other steps required for your application upgrade. `eventData` will be a hash. It will look like {"conflicting key" : ["new value","old value"].. } + + + + + + + Ruby applications must use this method for processing of the application Event. May be called from setApplicationNotify callback.This method should be called for each event. The only exception is SyncUserChanged, where you can choose your own reset database logic. + WM, CE, Win32, Android, iOS + WM, CE, Win32, Android + + + + See setApplicationNotify for applicationEvent values. + + + This will only contain values for the `APP_EVENT_CONFIGCONFLICT` event. This event may be triggered after an application was upgraded. If your rhoconfig.txt file contains custom properties that are different then what is being provided in the application upgrade package. By default local values are kept in place but you may overwrite configuration with new values and any other steps required for your application upgrade. `eventData` will be a hash. It will look like {"conflicting key" : ["new value","old value"].. } + + + + + Set application specific locale. + + + + + + + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + + + +
    + There are times where you need access to files bundled with your application, or to write files to a safe folder. These examples show how to retrieve each of the several important folders available. + + + + + + + + +
    +
    +
    + + +
    + This will minimize your application. + + + + + + + + +
    +
    +
    + + +
    + This will exit your application. + + + + + + + + +
    +
    +
    + + +
    + This will restore you application. + + + + + + + + +
    +
    +
    +
    +
    +
    diff --git a/docs/en/5.5/api/Config.md b/docs/en/5.5/api/Config.md new file mode 100644 index 00000000..3d9d6679 --- /dev/null +++ b/docs/en/5.5/api/Config.md @@ -0,0 +1,39 @@ +#Config +
    +

    Rho.Config module

    +

    Implementation of the Config API.

    + + + +

    Methods

    + +

    getPropertyBool(STRING name)

    Get boolean value of config property.

    +

    Parameters

    • name : STRING

      Name of the property.

      +

    Synchronous Return:

    • BOOLEAN

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.Config.getPropertyBool(STRING name)
      • Ruby: Rho::Config.getPropertyBool(STRING name)

    getPropertyInt(STRING name)

    Get integer value of config property.

    +

    Parameters

    • name : STRING

      Name of the property.

      +

    Synchronous Return:

    • INTEGER

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.Config.getPropertyInt(STRING name)
      • Ruby: Rho::Config.getPropertyInt(STRING name)

    getPropertyString(STRING name)

    Get string value of config property.

    +

    Parameters

    • name : STRING

      Name of the property.

      +

    Synchronous Return:

    • STRING

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.Config.getPropertyString(STRING name)
      • Ruby: Rho::Config.getPropertyString(STRING name)

    isPropertyExists(STRING name)

    Returns true if property exists in the loaded config file.

    +

    Parameters

    • name : STRING

      Name of the property.

      +

    Synchronous Return:

    • BOOLEAN

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.Config.isPropertyExists(STRING name)
      • Ruby: Rho::Config.isPropertyExists(STRING name)

    loadFromFile()

    Load config from the file specified by configPath property.

    +

    Synchronous Return:

    • Void

    Method Access:

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

    removeProperty(STRING name, BOOLEAN saveToFile)

    Remove existing property and optionally save changes to file. Remove properties works only with properties that has been set with setProperty*** methods. Properties from config file doesn’t changed.

    +

    Parameters

    • name : STRING

      Name of the property.

      +

    • saveToFile : BOOLEAN

      If true, save changes to file. All changes will save in separate file, not in common config of a aplication.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.Config.removeProperty(STRING name, BOOLEAN saveToFile)
      • Ruby: Rho::Config.removeProperty(STRING name, BOOLEAN saveToFile)

    setPropertyBool(STRING name, BOOLEAN value, BOOLEAN saveToFile)

    Set boolean value of config property and optionally save changes to file. Properties save to separate file, common file (specify with configPath) doesn’t change.

    +

    Parameters

    • name : STRING

      Name of the property.

      +

    • value : BOOLEAN

      Value of the property.

      +

    • saveToFile : BOOLEAN

      If true, save changes to file. All changes will save in separate file, not in common config of a aplication.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.Config.setPropertyBool(STRING name, BOOLEAN value, BOOLEAN saveToFile)
      • Ruby: Rho::Config.setPropertyBool(STRING name, BOOLEAN value, BOOLEAN saveToFile)

    setPropertyInt(STRING name, INTEGER value, BOOLEAN saveToFile)

    Set integer value of config property and optionally save changes to file. Properties save to separate file, common file (specify with configPath) doesn’t change.

    +

    Parameters

    • name : STRING

      Name of the property.

      +

    • value : INTEGER

      Value of the property.

      +

    • saveToFile : BOOLEAN

      If true, save changes to file. All changes will save in separate file, not in common config of a aplication.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.Config.setPropertyInt(STRING name, INTEGER value, BOOLEAN saveToFile)
      • Ruby: Rho::Config.setPropertyInt(STRING name, INTEGER value, BOOLEAN saveToFile)

    setPropertyString(STRING name, STRING value, BOOLEAN saveToFile)

    Set string value of config property and optionally save changes to file. Properties save to separate file, common file (specify with configPath) doesn’t change.

    +

    Parameters

    • name : STRING

      Name of the property.

      +

    • value : STRING

      Value of the property.

      +

    • saveToFile : BOOLEAN

      If true, save changes to file. All changes will save in separate file, not in common config of a aplication.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.Config.setPropertyString(STRING name, STRING value, BOOLEAN saveToFile)
      • Ruby: Rho::Config.setPropertyString(STRING name, STRING value, BOOLEAN saveToFile)
    + +

    Properties

    + +

    configPath : STRING

    Path to the config file.

    +

    Property Access:

    • Instance: This property can be accessed via an instance object of this class:
      • myObject.configPath
    \ No newline at end of file diff --git a/docs/en/5.5/api/Config.xml b/docs/en/5.5/api/Config.xml new file mode 100644 index 00000000..50a71815 --- /dev/null +++ b/docs/en/5.5/api/Config.xml @@ -0,0 +1,127 @@ + + + + + Rho.Config module + Implementation of the Config API. + + Android, WP8,iOS + Android + 5.1.0 + + + + + Path to the config file. + + + + + + + + + Name of the property. + + + + Get string value of config property. + + + + + + Name of the property. + + + Value of the property. + + + If true, save changes to file. All changes will save in separate file, not in common config of a aplication. + + + Set string value of config property and optionally save changes to file. Properties save to separate file, common file (specify with configPath) doesn't change. + + + + + + Name of the property. + + + + Get integer value of config property. + + + + + + Name of the property. + + + Value of the property. + + + If true, save changes to file. All changes will save in separate file, not in common config of a aplication. + + + Set integer value of config property and optionally save changes to file. Properties save to separate file, common file (specify with configPath) doesn't change. + + + + + + Name of the property. + + + + Get boolean value of config property. + + + + + + Name of the property. + + + Value of the property. + + + If true, save changes to file. All changes will save in separate file, not in common config of a aplication. + + + Set boolean value of config property and optionally save changes to file. Properties save to separate file, common file (specify with configPath) doesn't change. + + + + + + Name of the property. + + + + Returns true if property exists in the loaded config file. + + + + + + Name of the property. + + + If true, save changes to file. All changes will save in separate file, not in common config of a aplication. + + + Remove existing property and optionally save changes to file. Remove properties works only with properties that has been set with setProperty*** methods. Properties from config file doesn't changed. + + + + Load config from the file specified by configPath property. + + + + + + + + diff --git a/docs/en/5.5/api/Configreadwrite.md b/docs/en/5.5/api/Configreadwrite.md new file mode 100644 index 00000000..811840f6 --- /dev/null +++ b/docs/en/5.5/api/Configreadwrite.md @@ -0,0 +1,28 @@ +#Configreadwrite +
    +

    The Configreadwrite API provides access to read and write to temporary config files in Android platform. It also provides capabilities to update the user configured attribute value in actual config file.

    +

    Enabling the API

    + +

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

    + +
    :::ruby
    +extensions: ["configreadwrite"]
    +
    + +

    The configreadwrite extension is also included automatically if you specify the following in your build.yml

    + +
    :::ruby
    +app_type: "rhoelements"
    +
    + +

    NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

    + +

    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.

    + +
    \ No newline at end of file diff --git a/docs/en/5.5/api/Configreadwrite.xml b/docs/en/5.5/api/Configreadwrite.xml new file mode 100644 index 00000000..92b80221 --- /dev/null +++ b/docs/en/5.5/api/Configreadwrite.xml @@ -0,0 +1,90 @@ + + + + + The Configreadwrite API provides access to read and write to temporary config files in Android platform. It also provides capabilities to update the user configured attribute value in actual config file. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + :::ruby + extensions: ["configreadwrite"] + +The `configreadwrite` extension is also included automatically if you specify the following in your `build.yml` + :::ruby + app_type: "rhoelements" + +NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + 5.3.0 + Android + + + + Write to actual xml file + + + + + + + + Get the status whether updation was done properly or not. + + + + Android + + + Write to temporary xml file + + + + + + + + Get the status whether updation was done properly or not. + + + + Android + + + Read from temporary xml file + + + + Reading the value from temporary config.xml. + + + + Android + + + Read from Original xml file + + + + Reading the value from temporary config.xml. + + + + Android + + + + + + + 5.3.0 + + + + diff --git a/docs/en/5.5/api/ConnectionChecking.md b/docs/en/5.5/api/ConnectionChecking.md new file mode 100644 index 00000000..45e7a752 --- /dev/null +++ b/docs/en/5.5/api/ConnectionChecking.md @@ -0,0 +1,15 @@ +#ConnectionChecking +
    +

    Example extension api

    +

    This is example of API. Implementation contain in extension.

    + + + +

    Properties

    + +

    hostURL : STRING Read Only

    The URL to be checked for connection

    +

    Property Access:

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

    message : STRING Read Only

    The message to be displayed during connection checking

    +

    Property Access:

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

    pollInterval : INTEGER Read Only

    The time gap between sucessive cheking.

    +

    Property Access:

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

    timeout : INTEGER Read Only

    The total time for checking the connection.

    +

    Property Access:

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

    trackConnection : INTEGER Read Only

    whether this feature to be implemeneted or not

    +

    Property Access:

    • Instance: This property can be accessed via an instance object of this class:
      • myObject.trackConnection
    \ No newline at end of file diff --git a/docs/en/5.5/api/ConnectionChecking.xml b/docs/en/5.5/api/ConnectionChecking.xml new file mode 100644 index 00000000..fcbabb66 --- /dev/null +++ b/docs/en/5.5/api/ConnectionChecking.xml @@ -0,0 +1,41 @@ + + + + + Example extension api + This is example of API. Implementation contain in extension. + + + + + + + + list of properties supported by instance of object + + The URL to be checked for connection + + + whether this feature to be implemeneted or not + + + The total time for checking the connection. + + + The time gap between sucessive cheking. + + + The message to be displayed during connection checking + + + + + + + + + 1.0.0 + + + + diff --git a/docs/en/5.5/api/Database.md b/docs/en/5.5/api/Database.md new file mode 100644 index 00000000..c4349053 --- /dev/null +++ b/docs/en/5.5/api/Database.md @@ -0,0 +1,140 @@ +#Database +
    +

    Database is low-level API to access SQLite local database.

    +

    This API used internally by RHOM. To use RHOM, just define your models and partition databases will be created automatically.

    + +

    Enabling the API

    + +

    This API is part of the coreapi extension that is included automatically.

    + +
    :::ruby
    +extensions: ["coreapi"]
    +
    + +

    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

    + +

    Destructor close()

    Closes the database. The database will not be accessible until it is opened again.

    +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method is a destructor and can only be accessed via the object that was created by the `new` constructor.
      • JavaScript: myObj.close()
      • Ruby: @myObj.close()

    commitTransaction()

    Replaces: commit

    Commit database transaction. Saves all updates to the database from the start of the transaction.

    +

    Synchronous Return:

    • Void

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.commitTransaction()

    destroyTable(STRING tableName)

    Destroys a database table.

    +

    Parameters

    • tableName : STRING

      Table name to destroy.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.destroyTable(STRING tableName)

    destroyTables(HASH propertyMap)

    Destroy a list of database tables.

    +

    Parameters

    • propertyMap : HASH

      • include : ARRAY

        Include tables.

        +

      • exclude : ARRAY

        Exclude tables.

        +

    Synchronous Return:

    • Void

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.destroyTables(HASH propertyMap)

    executeBatchSql(STRING sqlStmt)

    Execute a series of sql statements included in the sqlStmt string parameter.

    +

    Parameters

    • sqlStmt : STRING

      The SQL statement.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.executeBatchSql(STRING sqlStmt)

    executeSql(STRING sqlStmt, ARRAY args)

    Execute the sql statement specified in the method’s parameters.

    +

    Parameters

    • sqlStmt : STRING

      The SQL statement.

      +

    • args : ARRAY Optional

      Array of the sql expressions.

      +

    Synchronous Return:

    • ARRAY :

      Array of Hashes. Each Hash item represents record from Database.

      +

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.executeSql(STRING sqlStmt, ARRAY args)

    Constructor new Rho::Database(STRING dbPath, STRING dbPartition)

    This method is a constructor for this class. Instead of saying Rho.Database.initialize(dbPath,dbPartition) you would use new Rho.Database(dbPath,dbPartition). ex: var db = new Rho.Database(Rho.Application.databaseFilePath('test'), 'test'); Make sure you issue a .close() when you are finished using the database. If the database file does not exist it will be created using a SQL schema: rhodes\platform\shared\db\res\db\syncdb.schema. Do not use predefined partition names: app, user, local. Do not open the same database file in different partitions. Do not use the same partition for different database files. Do not open the same file twice.

    +

    Parameters

    • dbPath : STRING

      The path to the database. Databases stored at the path provided by Application.databaseFilePath.

      +

    • dbPartition : STRING

      The database partition. Used as a file name for database and when connecting to RhoConnect server.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method is a constructor and can only be accessed via the `new` construct.
      • JavaScript: var myObj = new Rho.Database(STRING dbPath, STRING dbPartition)
      • Ruby: @myObj = Rho::Database.new(STRING dbPath, STRING dbPartition)

    isTableExist(STRING tableName)

    Replaces: table_exist?

    Will return true or false if the specified table exists in the current database.

    +

    Parameters

    • tableName : STRING

      The name of the table.

      +

    Synchronous Return:

    • BOOLEAN

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.isTableExist(STRING tableName)

    rollbackTransaction()

    Replaces: rollback

    Rollback database transaction. This will cancel any pending actions to the database that were executed since the last Start and before a commit.

    +

    Synchronous Return:

    • Void

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.rollbackTransaction()

    startTransaction()

    Start database transaction. All operations will not be the saved to the database until a commit is executed.

    +

    Synchronous Return:

    • Void

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.startTransaction()
    + +

    Examples

    + +
    Using Transactions
    +

    To insert/update multiple object/models use database transactions. This is the most performant method to initialize your application with a large set of data.

    +
    :::javascript
    +
    +                
    +var db = Rho.Database;
    +db.startTransaction();
    +try
    +{
    +  for (var index in items) {
    +    // create hash of attribute/value pairs
    +    data = {
    +      field1 : item[index].value1,
    +      field2 : item[index].value2
    +    };
    +    // Creates a new itemModel object and saves it
    +    new_item = itemModel.create(data);
    +  }
    +
    + db.commitTransaction();
    +}
    +catch
    +{
    + db.rollbackTransaction();
    +}
    +
    +              
    :::ruby
    +
    +                
    +db = Rho::Database.new
    +db.startTransaction
    +begin
    +  items.each do |item|
    +    # create hash of attribute/value pairs
    +    data = {
    +      :field1 => item['value1'],
    +      :field2 => item['value2']
    +    }
    +    # Creates a new itemModel object and saves it
    +    new_item = itemModel.create(data)
    +  end
    +  db.commitTransaction
    +rescue
    +  db.rollbackTransaction
    +end
    +
    +              
    Open and close database
    +

    The following example opens the database using the constructor method: .initialize. It then closes the database using the destructor method .close()

    +
    :::javascript
    +
    +                
    +var db = new Rho.Database(Rho.Application.databaseFilePath('test'), 'test');
    +db.close();
    +
    +              
    :::ruby
    +
    +                
    +db = Rho::Database.new(Rho::Application.databaseFilePath('test'), 'test')
    +db.close()
    +
    +              
    destroyTables
    +

    Destroy multiple tables. The following example opens the database using the constructor method: .initialize.

    +
    :::javascript
    +
    +                
    +var db = new Rho.Database(...);
    +
    +// destroy all tables in database
    +db.destroyTables({include: [], exclude: []});
    +
    +// destroy specified tables
    +db.destroyTables({include: ['table1', 'table2'], exclude: []});
    +
    +// destroy all but specified tables
    +db.destroyTables({include: [], exclude: ['table1', 'table2']});
    +
    +              
    :::ruby
    +
    +                
    +db = Rho::Database.new(...)
    +
    +# destroy all tables in database
    +db.destroyTables(:include => [], :exclude => [])
    +
    +# destroy specified tables
    +db.destroyTables(:include => ['table1', 'table2'], :exclude => [])
    +
    +# destroy all but specified tables
    +db.destroyTables(:include => [], :exclude => ['table1', 'table2'])
    +
    +              
    \ No newline at end of file diff --git a/docs/en/5.5/api/Database.xml b/docs/en/5.5/api/Database.xml new file mode 100644 index 00000000..3dcea425 --- /dev/null +++ b/docs/en/5.5/api/Database.xml @@ -0,0 +1,297 @@ + + + + + Database is low-level API to access SQLite local database. + This API used internally by RHOM. To use RHOM, just define your models and partition databases will be created automatically. +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the Database API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Database API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.database.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + + + + + + + + + This method is a constructor for this class. Instead of saying Rho.Database.initialize(dbPath,dbPartition) you would use new Rho.Database(dbPath,dbPartition). ex: `var db = new Rho.Database(Rho.Application.databaseFilePath('test'), 'test');` Make sure you issue a `.close()` when you are finished using the database. If the database file does not exist it will be created using a SQL schema: rhodes\platform\shared\db\res\db\syncdb.schema. Do not use predefined partition names: app, user, local. Do not open the same database file in different partitions. Do not use the same partition for different database files. Do not open the same file twice. + This method is a constructor for this class. Instead of saying `EB.Database.initialize(dbPath,dbPartition)` you would use `new EB.Database(dbPath,dbPartition)`. ex: `var db = new EB.Database(EB.Application.databaseFilePath('test'), 'test');` Make sure you issue a `.close()` when you are finished using the database. If the database file does not exist it will be created using a default SQL schema. Do not use predefined partition names: app, user, local. Do not open the same database file in different partitions. Do not use the same partition for different database files. Do not open the same file twice. + + + The path to the database. Databases stored at the path provided by Application.databaseFilePath. + + + The database partition. Used as a file name for database and when connecting to RhoConnect server. + + + + + Closes the database. The database will not be accessible until it is opened again. + + + Start database transaction. All operations will not be the saved to the database until a commit is executed. + + + Commit database transaction. Saves all updates to the database from the start of the transaction. + + + Rollback database transaction. This will cancel any pending actions to the database that were executed since the last Start and before a commit. + + + Lock database. This method should be used to synchronize Database access with RhoConnect client. The startTransaction method also locks the database but if you're going to read from database, lockDb is faster. + + + Unlock database, previously locked by lockDb. + + + Indicates if UI waiting for DB? Should be used in separate thread, which updates database (implementing custom data sync logic). Will be true when database method calls from Main application thread and waits for database. + + + + Execute the sql statement specified in the method's parameters. + + + The SQL statement. + + + Array of the sql expressions. + + + + + Array of Hashes. Each Hash item represents record from Database. + + + + Execute a series of sql statements included in the sqlStmt string parameter. + + + The SQL statement. + + + + + Import the contents of the archived database into the current database. + + + The name of the zip file. + + + + + + Exports the contents of the current database to a file. + + + + Destroys a database table. + + + Table name to destroy. + + + + + Destroy a list of database tables. + + + + + Include tables. + + + Exclude tables. + + + + + + + Will return true or false if the specified table exists in the current database. + + + The name of the table. + + + + + + Set "do not backup attribute" for the database file. This is special flag set on files, which will exclude it from iCloud service. + iOS + + + + + + + + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + +
    + To insert/update multiple object/models use database transactions. This is the most performant method to initialize your application with a large set of data. + + + item['value1'], + :field2 => item['value2'] + } + # Creates a new itemModel object and saves it + new_item = itemModel.create(data) + end + db.commitTransaction +rescue + db.rollbackTransaction +end +]]> + + + + + +
    +
    +
    + + + +
    + The following example opens the database using the `constructor` method: .initialize. It then closes the database using the destructor method `.close()` + + + + + + + + +
    +
    +
    + + +
    + Destroy multiple tables. The following example opens the database using the `constructor` method: .initialize. + + + [], :exclude => []) + +# destroy specified tables +db.destroyTables(:include => ['table1', 'table2'], :exclude => []) + +# destroy all but specified tables +db.destroyTables(:include => [], :exclude => ['table1', 'table2']) +]]> + + + + + +
    +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/docs/en/5.5/api/EzNFC.md b/docs/en/5.5/api/EzNFC.md new file mode 100644 index 00000000..7d06c5ba --- /dev/null +++ b/docs/en/5.5/api/EzNFC.md @@ -0,0 +1,50 @@ +#EzNFC +
    +

    This API is used to enable/disable the NFC Adapter and read NFC Tags. The EzNFC API is currently supported on Android only.

    +

    Enabling the API

    + +

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

    + +
    extensions: ["eznfc"]
    +
    + + + +

    Methods

    + +

    disableRead()

    Disables NFC read of the application.

    +

    Synchronous Return:

    • Void

    Method Access:

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

    enableAdapter()

    Navigates to device NFC Adapter settings screen if device’s NFC Adapter is not enabled.

    +

    Synchronous Return:

    • Void

    Method Access:

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

    enableRead(CallBackHandler callback)

    Enables NFC read of the application if device supports NFC.

    +

    Parameters

    • callback : CallBackHandler Mandatory

    Async Callback Returning Parameters: HASH

      • Type : STRING

        The Type of NFC Tag that has been read

        +

      • ID : STRING

        The ID of the Tag that has been read

        +

      • Payload : STRING

        Payload is the data overall data of NFC Tag

        +

      • TNF : STRING

        TNF is last 3 bits of Payload

        +

      • EncodingFormat : STRING

        Text encoding format applied

        +

      • data : STRING

        The String data that is read from Tag

        +

      • TagIDHexa : STRING

        NFC Tag id in Hexacode

        +

    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.EzNFC.enableRead(CallBackHandler callback)
      • Ruby: Rho::EzNFC.enableRead(CallBackHandler callback)
    + +

    Properties

    + +

    isEnabled : BOOLEAN

    Detects whether the NFC Adapter is enabled. Returns true if the NFC Adapter is enabled.

    +

    Default: false

    Property Access:

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

    isSupported : BOOLEAN

    Determines whether NFC is supported on the device. Returns true if NFC is supported.

    +

    Default: false

    Property Access:

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

    Remarks

    + +
    General
      +
    1. NFC reads are only possible when the application is in the foreground.
    2. +
    3. It is mandatory to disable default NFC application of the device before using this API.
    4. +
    5. The APIs are designed to read NON-Secure NFC Tags.
    6. +
    7. The NFC APIs are designed to work in Reader Mode only.
    8. +
    + +
    Recommended order of API calls
      +
    1. EB.EzNFC.isSupported;
    2. +
    3. EB.EzNFC.isEnabled;
    4. +
    5. EB.EzNFC.enableAdapter();
    6. +
    7. EB.EzNFC.enableRead();
    8. +
    9. EB.EzNFC.disableRead();
    10. +
    + +
    \ No newline at end of file diff --git a/docs/en/5.5/api/EzNFC.xml b/docs/en/5.5/api/EzNFC.xml new file mode 100644 index 00000000..fa042081 --- /dev/null +++ b/docs/en/5.5/api/EzNFC.xml @@ -0,0 +1,272 @@ + + + + + This API is used to enable/disable the NFC Adapter and read NFC Tags. **The EzNFC API is currently supported on Android only**. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + extensions: ["eznfc"] + + +## Enabling the API +There are two ways to enable Enterprise Browser APIs: + +* Include all 'ebapi' modules +* Include only the API modules you need + +Both methods are explained below. + +Either way, the included files will be from: +`/Enterprise Browser/JavaScript Files/Enterprise Browser`, +a directory on the computer that contains the Enterprise Browser installation. + +### Include all JS API modules +To include all JavaScript APIs, copy the `ebapi-modules.js` file to a location accessible by your app's files and include the JavaScript modules file in your app. For instance, to include the modules file in your `index.html`, copy the file to the same directory as your index.html and add the following line to the HEAD section of your index.html file: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> This will define the EB class within the page. **Note that the path for this file is relative to the current page** (index.html). Any page on which the modules are required will need to have the required .js file(s) included in this fashion. + +### Include only the modules you need + +To include individual APIs, you must first include the `ebapi.js` in your HTML, and then the additional required API file(s). For instance, to use the EzNFC API, add the following code to the HTML file(s). Again, this assumes that relevant API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.eznfc.js"></script> + +> In the code lines above, notice that `ebapi.js` is included first, followed by `eb.eznfc.js`, which is the EzNFC API for Enterprise Browser. **This coding is required on each HTML page whenever an individual API will be called from that page**. + + + 1.4.0 + Android + + + + + + Android + Determines whether NFC is supported on the device. Returns true if NFC is supported. + Android + + + + Android + Detects whether the NFC Adapter is enabled. Returns true if the NFC Adapter is enabled. + Android + + + + + + + Navigates to device NFC Adapter settings screen if device's NFC Adapter is not enabled. + Android + + + + Enables NFC read of the application if device supports NFC. + Android + + List of callback data after the NFC Tag is read + + + The Type of NFC Tag that has been read + + + The ID of the Tag that has been read + + + Payload is the data overall data of NFC Tag + + + TNF is last 3 bits of Payload + + + Text encoding format applied + + + The String data that is read from Tag + + + NFC Tag id in Hexacode + + + + + + + + Disables NFC read of the application. + Android + + + + + + + + + + + + + + + + + + + + +
    + This example shows how to use the EzNFC API: + + + + Enterprise Browser NFC API Test + + + + +

    Enterprise Browser NFC API Test

    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + +
    + : +
    + : +
    + : +
    + :
    + :
    +
    +
    + + + ]]> +
    +
    +
    +
    +
    +
    +
    +
    diff --git a/docs/en/5.5/api/File.md b/docs/en/5.5/api/File.md new file mode 100644 index 00000000..f1436261 --- /dev/null +++ b/docs/en/5.5/api/File.md @@ -0,0 +1,136 @@ +#RhoFile +
    +

    This API provides several methods for access to files and folders found on the device’s local file system.

    +

    Use this API to access local files for reading and writing. Only string data can be read and written with this API. Please note that binary files are not supported. Strings filled with \0 will be truncated to the last non \0 character.

    + +

    Enabling the API

    + +

    This API is part of the coreapi extension that is included automatically.

    + +
    :::ruby
    +extensions: ["coreapi"]
    +
    + +

    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

    + +

    basename(STRING path)

    Return basename part for the specified path. Will remove any prefix up to the last path separator (‘/’ or ‘\’ depending on platform). Example: for path ‘/full/path/to/file.ext’ basename will return ‘file.ext’.

    +

    Parameters

    • path : STRING

      Absolute path for which basename is given.

      +

    Synchronous Return:

    • STRING :

      Basename part for the given path.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.basename(STRING path)
      • Ruby: Rho::RhoFile.basename(STRING path)

    Destructor close()

    Closes file. Once Close method is invoked, no file object will be alive.

    +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method is a destructor and can only be accessed via the object that was created by the `new` constructor.
      • JavaScript: myObj.close()
      • Ruby: @myObj.close()

    copy(STRING from, STRING to)

    Copies file from “from” (source) to “to” (destination).

    +

    Parameters

    • from : STRING

      File name to be copied.

      +

    • to : STRING

      Destination path.

      +

    Synchronous Return:

    • INTEGER :

      Error code raised during copy operation. 0 if no error.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.copy(STRING from, STRING to)
      • Ruby: Rho::RhoFile.copy(STRING from, STRING to)

    deleteDir(STRING path)

    Deletes specified directory. The specified directory must be empty to be deleted.

    +

    Parameters

    • path : STRING

      Absolute path to the directory to be deleted.

      +

    Synchronous Return:

    • INTEGER :

      Error code raised on directory deletion. 0 on success, -1 otherwise.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.deleteDir(STRING path)
      • Ruby: Rho::RhoFile.deleteDir(STRING path)

    deleteFile(STRING path)

    Deletes file.

    +

    Parameters

    • path : STRING

      Absolute path to the file to be deleted.

      +

    Synchronous Return:

    • INTEGER :

      Error code raised on file deletion. 0 on success, -1 otherwise.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.deleteFile(STRING path)
      • Ruby: Rho::RhoFile.deleteFile(STRING path)

    deleteRecursive(STRING path, BOOLEAN leaveRoot)

    Deletes all directory contents.

    +

    Parameters

    • path : STRING

      Absolute path to the directory.

      +

    • leaveRoot : BOOLEAN Optional Default: false

      Set to true if you only want to delete directory contents, but no the directory itself.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.deleteRecursive(STRING path, BOOLEAN leaveRoot)
      • Ruby: Rho::RhoFile.deleteRecursive(STRING path, BOOLEAN leaveRoot)

    dirname(STRING path)

    Returns directory name part of the specified path.

    +

    Parameters

    • path : STRING

      Absolute path to directory.

      +

    Synchronous Return:

    • STRING :

      Directory name.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.dirname(STRING path)
      • Ruby: Rho::RhoFile.dirname(STRING path)

    exists(STRING path)

    Checks if specified path exists.

    +

    Parameters

    • path : STRING

      Absolute path to file or directory.

      +

    Synchronous Return:

    • BOOLEAN :

      True if path exists, otherwise false.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.exists(STRING path)
      • Ruby: Rho::RhoFile.exists(STRING path)

    flush()

    Flushes all buffered data to the storage media.

    +

    Synchronous Return:

    • Void

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.flush()

    getFileSize(STRING path)

    Returns size of the file.

    +

    Parameters

    • path : STRING

      Absolute path to the file.

      +

    Synchronous Return:

    • INTEGER :

      File size in bytes.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.getFileSize(STRING path)
      • Ruby: Rho::RhoFile.getFileSize(STRING path)

    isDir(STRING path)

    Checks if specified path is a directory.

    +

    Parameters

    • path : STRING

      Absolute path of the directory.

      +

    Synchronous Return:

    • BOOLEAN :

      True if path is a directory. False otherwise.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.isDir(STRING path)
      • Ruby: Rho::RhoFile.isDir(STRING path)

    isFile(STRING path)

    Checks if specified path is a file.

    +

    Parameters

    • path : STRING

      Absolute path of the file.

      +

    Synchronous Return:

    • BOOLEAN :

      True if path is a file, false otherwise.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.isFile(STRING path)
      • Ruby: Rho::RhoFile.isFile(STRING path)

    isOpened()

    Checks if file is opened.

    +

    Synchronous Return:

    • BOOLEAN :

      True if file is opened, false otherwise.

      +

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.isOpened()

    join(STRING p1, STRING p2)

    Joins two parts of the path considering all necessary path delimiters. I.e.: join(‘/path/to’,‘file’) will return ‘/path/to/file’

    +

    Parameters

    • p1 : STRING

      First part of the path.

      +

    • p2 : STRING

      Second part of the path.

      +

    Synchronous Return:

    • STRING :

      Joined path.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.join(STRING p1, STRING p2)
      • Ruby: Rho::RhoFile.join(STRING p1, STRING p2)

    listDir(STRING path)

    Lists all entries of specified directory.

    +

    Parameters

    • path : STRING

      Absolute path to directory.

      +

    Synchronous Return:

    • ARRAY :

      Array of directory entry names. If directory is empty array of size 0 will be returned.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.listDir(STRING path)
      • Ruby: Rho::RhoFile.listDir(STRING path)

    makeDir(STRING path)

    Creates directory with the provided path. If all top-level nodes of the path doesn’t exists, directory will not be created.

    +

    Parameters

    • path : STRING

      Path to the new directory.

      +

    Synchronous Return:

    • INTEGER :

      Error code raised on directory creation. 0 on success, -1 otherwise.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.makeDir(STRING path)
      • Ruby: Rho::RhoFile.makeDir(STRING path)

    makeDirs(STRING path)

    Creates directory and all top-level directories if necessary. Subsequent isDir call is necessary to check if path was successfully created.

    +

    Parameters

    • path : STRING

      Absolute path to the directory to be created.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.makeDirs(STRING path)
      • Ruby: Rho::RhoFile.makeDirs(STRING path)

    Constructor new Rho::RhoFile(STRING path, INTEGER mode)

    Opens file in a mode specified by the “mode” parameter.

    +

    Parameters

    • path : STRING

      Absolute path to the file.

      +

    • mode : INTEGER

      Mode in which to open the file.

      +

      Possible Values :

      Constant: Rho::RhoFile.OPEN_FOR_APPEND (For Ruby use "::" for all "." when referencing constants)
      String:1

      Open file for output at the end of a file. The file is created if it does not exist.

      +
      Constant: Rho::RhoFile.OPEN_FOR_READ (For Ruby use "::" for all "." when referencing constants)
      String:2

      Open file for read-only operations. The file must exist.

      +
      Constant: Rho::RhoFile.OPEN_FOR_WRITE (For Ruby use "::" for all "." when referencing constants)
      String:3

      Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.

      +
      Constant: Rho::RhoFile.OPEN_FOR_READ_WRITE (For Ruby use "::" for all "." when referencing constants)
      String:4

      Open a file for update (both for read and write). The file must exist.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method is a constructor and can only be accessed via the `new` construct.
      • JavaScript: var myObj = new Rho.RhoFile(STRING path, INTEGER mode)
      • Ruby: @myObj = Rho::RhoFile.new(STRING path, INTEGER mode)

    read(STRING path)

    Reads specified file to a string object.

    +

    Parameters

    • path : STRING

      Absolute path to file.

      +

    Synchronous Return:

    • STRING :

      File contents.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.read(STRING path)
      • Ruby: Rho::RhoFile.read(STRING path)

    read(INTEGER size)

    Reads specified number of characters from current position of the file.

    +

    Parameters

    • size : INTEGER

      Number of characters to be read.

      +

    Synchronous Return:

    • STRING :

      String from current position of file containing specified number of characters.

      +

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.read(INTEGER size)

    readAll()

    Reads all file contents to the string object.

    +

    Synchronous Return:

    • STRING :

      Contents of the file.

      +

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.readAll()

    rename(STRING from, STRING to)

    Renames / moves file.

    +

    Parameters

    • from : STRING

      Original path / name.

      +

    • to : STRING

      New path / name.

      +

    Synchronous Return:

    • INTEGER :

      Error code raised on move / rename. 0 on success, -1 otherwise.

      +

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoFile.rename(STRING from, STRING to)
      • Ruby: Rho::RhoFile.rename(STRING from, STRING to)

    seek(INTEGER pos)

    Sets file position to specified value from the beginning of the file.

    +

    Parameters

    • pos : INTEGER

      Position within the file.

      +

    Synchronous Return:

    • Void

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.seek(INTEGER pos)

    size()

    Returns file size.

    +

    Synchronous Return:

    • INTEGER :

      File size in bytes.

      +

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.size()

    write(STRING val)

    Writes the provided string at current position in the file.

    +

    Parameters

    • val : STRING

      String to be written to the file.

      +

    Synchronous Return:

    • INTEGER :

      Number of bytes written.

      +

    Method Access:

    • Instance Method: This method can be accessed via an instance object of this class:
      • myObject.write(STRING val)
    + +

    Examples

    + +
    List contents of a folder
    +

    Iterate through the contents of a folder and divide the entries in “folders” and “files”.

    +
    :::javascript
    +
    +           
    +var folders = [];
    +var files = [];
    +var root_path = "/arbitrary/path"
    +var entries = Rho.RhoFile.listDir(root_path);
    +
    +for (var i = 0; i < entries.length; i++) {
    +  var entry = entries[i];
    +  if ((entry != ".") && (entry != "..")) {
    +
    +    (Rho.RhoFile.isDir(Rho.RhoFile.join(root_path, entry)) ? folders : files).push(entry);
    +  }
    +}
    +                   
    +                 
    :::ruby
    +
    +           
    +folders = []
    +files = []
    +
    +root_path = "/arbitrary/path"
    +entries = Rho::RhoFile.listDir(root_path)
    +
    +entries.each do |entry|
    +  unless (entry == "." || entry == "..")
    +    (Rho::RhoFile.isDir(Rho::RhoFile.join(root_path,entry)) ? folders : files) << entry
    +  end
    +end
    +                   
    +                 
    \ No newline at end of file diff --git a/docs/en/5.5/api/File.xml b/docs/en/5.5/api/File.xml new file mode 100644 index 00000000..40b20f66 --- /dev/null +++ b/docs/en/5.5/api/File.xml @@ -0,0 +1,401 @@ + + + + + This API provides several methods for access to files and folders found on the device's local file system. + Use this API to access local files for reading and writing. Only string data can be read and written with this API. Please note that binary files are not supported. Strings filled with \0 will be truncated to the last non \0 character. +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the RhoFile API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the RhoFile API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.file.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + + + + + Opens file in a mode specified by the "mode" parameter. + + + Absolute path to the file. + + + Mode in which to open the file. + + + Open file for output at the end of a file. The file is created if it does not exist. + + + Open file for read-only operations. The file must exist. + + + Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. + + + Open a file for update (both for read and write). The file must exist. + + + + + + + + Closes file. Once Close method is invoked, no file object will be alive. + + + + Checks if file is opened. + + True if file is opened, false otherwise. + + + + + Reads specified number of characters from current position of the file. + + + Number of characters to be read. + + + + String from current position of file containing specified number of characters. + + + + + Reads all file contents to the string object. + + Contents of the file. + + + + + Writes the provided string at current position in the file. + + + String to be written to the file. + + + + Number of bytes written. + + + + + Flushes all buffered data to the storage media. + + + + Sets file position to specified value from the beginning of the file. + + + Position within the file. + + + + + + Returns file size. + + File size in bytes. + + + + + + Copies file from "from" (source) to "to" (destination). + + + File name to be copied. + + + Destination path. + + + + Error code raised during copy operation. 0 if no error. + + + + + Renames / moves file. + + + Original path / name. + + + New path / name. + + + + Error code raised on move / rename. 0 on success, -1 otherwise. + + + + + Creates directory with the provided path. If all top-level nodes of the path doesn't exists, directory will not be created. + + + Path to the new directory. + + + + Error code raised on directory creation. 0 on success, -1 otherwise. + + + + + Checks if specified path exists. + + + Absolute path to file or directory. + + + + True if path exists, otherwise false. + + + + + Returns size of the file. + + + Absolute path to the file. + + + + File size in bytes. + + + + + Checks if specified path is a directory. + + + Absolute path of the directory. + + + + True if path is a directory. False otherwise. + + + + + Checks if specified path is a file. + + + Absolute path of the file. + + + + True if path is a file, false otherwise. + + + + + Deletes file. + + + Absolute path to the file to be deleted. + + + + Error code raised on file deletion. 0 on success, -1 otherwise. + + + + + + Deletes specified directory. The specified directory must be empty to be deleted. + + + Absolute path to the directory to be deleted. + + + + Error code raised on directory deletion. 0 on success, -1 otherwise. + + + + + Creates directory and all top-level directories if necessary. Subsequent isDir call is necessary to check if path was successfully created. + + + Absolute path to the directory to be created. + + + + + + Deletes all directory contents. + + + Absolute path to the directory. + + + Set to true if you only want to delete directory contents, but no the directory itself. + + + + + + + Lists all entries of specified directory. + + + Absolute path to directory. + + + + Array of directory entry names. If directory is empty array of size 0 will be returned. + + + + + + + + Return basename part for the specified path. Will remove any prefix up to the last path separator ('/' or '\' depending on platform). Example: for path '/full/path/to/file.ext' basename will return 'file.ext'. + + + Absolute path for which basename is given. + + + + Basename part for the given path. + + + + + Returns directory name part of the specified path. + + + Absolute path to directory. + + + + Directory name. + + + + + Joins two parts of the path considering all necessary path delimiters. I.e.: join('/path/to','file') will return '/path/to/file' + + + First part of the path. + + + Second part of the path. + + + + Joined path. + + + + + Reads specified file to a string object. + + + Absolute path to file. + + + + File contents. + + + + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + +
    + Iterate through the contents of a folder and divide the entries in "folders" and "files". + + + + + + + + +
    +
    +
    +
    +
    +
    diff --git a/docs/en/5.5/api/Intent.md b/docs/en/5.5/api/Intent.md new file mode 100644 index 00000000..a9017aa4 --- /dev/null +++ b/docs/en/5.5/api/Intent.md @@ -0,0 +1,131 @@ +#Intent +
    +

    The Intent API provides an inter-application broadcast message-passing framework.

    +

    Enabling the API

    + +

    This API is part of the coreapi extension that is included automatically.

    + +
    :::ruby
    +extensions: ["coreapi"]
    +
    + +

    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

    + +

    send(HASH params, CallBackHandler callback)

    Sends an intent. The receiver of the intent can either be another RhoMobile application that is listening for this Intent characteristic or on Android can be a native Android application setup with an Intent-Filter that will trigger based on the parameters of this method.

    + +

    Android Note: On Android, the callback should be used only when the intentType is set to START_ACTIVITY. The only valid way for an Android app to pass a private file from a package directly to another application is to set the ‘uri’ parameter with content URI:

    + +

    Sample JavaScript:

    + +
    :::javascript
    +var params = {
    +    intentType: Rho.Intent.START_ACTIVITY,
    +    action: "ACTION_VIEW",
    +    uri: "content://com.rhomobile.sample/rhodata/apps/public/sample.pdf"
    +}
    +Rho.Intent.send(params);
    +
    + +

    In most cases the extension of the exported file also must be added to the ‘android:no_compression’ list in the build.yml:

    + +

    Sample Build.yml

    + +
    :::ruby
    +android:
    +  no_compression: ['pdf','html','css']
    +
    +

    Parameters

    • params : HASH

      A hash-map with intent parameters.

      +

      • intentType : STRING

        Type of Intent to send.

        +

        Possible Values :

        Constant: Intent.BROADCAST (For Ruby use "::" for all "." when referencing constants)
        String:broadcast

        Use the intent as broadcast intent.

        +
        Constant: Intent.START_ACTIVITY (For Ruby use "::" for all "." when referencing constants)
        String:startActivity

        Use the intent to start a UI activity.

        + Platforms:

        Android

        +
        Constant: Intent.START_SERVICE (For Ruby use "::" for all "." when referencing constants)
        String:startService

        Use the intent to start a background service.

        + Platforms:

        Android

        +
      • permission : STRING

        Permission used to send a broadcast intent.

        + Platforms:Android

      • action : STRING

        Intent action. See Android docs for possible values. Use the Constant Value instead of the actual Constant Name. For example, for the Constant ACTION_PICK use ‘android.intent.action.PICK’ instead.

        + Platforms:Android

      • categories : ARRAY

        List of intent categories. See Android docs for possible values. Use the Constant Value instead of the actual Constant Name. For example, for the Constant CATEGORY_HOME use ‘android.intent.category.HOME’ instead.

        + Platforms:Android

        • Object : STRING

      • appName : STRING

        Explicit name of the application to run on the device. The platform will determine the value to use.

        + +
          +
        • iOS it is BundleURLScheme of executed application.
        • +
        • Android it is application package name.
        • +
        • Windows it is the application/executable name. For shared runtime based applications, the application name is taken from the “Name” attribute from the Config.xml file. Hence use the application name which is mentioned in config.xml.
        • +
        + +

      • targetClass : STRING

        Explicit name of the class in the application that will receive the intent. Must be specified if and only if ‘appName’ is defined.

        + Platforms:Android

      • uri : STRING

        Open the application associated with the URI. Behavior may be different on different platforms and on software installed. For example, open URL with ‘http://’ prefix usually executes the Web Browser installed on system and opens the URL in that browser. On Android, this is similar to Intent.setData(). For example, if sending a <![CDATA[ Map Intent, you might set this value to something like ‘geo:47.6,-122.3.’

        +

      • mimeType : STRING

        MIME type of data defined in the intent. For example, for Plain Text one would use ‘text/plain.’ On Android, this is similar to Intent.setType.

        +

      • data : HASH

        Data to be sent within the intent. On Android, this is similar to Intent.putExtra, and ‘data’ should contain a HASH of Extra-String/Value pairs. The ‘Value’ type of the ‘Extra’ can be a String, Integer, Boolean or Double. Other object types are not supported at this time. For sample code, please refer to examples section, below. Use the full constant string ‘android.intent.extra.TEXT’ in place of Intent.EXTRA_TEXT.

        +

    • callback : CallBackHandler Optional

    Async Callback Returning Parameters: HASH

      • responseCode : INTEGER

        Response code passed to Android Activity.setResult() method. RESULT_OK = -1. Check Android Docs for more information. Other attributes, such as ‘uri’ may be returned depending on the Intent that was triggered. Possible parameters include the same params that are used in this ‘send(params)’ method.

        + Platforms:Android

    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.Intent.send(HASH params, CallBackHandler callback)
      • Ruby: Rho::Intent.send(HASH params, CallBackHandler callback)

    startListening(CallBackHandler callback)

    Start listening for custom intents.

    + +

    For Android, this is how we have implemented Android Intent Filters. In order to listen for Intents you will have to update the AndroidManifest.erb file and add a special section to it. This file is now generated with RhoMobile Version 4.1 when you create a new project. The file is located in the root of project.

    + +

    Add the following snippet to AndroidManifest.erb within the manifest tags

    + +
    :::xml
    +<receiver android:name='com.rho.intent.IntentReceiver'>
    +  <intent-filter>
    +    <action android:name="Intent.ACTION_BATTERY_CHANGED" />
    +  </intent-filter>
    +</receiver>
    +
    + +

    Notice that this looks very similar to a standard AndroidManifest.XML file section except the receiver is the common RhoMobile intent receiver. The intent-filter tags within this section are standard AndroidManifest.XML notation that you would put in for the Intent-Filters that you want to listen for. Consult the Android Docs for more information about Intent Filters. From your Android application, you would use the sendBroadcast() method with the appropriate parameters for this filter.

    +

    Parameters

    • callback : CallBackHandler Mandatory

    Async Callback Returning Parameters: HASH

      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.Intent.startListening(CallBackHandler callback)
        • Ruby: Rho::Intent.startListening(CallBackHandler callback)

      stopListening()

      Stop listening for custom intents.

      +

      Synchronous Return:

      • Void

      Method Access:

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

      Examples

      + +
      Plot a location on a map
      +

      You can use the Intent API to use the default mapping program to plot locations.

      +
      :::javascript
      +
      +function sendGeo(){
      +  var intentParams = {action     : "android.intent.action.VIEW",
      +                      intentType : Rho.Intent.START_ACTIVITY,
      +                      uri        : "geo:37.422, -122.084"};
      +
      +  Rho.Intent.send(intentParams);
      +}
      :::ruby
      +
      +def send_geo
      +  intent_params = {:action     => "android.intent.action.VIEW",
      +                   :intentType => Rho::Intent::START_ACTIVITY,
      +                   :uri        => "geo:37.422, -122.084"}
      +
      +  Rho::Intent.send intent_params
      +end
      Sending Extras
      +

      Sometimes you will want to send some extras along with an intent such as an SMS body or do a web search with a given string. Here is an example of an intent that will launch the default web browser and perform a search with the default search engine.

      +
      :::javascript
      +
      +function webSearch(){}
      +  var intentParams = {action     : "android.intent.action.WEB_SEARCH",
      +                      intentType : Rho.Intent.START_ACTIVITY,
      +                      data       : {query : "Rhomobile docs"}}
      +
      +  Rho.Intent.send(intentParams)
      +}
      :::ruby
      +
      +def web_search
      +  intent_params = { :action     => "android.intent.action.WEB_SEARCH",
      +                    :intentType => Rho::Intent::START_ACTIVITY,
      +                    :data       => { :query => "Rhomobile docs" } }
      +
      +  Rho::Intent.send intent_params
      +end
      + +

      Remarks

      + +
      Registering Intent Receiver

      For an Android app to receive intent data, the Intent receiver must be registered in the app’s AndroidManifest.erb file. Please refer to the Intent Guide for more information.

      +
      \ No newline at end of file diff --git a/docs/en/5.5/api/Intent.xml b/docs/en/5.5/api/Intent.xml new file mode 100644 index 00000000..a58114f7 --- /dev/null +++ b/docs/en/5.5/api/Intent.xml @@ -0,0 +1,297 @@ + + + + + The Intent API provides an inter-application broadcast message-passing framework. + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API + +There are two methods of enabling the Intent API: + +* Include all 'ebapi' modules +* Include only the API modules you need + +Both methods are explained below. + +Either way, the included files will be found in: +`/Enterprise Browser/JavaScript Files/Enterprise Browser`, +a directory on the computer that contains the Enterprise Browser installation. + +### Include all JS API modules +To include all JavaScript APIs, copy the `ebapi-modules.js` file to a location accessible by your app's files and include the JavaScript modules file in your app. For instance, to include the modules file in your `index.html`, copy the file to the same directory as your index.html and add the following line to the HEAD section of your index.html file: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> This will define the EB class within the page. **Note that the path for this file is relative to the current page** (index.html). Any page on which the modules are required will need to have the required .js file(s) included in this fashion. + +### Include only the modules you need +To include individual APIs, you must first include the `ebapi.js` in your HTML, and then the additional required API file(s). For instance, to use the Intent API, add the following code to the HTML file(s). Again, this assumes that relevant API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.intent.js"></script> + +> In the code lines above, notice that `ebapi.js` is included first, followed by `eb.intent.js`, which is the Intent API for Enterprise Browser. **This coding is required on each HTML page whenever an individual API will be called from that page**. + + + + + + + Sends an intent. The receiver of the intent can either be another RhoMobile application that is listening for this Intent characteristic or on Android can be a native Android application setup with an Intent-Filter that will trigger based on the parameters of this method. + +**Android Note**: On Android, the callback should be used only when the intentType is set to START_ACTIVITY. The only valid way for an Android app to pass a private file from a package directly to another application is to set the 'uri' parameter with content URI: + +Sample JavaScript: + + :::javascript + var params = { + intentType: Rho.Intent.START_ACTIVITY, + action: "ACTION_VIEW", + uri: "content://com.rhomobile.sample/rhodata/apps/public/sample.pdf" + } + Rho.Intent.send(params); + +In most cases the extension of the exported file also must be added to the 'android:no_compression' list in the `build.yml:` + + +Sample Build.yml + + :::ruby + android: + no_compression: ['pdf','html','css'] + + + + Sends an intent. The receiver of the intent can be another application that is listening for this Intent characteristic or, on Android, the receiver can be a native Android application set up with an Intent-Filter that will trigger based on the parameters of this method. + +**Android Note**: On Android, the callback should be used only when the intentType is set to START_ACTIVITY. The only valid way for an Android app to pass a private file from a package directly to another application is to set the 'uri' parameter with content URI. + + + + A hash-map with intent parameters. + + + Type of Intent to send. + + + Use the intent as broadcast intent. + + + Use the intent to start a UI activity. + Android + + + Use the intent to start a background service. + Android + + + + + Android + Permission used to send a broadcast intent. + + + Android + Intent action. See Android docs]]> for possible values. Use the Constant Value instead of the actual Constant Name. For example, for the ConstantACTION_PICK]]> use 'android.intent.action.PICK' instead. + + + + + Android + List of intent categories. See Android docs ]]> for possible values. Use the Constant Value instead of the actual Constant Name. For example, for the Constant CATEGORY_HOME ]]> use 'android.intent.category.HOME' instead. + + + + + + Explicit name of the application to run on the device. The platform will determine the value to use. + +* iOS it is BundleURLScheme of executed application. +* Android it is application package name. +* Windows it is the application/executable name. For shared runtime based applications, the application name is taken from the "Name" attribute from the Config.xml file. Hence use the application name which is mentioned in config.xml. + + Explicit name of the application to run on the device. The platform will determine the value to use. + + + + + + Android + Explicit name of the class in the application that will receive the intent. Must be specified if and only if 'appName' is defined. + + + Open the application associated with the URI. Behavior may be different on different platforms and on software installed. For example, open URL with 'http://' prefix usually executes the Web Browser installed on system and opens the URL in that browser. On Android, this is similar to Intent.setData(). For example, if sending a Map Intent, you might set this value to something like 'geo:47.6,-122.3.']]> + + + + MIME type of data defined in the intent. For example, for Plain Text one would use 'text/plain.' On Android, this is similar to Intent.setType.]]> + + + + Data to be sent within the intent. On Android, this is similar to Intent.putExtra, and 'data' should contain a HASH of Extra-String/Value pairs. The 'Value' type of the 'Extra' can be a String, Integer, Boolean or Double. Other object types are not supported at this time. For sample code, please refer to examples section, below. Use the full constant string 'android.intent.extra.TEXT' in place of Intent.EXTRA_TEXT.]]> + + + + + + + + Same format as 'params' argument and some additional values described below. + Android: Developer has to ensure that the response is addressed to this call because of possible conflicts in integer request code with other extensions. + + + Android + Response code passed to Android Activity.setResult() method. RESULT_OK = -1. Check Android Docs]]> for more information. Other attributes, such as 'uri' may be returned depending on the Intent that was triggered. Possible parameters include the same params that are used in this 'send(params)' method. + + + + + + + Start listening for custom intents. + Start listening for custom intents. + +For Android, this is how we have implemented [Android Intent Filters](http://developer.android.com/guide/components/intents-filters.html#Receiving). In order to listen for Intents you will have to update the `AndroidManifest.erb` file and add a special section to it. This file is now generated with RhoMobile Version 4.1 when you create a new project. The file is located in the root of project. + +Add the following snippet to AndroidManifest.erb within the `manifest` tags + + + + + +]]> + +Notice that this looks very similar to a standard AndroidManifest.XML file section except the `receiver` is the common RhoMobile intent receiver. The `intent-filter` tags within this section are standard AndroidManifest.XML notation that you would put in for the Intent-Filters that you want to listen for. Consult the [Android Docs](http://developer.android.com/guide/components/intents-filters.html#Receiving) for more information about Intent Filters. From your Android application, you would use the [sendBroadcast() method](http://developer.android.com/reference/android/content/Context.html#sendBroadcast(android.content.Intent\)) with the appropriate parameters for this filter. + + + Same format as 'params' argument passed to Rho.Intent.send method + Android: Developer has to ensure that an intent passed to handler is what he intended to proceed since any other intent may also be passed here. + + Android, WM + + + Stop listening for custom intents. + + + + + + Intent Guide for more information. + ]]> + + + Intent section of the EB Config Reference for more information. + ]]> + + + + 4.1.0 + iOS, WM, Android + Android, WM + + + +
      + You can use the Intent API to use the default mapping program to plot locations. + + +def send_geo + intent_params = {:action => "android.intent.action.VIEW", + :intentType => Rho::Intent::START_ACTIVITY, + :uri => "geo:37.422, -122.084"} + + Rho::Intent.send intent_params +end + +function sendGeo(){ + var intentParams = {action : "android.intent.action.VIEW", + intentType : Rho.Intent.START_ACTIVITY, + uri : "geo:37.422, -122.084"}; + + Rho.Intent.send(intentParams); +} + +
      +
      +
      + + +
      + Sometimes you will want to send some extras along with an intent such as an SMS body or do a web search with a given string. Here is an example of an intent that will launch the default web browser and perform a search with the default search engine. + + +def web_search + intent_params = { :action => "android.intent.action.WEB_SEARCH", + :intentType => Rho::Intent::START_ACTIVITY, + :data => { :query => "Rhomobile docs" } } + + Rho::Intent.send intent_params +end + +function webSearch(){} + var intentParams = {action : "android.intent.action.WEB_SEARCH", + intentType : Rho.Intent.START_ACTIVITY, + data : {query : "Rhomobile docs"}} + + Rho.Intent.send(intentParams) +} + +
      +
      +
      +
      + + + +
      + This example shows how to send data within an intent. On Android, this is similar to Intent.putExtra. Data should contain a HASH of Extra-String/Value pairs. The 'Value' type of the 'Extra' can be a String, Integer, Boolean or Double. Notice the use of the full constant string 'android.intent.extra.TEXT' in place of Intent.EXTRA_TEXT.]]> + + + + + +
      +
      +
      +
      + +
      +
      diff --git a/docs/en/5.5/api/Log.md b/docs/en/5.5/api/Log.md new file mode 100644 index 00000000..688c26fb --- /dev/null +++ b/docs/en/5.5/api/Log.md @@ -0,0 +1,180 @@ +#Log +
      +

      Use this API to control the behavior of the RhoMobile Log API as well as access it. This API gives access to the Logging functionality. There are five functions to add messages to the log with different severity (from lowest to highest) : trace, info, warning, error and fatal. Each of those functions gets two parameters: message and category. Category is an user defined group that helps with used searching and filtering.

      + +

      Accessing Log File: +sendLogFile: will sent all the log to server +showLog: brings up popup with log, +readLogFile: returns the full log file, +cleanLogFile: removes all logged messages

      + +

      Filtering:

      + +
        +
      • Using level property: It limits minimal severity of messages that will be added to log. For example: setting log level to 2 (warning) will filter out messages generated by trace and info.

      • +
      • Categories: user defined groups that are used to select messages from different modules for ease of use. There are two main filters: includeCategories and excludeCategories. They are both active at the same time. includeCategories allows to select groups/categories that should be in the log (setting this property to empty will turn disable logging). excludeCategories is used for filtering out some of categories.

      • +
      • excludeFilter, this filter is used to remove all sensitive information like passwords, security tokens from log.

      • +
      + + +

      Log destinations (any combinations of them):

      + +
        +
      • debug console (stdio),
      • +
      • device filesystem (file)
      • +
      • remote sever (url)
      • +
      + +

      Enabling the API

      + +

      This API is part of the coreapi extension that is included automatically.

      + +
      :::ruby
      +extensions: ["coreapi"]
      +
      + +

      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

      + +

      cleanLogFile()

      Clean log file, all logged messages will be removed.

      +

      Synchronous Return:

      • Void

      Method Access:

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

      error(STRING message, STRING category)

      Log message at the Error level.

      +

      Parameters

      • message : STRING

        Log message.

        +

      • category : STRING Default: APP

        Log category.

        +

      Synchronous Return:

      • Void

      Method Access:

      • Class Method: This method can only be accessed via the API class object.
        • JavaScript: Rho.Log.error(STRING message, STRING category)
        • Ruby: Rho::Log.error(STRING message, STRING category)

      fatalError(STRING message, STRING category)

      Log message at the FatalError level. Application will be terminated (on all platforms except iOS).

      +

      Parameters

      • message : STRING

        Log message.

        +

      • category : STRING Default: APP

        Log category.

        +

      Synchronous Return:

      • Void

      Method Access:

      • Class Method: This method can only be accessed via the API class object.
        • JavaScript: Rho.Log.fatalError(STRING message, STRING category)
        • Ruby: Rho::Log.fatalError(STRING message, STRING category)

      info(STRING message, STRING category)

      Log message at the Info level.

      +

      Parameters

      • message : STRING

        Log message.

        +

      • category : STRING Default: APP

        Log category.

        +

      Synchronous Return:

      • Void

      Method Access:

      • Class Method: This method can only be accessed via the API class object.
        • JavaScript: Rho.Log.info(STRING message, STRING category)
        • Ruby: Rho::Log.info(STRING message, STRING category)

      readLogFile(INTEGER limit)

      Read log file. Returns string from the log file containing specified number of symbols.

      +

      Parameters

      • limit : INTEGER

        Maximum size of the resulting string in symbols.

        +

      Synchronous Return:

      • STRING

      Method Access:

      • Class Method: This method can only be accessed via the API class object.
        • JavaScript: Rho.Log.readLogFile(INTEGER limit)
        • Ruby: Rho::Log.readLogFile(INTEGER limit)

      sendLogFile(CallBackHandler callback)

      Send log file to destinationURI property. Please note that this procedure is blocking and will stop any logging while log file is being send.

      +

      Parameters

      • callback : CallBackHandler Optional

      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.Log.sendLogFile(CallBackHandler callback)
        • Ruby: Rho::Log.sendLogFile(CallBackHandler callback)

      showLog()

      Display Log view window.

      +

      Synchronous Return:

      • Void

      Method Access:

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

      trace(STRING message, STRING category)

      Log message at the Trace level. By default trace messages are not shown in log (if level equals to 1).

      +

      Parameters

      • message : STRING

        Log message.

        +

      • category : STRING Default: APP

        Log category.

        +

      Synchronous Return:

      • Void

      Method Access:

      • Class Method: This method can only be accessed via the API class object.
        • JavaScript: Rho.Log.trace(STRING message, STRING category)
        • Ruby: Rho::Log.trace(STRING message, STRING category)

      warning(STRING message, STRING category)

      Log message at the Warning level.

      +

      Parameters

      • message : STRING

        Log message.

        +

      • category : STRING Default: APP

        Log category.

        +

      Synchronous Return:

      • Void

      Method Access:

      • Class Method: This method can only be accessed via the API class object.
        • JavaScript: Rho.Log.warning(STRING message, STRING category)
        • Ruby: Rho::Log.warning(STRING message, STRING category)
      + +

      Properties

      + +

      destination : ARRAY

      List of log destinations that are being used. Destination could be set to empty (disable all logging), Logging to several destinations could be set by setting destination to comma separated list in any order (for example “stdio,file”). By default logging to console can be enabled from rhoconfig.txt (LogToOutput = 1). After Rhodes initialization logging to file is enabled automatically.

      +

      Possible Values (STRING):

      Constant: Rho.Log.DEST_FILE (For Ruby use "::" for all "." when referencing constants)
      String: file

      Log is written to a local file on the device (typically rholog.txt)

      +
      Constant: Rho.Log.DEST_OUTPUT (For Ruby use "::" for all "." when referencing constants)
      String: stdio

      Log is written to the standard output (ex: Android ADB)

      +
      Constant: Rho.Log.DEST_URI (For Ruby use "::" for all "." when referencing constants)
      String: uri

      Log is written to a remote logger.

      +

      Property Access:

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

      destinationURI : STRING

      Log server URI where log will be posted by using Rho::Log.sendLogFile or from the log view. Log server source code is open and available at http://github.com/rhomobile/rhologs, so you can deploy your own logserver. URI format: ‘http://host:port[/path][?log_name=appName]’. Default value is set in rhoconfig.txt (logserver)

      +

      Property Access:

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

      excludeCategories : STRING

      Comma-separated list of excluded log categories. Set to ‘’ (empty) to allow all messages to be logged. Set to concrete value to filter out log from those categories. Default value is ‘’ (empty), it is set in rhoconfig.txt (ExcludeLogCategories)

      +

      Property Access:

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

      excludeFilter : STRING

      Define exclude parameters log filter(for security reasons) – parameter names separated by comma. It works when user tries to put in log string containing json / urls. Default value is “” (empty). For example, if user set excludeFilter=“password”, then tries to put in log this string: “{"user”:“alex”,“password”:“abcdef”,“sessionid”:123456}“, "abcdef” will not appear in log.

      +

      Property Access:

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

      filePath : STRING

      Path to the log file including file name. The path is relative to the platform specific application root or start if from ‘/’ if you wish to store elsewhere (‘/mnt/sdcard/myapp.log’). Default file path is “rholog.txt”

      +

      Default: rholog.txt

      Property Access:

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

      fileSize : INTEGER

      Maximum log file size in bytes, set 0 to unlimited size; when limit is reached, log wraps to beginning of file. Default value is 50000, it is set in rhoconfig.txt (MaxLogFileSize)

      +

      Default: 50000

      Property Access:

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

      includeCategories : STRING

      Comma-separated list of included log categories. Set to ‘*’ (asterisk) to log all categories. Set to ‘’ (empty) to filter out all messages. Default value is ‘*’ (asterisk), it is set in rhoconfig.txt (LogCategories).

      +

      Default: *

      Property Access:

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

      level : INTEGER

      The current logging level. Minimal severity level of messages that will appear in log. When level is set to 0 any messages will be logged. When level is set to 4 only fatal error messages will be logged. Default value is defined in rhoconfig.txt (MinSeverity)

      +

      Possible Values (STRING):

      Constant: Rho.Log.LEVEL_TRACE (For Ruby use "::" for all "." when referencing constants)
      String: 0

      Everything will be logged. Also see settings for controlling log size.

      +
      Constant: Rho.Log.LEVEL_INFO (For Ruby use "::" for all "." when referencing constants)
      String: 1

      Information level logs and above will be shown.

      +
      Constant: Rho.Log.LEVEL_WARNING (For Ruby use "::" for all "." when referencing constants)
      String: 2

      Warnings and above will only be shown.

      +
      Constant: Rho.Log.LEVEL_ERROR (For Ruby use "::" for all "." when referencing constants)
      String: 3

      Error level log messages and above will be shown.

      +
      Constant: Rho.Log.LEVEL_FATAL (For Ruby use "::" for all "." when referencing constants)
      String: 4

      Fatal level log messages and above will be shown.

      +

      Property Access:

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

      memoryPeriod : INTEGER

      Enables the logging of memory usage in the system; specifies the time interval in milliseconds at which memory logs will be generated periodically. Setting it to 0 will disable logging memory information.

      +

      Default: 0

      Property Access:

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

      netTrace : BOOLEAN

      Turn on remote network traces regardless of log level set (e.g. Network, asyncHttp). Traces contain information about connection process, sent and received headers and data. Please note that this parameter will not take an effect in case of local server app (and / or shared runtime). Default value can be overridden by the setting in rhoconfig.txt (net_trace). To get local server trace, use Rho.Log.LEVEL_TRACE in JavaScript and Rho::Log::LEVEL_TRACE in Ruby.

      +

      Default: false

      Property Access:

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

      skipPost : BOOLEAN

      Skip http package body from log(for security reasons). Please note that this parameter will not take an effect in case of remote server app (and / or shared runtime), no log will appear in this case.

      +

      Default: false

      Property Access:

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

      Examples

      + +
      Show log file
      +

      Show the contents of the log file in a window with controls to refresh, clear and send. Useful for debugging and when asking users to report error messages.

      +
      :::javascript
      +
      +           
      +Rho.Log.showLog();
      +                
      :::ruby
      +
      +           
      +Rho::Log.showLog
      +                
      Read log file content
      +

      Retrieve the contents of the log file as a string.

      +
      :::javascript
      +
      +           
      +//Read at most 16384 symbols
      +logFileContent = Rho.Log.readLogFile(16384);
      +                
      :::ruby
      +
      +           
      +# Read at most 16384 symbols
      +logFileContent = Rho::Log.readLogFile 16384
      +                
      Clean log file
      +

      Clear the contents of the log file. In this example, logFileContentBefore will contain the log up until that point, while logFileContentAfter will be empty.

      +
      :::javascript
      +
      +           
      +// Read log file
      +logFileContentBefore = Rho.Log.readLogFile(16384);
      +
      +// Clear log file
      +Rho.Log.cleanLogFile();
      +
      +// Read log file again - this time it will be empty
      +logFileContentAfter = Rho.Log.readLogFile(16384);
      +                
      :::ruby
      +
      +           
      +# Read log file
      +logFileContentBefore = Rho::Log.readLogFile 16384
      +
      +# Clear log file
      +Rho::Log.cleanLogFile
      +
      +# Read log file again - this time it will be empty
      +logFileContentAfter = Rho::Log.readLogFile(16384
      +                
      Logging categories
      +

      Categories help you organize your logging messages and find related statements using tools like grep or a text editor’s “search” function.

      +
      :::javascript
      +
      +           
      +Rho.Log.info("Consectetuer adipiscing elit", "Lorem Ipsum");
      +Rho.Log.info("Foo acquired value Bar in method Baz", "Miscellaneous");
      +
      +//The above code will result in logging statements like these
      +Lorem Ipsum| Consectetuer adipiscing elit
      +Miscellaneous Foo acquired value Bar in method Baz
      +
      +                
      :::ruby
      +
      +           
      +Rho::Log.info("Consectetuer adipiscing elit", "Lorem Ipsum")
      +Rho::Log.info("Foo acquired value Bar in method Baz", "Miscellaneous")
      +
      +#The above code will result in logging statements like these
      +Lorem Ipsum| Consectetuer adipiscing elit
      +Miscellaneous Foo acquired value Bar in method Baz
      +
      +                
      Memory Usage
      +

      You can ask the system to automatically log memory usage information on a set interval. This can be used to debug potential memory leaks in operations where a high number of objects are touched in memory.

      +
      :::javascript
      +
      +           
      +Rho.Log.memoryPeriod = 1000;
      +// Perform memory-intensive operations here. Examining the log will tell us if we have a memory leak
      +// Once our task finishes, disable automatic memory logging
      +Rho.Log.memoryPeriod = 0;
      +               
      :::ruby
      +
      +           
      +# Request that memory usage be logged automatically by the system every second.
      +Rho::Log.memoryPeriod = 1000
      +# Perform memory-intensive operations here. Examining the log will tell us if we have a memory leak
      +# Once our task finishes, disable automatic memory logging
      +Rho::Log.memoryPeriod = 0
      +                
      \ No newline at end of file diff --git a/docs/en/5.5/api/Log.xml b/docs/en/5.5/api/Log.xml new file mode 100644 index 00000000..a4ffaebd --- /dev/null +++ b/docs/en/5.5/api/Log.xml @@ -0,0 +1,403 @@ + + + + + Use this API to control the behavior of the RhoMobile Log API as well as access it. This API gives access to the Logging functionality. There are five functions to add messages to the log with different severity (from lowest to highest) : trace, info, warning, error and fatal. Each of those functions gets two parameters: message and category. Category is an user defined group that helps with used searching and filtering. + +Accessing Log File: +sendLogFile: will sent all the log to server +showLog: brings up popup with log, +readLogFile: returns the full log file, +cleanLogFile: removes all logged messages + +Filtering: + +* Using level property: It limits minimal severity of messages that will be added to log. For example: setting log level to 2 (warning) will filter out messages generated by trace and info. + +* Categories: user defined groups that are used to select messages from different modules for ease of use. There are two main filters: includeCategories and excludeCategories. They are both active at the same time. includeCategories allows to select groups/categories that should be in the log (setting this property to empty will turn disable logging). excludeCategories is used for filtering out some of categories. + +* excludeFilter, this filter is used to remove all sensitive information like passwords, security tokens from log. + +Log destinations (any combinations of them): + +* debug console (stdio), +* device filesystem (file) +* remote sever (url) + + Use this API to control the behavior of the log as well as access it. This API gives access to the Logging functionality. There are five functions to add messages to the log with different severity (from lowest to highest) : trace, info, warning, error and fatal. Each of those functions gets two parameters: message and category. Category is an user defined group that helps with used searching and filtering. + +Accessing Log File: +sendLogFile: will sent all the log to server +showLog: brings up popup with log, +readLogFile: returns the full log file, +cleanLogFile: removes all logged messages + +Filtering: + +* Using level property: It limits minimal severity of messages that will be added to log. For example: setting log level to 2 (warning) will filter out messages generated by trace and info. + +* Categories: user defined groups that are used to select messages from different modules for ease of use. There are two main filters: includeCategories and excludeCategories. They are both active at the same time. includeCategories allows to select groups/categories that should be in the log (setting this property to empty will turn disable logging). excludeCategories is used for filtering out some of categories. + +* excludeFilter, this filter is used to remove all sensitive information like passwords, security tokens from log. + +Log destinations (any combinations of them): + +* debug console (stdio), +* device filesystem (file) +* remote sever (url) + + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + +## Enabling the API +There are two methods of enabling the Log API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Log API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.log.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + The current logging level. Minimal severity level of messages that will appear in log. When level is set to 0 any messages will be logged. When level is set to 4 only fatal error messages will be logged. Default value is defined in rhoconfig.txt (MinSeverity) + The current logging level. Minimal severity level of messages that will appear in log. When level is set to 0 any messages will be logged. When level is set to 4 only fatal error messages will be logged. Default value is defined in Config.xml + + + Everything will be logged. Also see settings for controlling log size. + + + Information level logs and above will be shown. + + + Warnings and above will only be shown. + + + Error level log messages and above will be shown. + + + Fatal level log messages and above will be shown. + + + + + + List of log destinations that are being used. Destination could be set to empty (disable all logging), Logging to several destinations could be set by setting destination to comma separated list in any order (for example "stdio,file"). By default logging to console can be enabled from rhoconfig.txt (LogToOutput = 1). After Rhodes initialization logging to file is enabled automatically. + List of log destinations that are being used. Destination could be set to empty (disable all logging), Logging to several destinations could be set by setting destination to comma separated list in any order (for example "stdio,file"). By default logging to console can be enabled from Config.xml). + + + Log is written to a local file on the device (typically rholog.txt) + Log is written to a local file on the device (typically Log.txt) + + + Log is written to the standard output (ex: Android ADB) + + + Log is written to a remote logger. + + + + + + Comma-separated list of included log categories. Set to '\*' (asterisk) to log all categories. Set to '' (empty) to filter out all messages. Default value is '\*' (asterisk), it is set in rhoconfig.txt (LogCategories). + Comma-separated list of included log categories. Set to '\*' (asterisk) to log all categories. Set to '' (empty) to filter out all messages. Default value is '\*' (asterisk), it is set in Config.xml. + + + + Comma-separated list of excluded log categories. Set to '' (empty) to allow all messages to be logged. Set to concrete value to filter out log from those categories. Default value is '' (empty), it is set in rhoconfig.txt (ExcludeLogCategories) + Comma-separated list of excluded log categories. Set to '' (empty) to allow all messages to be logged. Set to concrete value to filter out log from those categories. Default value is '' (empty), it is set in Config.xml + + + + Maximum log file size in bytes, set 0 to unlimited size; when limit is reached, log wraps to beginning of file. Default value is 50000, it is set in rhoconfig.txt (MaxLogFileSize) + Maximum log file size in bytes, set 0 to unlimited size; when limit is reached, log wraps to beginning of file. Default value is 50000, it is set in Config.xml + + + + Path to the log file including file name. The path is relative to the platform specific application root or start if from '/' if you wish to store elsewhere ('/mnt/sdcard/myapp.log'). Default file path is "rholog.txt" + Path to the log file including file name. The path is relative to the platform specific application root or start if from '/' if you wish to store elsewhere ('/mnt/sdcard/myapp.log'). Default file path is Log.txt + + + + WM, CE, Android, iOS + WM, CE, Android + Enables the logging of memory usage in the system; specifies the time interval in milliseconds at which memory logs will be generated periodically. Setting it to 0 will disable logging memory information. + + + + Turn on remote network traces regardless of log level set (e.g. Network, asyncHttp). Traces contain information about connection process, sent and received headers and data. Please note that this parameter will not take an effect in case of local server app (and / or shared runtime). Default value can be overridden by the setting in rhoconfig.txt (net_trace). To get local server trace, use `Rho.Log.LEVEL_TRACE` in JavaScript and `Rho::Log::LEVEL_TRACE` in Ruby. + Turn on remote network traces regardless of log level set (e.g. Network, asyncHttp). Traces contain information about connection process, sent and received headers and data. Please note that this parameter will not take an effect in case of local server app. Default value can be overridden by the setting in Config.xml. To get local server trace, use `Rho.Log.LEVEL_TRACE`. + Android, iOS, WP8 + Android + + + + Skip http package body from log(for security reasons). Please note that this parameter will not take an effect in case of remote server app (and / or shared runtime), no log will appear in this case. + + + + Define exclude parameters log filter(for security reasons) - parameter names separated by comma. It works when user tries to put in log string containing json / urls. Default value is "" (empty). For example, if user set excludeFilter="password", then tries to put in log this string: "{"user":"alex","password":"abcdef","sessionid":123456}", "abcdef" will not appear in log. + + + + Log server URI where log will be posted by using Rho::Log.sendLogFile or from the log view. Log server source code is open and available at http://github.com/rhomobile/rhologs, so you can deploy your own logserver. URI format: 'http://host:port[/path][?log_name=appName]'. Default value is set in rhoconfig.txt (logserver) + Log server URI where log will be posted by using EB.Log.sendLogFile or from the log view. Log server source code is open and available at http://github.com/rhomobile/rhologs, so you can deploy your own logserver. URI format: 'http://host:port[/path][?log_name=appName]'. Default value is set in Config.xml in the LogURI setting under the Logger section. + + + + + + + + + Log message at the Trace level. By default trace messages are not shown in log (if level equals to 1). + + + Log message. + + + Log category. + + + + + + Log message at the Info level. + + + Log message. + + + Log category. + + + + + + Log message at the Warning level. + + + Log message. + + + Log category. + + + + + + Log message at the Error level. + + + Log message. + + + Log category. + + + + + + Log message at the FatalError level. Application will be terminated (on all platforms except iOS). + Log message at the FatalError level. Application will be terminated. + + + Log message. + + + Log category. + + + + + + Send log file to destinationURI property. Please note that this procedure is blocking and will stop any logging while log file is being send. + + + + Display Log view window. + WM, CE, Win32, iOS, Android + WM, CE, Win32, Android + + + + Clean log file, all logged messages will be removed. + + + + Read log file. Returns string from the log file containing specified number of symbols. + + + Maximum size of the resulting string in symbols. + + + + + + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + +
      + Show the contents of the log file in a window with controls to refresh, clear and send. Useful for debugging and when asking users to report error messages. + + + + + + + + +
      +
      +
      + + +
      + Retrieve the contents of the log file as a string. + + + + + + + + +
      +
      +
      + + +
      + Clear the contents of the log file. In this example, logFileContentBefore will contain the log up until that point, while logFileContentAfter will be empty. + + + + + + + + +
      +
      +
      + + +
      + Categories help you organize your logging messages and find related statements using tools like grep or a text editor's "search" function. + + + + + + + + +
      +
      +
      + + +
      + You can ask the system to automatically log memory usage information on a set interval. This can be used to debug potential memory leaks in operations where a high number of objects are touched in memory. + + + + + + + + +
      +
      +
      +
      +
      +
      \ No newline at end of file diff --git a/docs/en/5.5/api/Message.md b/docs/en/5.5/api/Message.md new file mode 100644 index 00000000..1754c433 --- /dev/null +++ b/docs/en/5.5/api/Message.md @@ -0,0 +1,39 @@ +#Message +
      +

      NFC Message

      +

      This class representative NFC Message object

      + +
      # Enabling the API
      +In order to use this API you must include the following extension in your `build.yml`
      +    :::ruby
      +    extensions: ["nfc"]
      +
      +NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings).
      +
      + + + +

      Methods

      + +

      addMessage(STRING messageID)

      Add new Smart Poster message to the message.

      +

      Parameters

      • messageID : STRING

        Added Message object ID.

        +

      Synchronous Return:

      • Void

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.addMessage(STRING messageID)

      addRecord(STRING recordID)

      Add new Record to Message.

      +

      Parameters

      • recordID : STRING

        Added Record object ID.

        +

      Synchronous Return:

      • Void

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.addRecord(STRING recordID)

      close()

      Release NFC resources.

      +

      Synchronous Return:

      • Void

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.close()

      create()

      Creates message object.

      +

      Synchronous Return:

      • Rho.NFC.Message :

        Created Message object.

        +

      Method Access:

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

      getContent()

      Returns Message as byte array.

      +

      Synchronous Return:

      • STRING :

        Message to get.

        +

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.getContent()

      getMessageById(STRING id)

      This function returns Message object.

      +

      Parameters

      • id : STRING

        Message object ID.

        +

      Synchronous Return:

      • SELF_INSTANCE :

        “self” instance of the Message object.

        +

      Method Access:

      • Class Method: This method can only be accessed via the API class object.
        • JavaScript: Rho.Message.getMessageById(STRING id)
        • Ruby: Rho::Message.getMessageById(STRING id)

      getMessages()

      Return array of Smart Poster Message objects.

      +

      Synchronous Return:

      • ARRAY :

        Array of Rho.NFC.Message objects.

        +
        • Object : Rho.NFC.Message

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.getMessages()

      getRecords()

      Return array of Record objects.

      +

      Synchronous Return:

      • ARRAY :

        Array of Rho.NFC.Record objects.

        +
        • Object : Rho.NFC.Record

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.getRecords()
      + +

      Properties

      + +

      ID : STRING Read Only

      Object ID.

      +

      Property Access:

      • Instance: This property can be accessed via an instance object of this class:
        • myObject.ID
      \ No newline at end of file diff --git a/docs/en/5.5/api/Message.xml b/docs/en/5.5/api/Message.xml new file mode 100644 index 00000000..374ed040 --- /dev/null +++ b/docs/en/5.5/api/Message.xml @@ -0,0 +1,139 @@ + + + + + NFC Message + This class representative NFC Message object + # Enabling the API + In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["nfc"] + + NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + + + +## Enabling the API +There are two methods of enabling the Message API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Message API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.message.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + List of properties supported by class. + + + Object ID. + WM + + + + + + This function returns Message object. + + + Message object ID. + + + + "self" instance of the Message object. + + WM + + + + Creates message object. + + Created Message object. + + WM + + + + Return array of Record objects. + + + Array of Rho.NFC.Record objects. + + WM + + + + Return array of Smart Poster Message objects. + + + Array of Rho.NFC.Message objects. + + WM + + + + Add new Record to Message. + + + Added Record object ID. + + + WM + + + + Add new Smart Poster message to the message. + + + Added Message object ID. + + + WM + + + + Returns Message as byte array. + + Message to get. + + WM + + + + Release NFC resources. + WM + + + + + + + 1.0.0 + + + + \ No newline at end of file diff --git a/docs/en/5.5/api/MobilePayment.md b/docs/en/5.5/api/MobilePayment.md new file mode 100644 index 00000000..4ccffe85 --- /dev/null +++ b/docs/en/5.5/api/MobilePayment.md @@ -0,0 +1,251 @@ +#MobilePayment +
      +

      The Mobile Payment module implements the functions required to work with the PD40 Bluetooth Payment MPOS. We need to include the emdk jar in the add-ons directory of android sdk in order to build it.

      +

      Before an application can use this module, the device must be paired via Bluetooth the mobile device requesting use.

      + +
      If this is not done, no functions will work and the Open function will return an error of not paired. Only One PD40 device should be worked with one device. emdk3-manager extension has to be included before mobile_payment.
      +
      +## Enabling the API
      +In order to use this API you must include the following extension in your `build.yml`.
      +:::ruby
      +extensions: ["mobile_payment"]
      +
      + +

      ## JavaScript Usage

      + +
      Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript.
      +
      +## Ruby Usage
      +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby.
      +
      + + + +

      Methods

      + +

      abort(CallBackHandler callback)

      Cancel previously issued method and display welcome screen on PAYMENT device.

      +

      Parameters

      • callback : CallBackHandler Mandatory

      Async Callback Returning Parameters: OBJECT

        • status : STRING

          Success or Failure depending on outcome of function.

          +

        • errorName : STRING

          If the status is error, this contains the ErrorName associated with that error.

          +

      Synchronous Return:

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

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.abort(CallBackHandler callback)
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.abort(CallBackHandler callback)
        • Ruby: Rho::MobilePayment.abort(CallBackHandler callback)

      authorizeCard(FLOAT amount, FLOAT otherAmount, INTEGER merchantDecision, ARRAY tags, BOOLEAN displayResult, BOOLEAN pinTryExceedStatus, BOOLEAN displayAmount, BOOLEAN displayAppExpired, INTEGER timeout, CallBackHandler callback)

      Authorizes the EMV transaction amounts using the inserted chip (EMV) card. This is an asynchronous call. Before calling this method,readcarddata has to be called.

      +

      Parameters

      • amount : FLOAT

        Transaction amount value.

        +

      • otherAmount : FLOAT

        Other transaction amount value.

        +

      • merchantDecision : INTEGER

        The merchant decision notes additional handling for the EMV request based on required processor handling.

        + +
                Please use the constants for Merchant Decision.
        +
        +

      • tags : ARRAY

        EMV tags that are required at this transaction stage to be retrieved.

        +

      • displayResult : BOOLEAN

        true or false. Display result on Payment device.

        +

      • pinTryExceedStatus : BOOLEAN

        true or false. Displays when PIN tries have exceeded value on Payment device.

        +

      • displayAmount : BOOLEAN

        true or false. Displays amount of Payment device.

        +

      • displayAppExpired : BOOLEAN

        true or false. Displays if app is expired on Payement display.

        +

      • timeout : INTEGER

        Card authorization timeout. Application must set the timeout.

        +

      • callback : CallBackHandler Mandatory

      Async Callback Returning Parameters: OBJECT

        • status : STRING

          Either SUCCESS or ERROR

          +

        • errorName : STRING

          If the status is error, this contains the ErrorName associated with that error.

          +

        • tlvStrings : ARRAY

          An array of the returned Tags requested.

          +

        • keySerialNo : STRING

          key Serial no

          +

        • pinBlock : STRING

          pin block

          +

      Synchronous Return:

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

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.authorizeCard(FLOAT amount, FLOAT otherAmount, INTEGER merchantDecision, ARRAY tags, BOOLEAN displayResult, BOOLEAN pinTryExceedStatus, BOOLEAN displayAmount, BOOLEAN displayAppExpired, INTEGER timeout, CallBackHandler callback)
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.authorizeCard(FLOAT amount, FLOAT otherAmount, INTEGER merchantDecision, ARRAY tags, BOOLEAN displayResult, BOOLEAN pinTryExceedStatus, BOOLEAN displayAmount, BOOLEAN displayAppExpired, INTEGER timeout, CallBackHandler callback)
        • Ruby: Rho::MobilePayment.authorizeCard(FLOAT amount, FLOAT otherAmount, INTEGER merchantDecision, ARRAY tags, BOOLEAN displayResult, BOOLEAN pinTryExceedStatus, BOOLEAN displayAmount, BOOLEAN displayAppExpired, INTEGER timeout, CallBackHandler callback)

      close(CallBackHandler callback)

      Close unitializes and disconnects the PD40 payment device.

      +

      Parameters

      • callback : CallBackHandler Mandatory

      Async Callback Returning Parameters: HASH

        • status : STRING

          Will contain either success or error.

          +

        • errorName : STRING

          If the status is error, this contains the ErrorName associated with that error.

          +

      Synchronous Return:

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

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.close(CallBackHandler callback)
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.close(CallBackHandler callback)
        • Ruby: Rho::MobilePayment.close(CallBackHandler callback)

      completeOnlineEmv(INTEGER hostDescision, BOOLEAN displayResult, ARRAY tlvStrings, CallBackHandler callback)

      Completes an online EMV transaction for PIN management. The application must call authorizeCard before calling this API. This is an asynchronous call. After the processing, the response (i.e., EmvData object) is returned through the registered Callback.

      +

      Parameters

      • hostDescision : INTEGER

        HostDecision enum value which is the decision indicator from the host response. Use the constants “HOST DEFINED” defined in the XML document.

        +

      • displayResult : BOOLEAN

        Indicator to note whether or not to display the final response message. False for Do not display and true to Display.

        +

      • tlvStrings : ARRAY

        List of EMV data which contains EMV tag and its values.

        +

      • callback : CallBackHandler Mandatory

      Async Callback Returning Parameters: HASH

        • status : STRING

          Either SUCCESS or ERROR

          +

        • errorName : STRING

          If the status is error, this contains the ErrorName associated with that error.

          +

        • tlvStrings : ARRAY

          An array of the returned Tags requested.

          +

      Synchronous Return:

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

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.completeOnlineEmv(INTEGER hostDescision, BOOLEAN displayResult, ARRAY tlvStrings, CallBackHandler callback)
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.completeOnlineEmv(INTEGER hostDescision, BOOLEAN displayResult, ARRAY tlvStrings, CallBackHandler callback)
        • Ruby: Rho::MobilePayment.completeOnlineEmv(INTEGER hostDescision, BOOLEAN displayResult, ARRAY tlvStrings, CallBackHandler callback)

      createMac(STRING u8MacData)

      This is a required transaction for Canada. Accepts a String of data to be MACed using the ANSI x9.91 standard and the MAC Working Key. This is used for MACing credit transactions when the PINPad is configured to support both credit and debit. This is synchronous call.

      +

      Parameters

      • u8MacData : STRING

        String of data to be MACed. The length of the key should be 16 or 32 or 48 in HEX format.

        +

      Synchronous Return:

      • HASH
        • status : STRING

          SUCCESS or ERROR.

          +

        • errorName : STRING

          If the status is error, this contains the ErrorName associated with that error.

          +

        • macBlock : STRING

          If the status is succes, it returns macBlock.

          +

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.createMac(STRING u8MacData)
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.createMac(STRING u8MacData)
        • Ruby: Rho::MobilePayment.createMac(STRING u8MacData)

      getAllProperties(CallBackHandler callback)

      This method will return all of object/value pairs for the propertyNames of the API class.

      +

      Parameters

      • callback : CallBackHandler Optional

      Async Callback Returning Parameters: HASH

        • : STRING

      Synchronous Return:

      • HASH :

        Map of all available properties

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

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.getAllProperties(CallBackHandler callback)
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.getAllProperties(CallBackHandler callback)
        • Ruby: Rho::MobilePayment.getAllProperties(CallBackHandler callback)

      getBatteryLevel()

      Query the battery level of the payment device.

      +

      Synchronous Return:

      • HASH
        • status : STRING

          success or error.

          +

        • errorName : STRING

          If the status is error, this contains the ErrorName associated with that error.

          +

        • batteryLevel : INTEGER

          If the status is success, this contains the battery level. Value would be 1,2,3,4.

          +

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.getBatteryLevel()
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.getBatteryLevel()
        • Ruby: Rho::MobilePayment.getBatteryLevel()

      getDefault()

      This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

      +

      Synchronous Return:

      • SELF_INSTANCE :

        Default object of Module.

        +

      Method Access:

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

      getDeviceInfo()

      Returns information about the payment device.

      +

      Synchronous Return:

      • HASH
        • status : STRING

          success or error.

          +

        • errorName : STRING

          If the status is error, this contains the ErrorName associated with that error.

          +

        • applicationVersion : STRING

          Application Version of PD40.

          +

        • firmwareVersion : STRING

          Firmware Version of PD40.

          +

        • connectionType : STRING

          Connection Type Version of PD40.

          +

        • deviceType : STRING

          Device Type of PD40.

          +

        • friendlyName : STRING

          Friendlyname of PD40.

          +

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.getDeviceInfo()
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.getDeviceInfo()
        • Ruby: Rho::MobilePayment.getDeviceInfo()

      getEmvTags(ARRAY emvTags, CallBackHandler callback)

      Gets tag information from the inserted card. This is an asynchronous call. After the processing, the response (TagData contains TLV raw data as per EMV specification)and also its parsed tag, length and value format is returned through the registered Callback.Before calling this method,readcarddata has to be called.

      +

      Parameters

      • emvTags : ARRAY

        Array containing EMV tag IDs to be retrieved from the inserted card. Refer to the EMV Tags section in the documentation to

        + +
                know which TAG IDs can be requested with this call.  Any number of Tag IDs are allowed and the number of Tag IDs will match the number of tag values.
        +
        +

      • callback : CallBackHandler Mandatory

      Async Callback Returning Parameters: OBJECT

        • status : STRING

          Either SUCCESS or ERROR

          +

        • errorName : STRING

          If the status is error, this contains the ErrorName associated with that error.

          +

        • tlvStrings : ARRAY

          An array of the returned Tags requested.

          +

      Synchronous Return:

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

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.getEmvTags(ARRAY emvTags, CallBackHandler callback)
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.getEmvTags(ARRAY emvTags, CallBackHandler callback)
        • Ruby: Rho::MobilePayment.getEmvTags(ARRAY emvTags, CallBackHandler callback)

      getLowBatteryThreshold()

      Gets the acceptable low battery level. If the battery drops below this value, the device will not execute any of the selected commands..

      +

      Synchronous Return:

      • HASH
        • status : STRING

          success or error.

          +

        • errorName : STRING

          If the status is error, this contains the ErrorName associated with that error.

          +

        • lowBatteryThreshold : INTEGER

          If the status is success, this contains the battery level. Value would be 1,2,3,4.

          +

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.getLowBatteryThreshold()
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.getLowBatteryThreshold()
        • Ruby: Rho::MobilePayment.getLowBatteryThreshold()

      getProperties(ARRAY arrayofNames, CallBackHandler callback)

      This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

      +

      Parameters

      • arrayofNames : ARRAY

        List of properties I want to know about

        +

        • Object : STRING

      • callback : CallBackHandler Optional

      Async Callback Returning Parameters: HASH

        • : STRING

      Synchronous Return:

      • HASH :

        Map of properties I want to know about

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

      Method Access:

      • Instance Method: This method can be accessed via an instance object of this class:
        • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
      • Default Instance: This method can be accessed via the default instance object of this class.
        • JavaScript: Rho.MobilePayment.getProperties(ARRAY arrayofNames, CallBackHandler callback)
        • Ruby: Rho::MobilePayment.getProperties(ARRAY arrayofNames, CallBackHandler callback)

      getProperty(STRING propertyName, CallBackHandler callback)

      This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

      +

      Parameters

      • propertyName : STRING

        The property to return info about.

        +

      • callback : CallBackHandler Optional

      Async Callback Returning Parameters: STRING

        Synchronous Return:

        • STRING :

          The property to return info about.

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.getProperty(STRING propertyName, CallBackHandler callback)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.getProperty(STRING propertyName, CallBackHandler callback)
          • Ruby: Rho::MobilePayment.getProperty(STRING propertyName, CallBackHandler callback)

        isOpened()

        Returns whether the PD40 device is enabled or not.

        +

        Synchronous Return:

        • BOOLEAN :

          Returns true if PD40 is opened,otherwise false.

          +

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.isOpened()
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.isOpened()
          • Ruby: Rho::MobilePayment.isOpened()

        open(STRING deviceName, CallBackHandler callback)

        Opens the PD40 Payment reader. Will fail if not paired manually beforehand.

        +

        Parameters

        • deviceName : STRING

          The name of the PD40 device which is paired and to be worked with.

          +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • status : STRING

            Will contain either success or error.

            +

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

        Synchronous Return:

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.open(STRING deviceName, CallBackHandler callback)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.open(STRING deviceName, CallBackHandler callback)
          • Ruby: Rho::MobilePayment.open(STRING deviceName, CallBackHandler callback)

        promptAdditionalInfo(HASH propertyMap, CallBackHandler callback)

        Requests the user to confirm the amount and surcharge passed by the application and prompts the user to provide tip and cashback. The tip, cashback values and the confirmation if surcharge was accepted, will be returned to the application via callback. If the user presses OK or CANCEL keys, or the call times out, the corresponding message is returned. This is asynchronous call.

        +

        Parameters

        • propertyMap : HASH

          The properties associated with the promptMessage function.

          +

          • amount : FLOAT

            Transaction amount value that is displayed, valid range is from 0.01 to 999999.99

            +

          • langCode : INTEGER

            Numeric value denoting the language code for determining language of the pre-defined prompt. Languages currently supported are listed in the constants section. Other languages can be used, but all information relating to that is the responsibility of the calling application. Currenly supported only 0 i.e. US

            +

          • promptForTip : BOOLEAN

            Indicates whether or not to prompt for tip and return the amount desired.

            +

          • cashBack : BOOLEAN

            Indicates whether or not to prompt for cashback and return the amount selected. The user would select cashback amount from 4 pre-defined – $20, $40, $60 and $100. These choices cannot be modified.

            +

          • surcharge : FLOAT

            An optional surcharge amount that is to be displayed and confirmed (valid range is from 0.01 to 99.99). A zero amount will cause this prompt to be bypassed.

            +

          • timeout : INTEGER

            Read timeout in milliseconds. The app can set the timeout, but the value must be within the threshold set by the payment device.

            +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • status : STRING

            Success or Failure depending upon outcome of function

            +

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

          • tip : FLOAT

            If a tip was input, this will contain that value, 0.00 otherwise

            +

          • cashBack : FLOAT

            If cashback is asked for, this contains the amount given.

            +

          • surchargeIndicator : STRING

        Synchronous Return:

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.promptAdditionalInfo(HASH propertyMap, CallBackHandler callback)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.promptAdditionalInfo(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::MobilePayment.promptAdditionalInfo(HASH propertyMap, CallBackHandler callback)

        promptMenu(HASH propertyMap, CallBackHandler callback)

        Displays two lines of messages on the PAYMENT device and provides a menu with a maximum of 4 choices. This is asynchronous call. The character “|” not allowed in the message strings and it is used as special character in the EMDK for PD40-100.

        +

        Parameters

        • propertyMap : HASH

          The properties associated with the promptMessage function.

          +

          • messageLine1 : STRING

            Message Line1 to display on the PINPad screen. Maximum characters allowed for Choice + Message = 18 characters.

            + +
                            For example, if Choice is 6 characters, maximum message length is 12 characters.  
            +                Messages longer than maximum message length will be truncated.
            +
            +

          • messageLine2 : STRING

            Message Line2 to display on the PINPad screen. Maximum characters allowed for Choice + Message = 18 characters.

            + +
                            For example, if Choice is 6 characters, maximum message length is 12 characters.  
            +                Messages longer than maximum message length will be truncated.
            +
            +

          • choice1 : STRING

            Choice text for selection from the PINPad using the function keys.

            + +
                            Choice string can consist of up to 8 characters.
            +
            +

          • choice2 : STRING

            Choice text for selection from the PINPad using the function keys.

            + +
                            Choice string can consist of up to 8 characters.
            +
            +

          • choice3 : STRING

            Choice text for selection from the PINPad using the function keys.

            + +
                            Choice string can consist of up to 8 characters.
            +
            +

          • choice4 : STRING

            Choice text for selection from the PINPad using the function keys.

            + +
                            Choice string can consist of up to 8 characters.
            +
            +

          • timeout : INTEGER

            Timeout in milliseconds. App can set the timeout,

            + +
                            but value must be within threshold set by the payment device.
            +
            +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • status : STRING

            Success or Failure depending upon the outcome of the function

            +

          • choice : STRING

            The choice that was decided by the user on status is success.

            +

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

        Synchronous Return:

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.promptMenu(HASH propertyMap, CallBackHandler callback)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.promptMenu(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::MobilePayment.promptMenu(HASH propertyMap, CallBackHandler callback)

        promptMessage(HASH propertyMap, CallBackHandler callback)

        Displays a maximum of 4 line messages on the PAYMENT device. This method also allows a user confirmation.

        + +
            This can be done by setting the 5th parameter to true, in which case a string containing OK, CANCEL, CORR or TIMEOUT (after 15 seconds).  
        +    This is an asynchronous call and all data is returned in the callback.
        +
        +

        Parameters

        • propertyMap : HASH

          The properties associated with the promptMessage function.

          +

          • messageLine1 : STRING

            A message to display on line 1 of the PINPad screen, may consist of up to 16 characters.

            +

          • messageLine2 : STRING

            A message to display on line 1 of the PINPad screen, may consist of up to 16 characters.

            +

          • messageLine3 : STRING

            A message to display on line 1 of the PINPad screen, may consist of up to 16 characters.

            +

          • messageLine4 : STRING

            A message to display on line 1 of the PINPad screen, may consist of up to 16 characters.

            +

          • getUserConfirmation : BOOLEAN

            true or false. Allows the user to press OK (Enter Key), CANCEL or CORR keys in response to the displayed message. If getUserConfirmation is false, this is a synchronous call.

            +

          • timeout : INTEGER

            Read timeout in milliseconds. The app can set the timeout, but the value must be within the threshold set by the payment device.

            +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • status : STRING

            Success or Error depending on outcome of function.

            +

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

          • userConfirmationMessage : STRING

            Will contain OK, CANCEL or CORR depending upon what the user pressed.

            +

        Synchronous Return:

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.promptMessage(HASH propertyMap, CallBackHandler callback)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.promptMessage(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::MobilePayment.promptMessage(HASH propertyMap, CallBackHandler callback)

        promptPin(HASH propertyMap, CallBackHandler callback)

        Requests for a PIN and gets the encrypted PIN block. The encrypted data will be returned only if a debit key is injected into the payment device. This is asynchronous call Note: The character “|” not allowed in the message strings for PD40-100 payment device and it is used as special character in the in the EMDK for PD40-100 device. Requesting promptPin() continuously may pop up the timer on PD40-100 payment device for security reasons and application should wait for this before performing any other actions.

        +

        Parameters

        • propertyMap : HASH

          The properties associated with promptPin.

          +

          • accountNumber : STRING

            The account number used with the entered PIN to create the encrypted PIN Block (8 to 19 alphanumeric digits inclusive).

            +

          • minPINLength : INTEGER

            Minimum PIN Length. A minimum length of 4 digits is required.

            +

          • maxPINLength : INTEGER

            Maximum PIN Length. A maximum length of 12 digits is allowed.

            +

          • isPinOptional : BOOLEAN

            isPinOptional is always false. It is kept for future modification.

            +

          • message1 : STRING

            Message 1 to be displayed on the PINPad (alternates with Message 2). Maximum message length 21 characters.

            +

          • message2 : STRING

            Message 2 to be displayed on the PINPad (alternates with Message 1). Maximum message length 21 characters.

            +

          • messageTitle : STRING

            Message Title to be displayed during PIN entry.

            +

          • readTimeOut : INTEGER

            Read timeout in milliseconds. App can set the timeout, but value must be within threshold set by the payment device.

            +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • status : STRING

            Success for Error depending upon the outcome of the call.

            +

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

          • pinBlockStr : STRING

            returns the pin block string

            +

          • serialNumber : STRING

            Returns the serial number

            +

          • isPinEntered : BOOLEAN

            returns true or false on whether the pin is entered by the user or not

            +

        Synchronous Return:

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.promptPin(HASH propertyMap, CallBackHandler callback)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.promptPin(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::MobilePayment.promptPin(HASH propertyMap, CallBackHandler callback)

        readCardData(HASH propertyMap, CallBackHandler callback)

        Reads the card data from the PAYMENT device through a swipe (MagStripe), insert (for smart cards).

        + +
            This is asynchronous so the return data is passed back through the callback.
        +
        +

        Parameters

        • propertyMap : HASH

          The properties associated with reading card data.

          +

          • amount : FLOAT

            Amount for the transaction; this value is required to enable EMV contactless transactions. Allowed upto a maximum of 7 digits.

            +

          • otherAmount : FLOAT

            Any additional amount information for the transaction; this value is used only if EMV Contactless is supported. Allowed upto a maximum of 7 digits

            +

          • readMode : INTEGER

            Use the constants defined in the XML for use with READMODE

            +

          • messageTitle : STRING

            The message Title to be displayed on the card data request. The maximum length is 18 characters. The character “|” not allowed. Please see remarks section.

            +

          • message1 : STRING

            The custom message to be displayed on the card data request. The maximum length is 18 characters. The character “|” not allowed.Please see remarks section.

            +

          • message2 : STRING

            The custom message to be displayed on the card data request. The maximum length is 18 characters. The character “|” not allowed.

            + +
                                Please see remarks section.
            +
            +

          • readTimeOut : INTEGER

            Read timeout in milliseconds. App can set the timeout, but value used must be within the threshold set by the payment device.

            +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • status : STRING

            Will contain either success or error depending on outcome of call.

            +

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

          • accountNumber : INTEGER

          • cardHolderName : STRING

          • expiryDate : STRING

          • track1Data : STRING

          • track2Data : STRING

          • track3Data : STRING

          • tlvStrings : ARRAY

          • maskedPan : STRING

        Synchronous Return:

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.readCardData(HASH propertyMap, CallBackHandler callback)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.readCardData(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::MobilePayment.readCardData(HASH propertyMap, CallBackHandler callback)

        removeCard(STRING message1, STRING message2)

        Instruct the user to remove the EMV card inserted in the payment device. This call prompts the user to remove the inserted EMV chip card and also clears the EMV data saved by readCardData method. If the card is NOT inserted, it will give success.

        +

        Parameters

        • message1 : STRING

          The message which gives the information of type of card.

          +

        • message2 : STRING

          The message which gives instructions to user for the removal of the card.

          +

        Synchronous Return:

        • HASH :

          The results describes the succesfulness of the operation.

          +
          • status : STRING

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.removeCard(STRING message1, STRING message2)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.removeCard(STRING message1, STRING message2)
          • Ruby: Rho::MobilePayment.removeCard(STRING message1, STRING message2)

        setDefault(SELF_INSTANCE: Rho::MobilePayment defaultInstance)

        This method allows you to set the attributes of the default object instance by passing in an object of the same class.

        +

        Parameters

        • defaultInstance : SELF_INSTANCE: Rho::MobilePayment

          An instance object that is of the same class.

          +

        Synchronous Return:

        • Void

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.MobilePayment.setDefault(SELF_INSTANCE: Rho::MobilePayment defaultInstance)
          • Ruby: Rho::MobilePayment.setDefault(SELF_INSTANCE: Rho::MobilePayment defaultInstance)

        setEmvTags(ARRAY tagIds)

        Sets tag information for the inserted card. Valid EMV tag IDs and tag values should be passed. Passing invalid EMV tag IDs or tag values may cause the payment device to go into unstable state or unknown behavior. The payment device has to be rebooted in order to continue normal operation.Before calling this method,readcarddata has to be called.

        +

        Parameters

        • tagIds : ARRAY

          Array containing valid EMV tag IDs to be set on the inserted card.Before calling this method,readcarddata has to be called.

          +

        Synchronous Return:

        • HASH
          • status : STRING

            Either SUCCESS or ERROR

            +

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.setEmvTags(ARRAY tagIds)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.setEmvTags(ARRAY tagIds)
          • Ruby: Rho::MobilePayment.setEmvTags(ARRAY tagIds)

        setLowBatteryThreshold(INTEGER lowThreshold, STRING lowBatterMessage)

        Sets the acceptable low battery percent. If the battery drops below this value, the device will not execute some of the commands.

        + +
                and it will return the error code indicating the battery is low.
        +
        +

        Parameters

        • lowThreshold : INTEGER

          Battery threshold value. Below this value, some of the commands will not execute

          +

        • lowBatterMessage : STRING

          The message to be displayed when the battery level goes below the low threshold.

          +

        Synchronous Return:

        • HASH :

          The results object which contains the error code and the description if applicable.

          +
          • status : STRING

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.setLowBatteryThreshold(INTEGER lowThreshold, STRING lowBatterMessage)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.setLowBatteryThreshold(INTEGER lowThreshold, STRING lowBatterMessage)
          • Ruby: Rho::MobilePayment.setLowBatteryThreshold(INTEGER lowThreshold, STRING lowBatterMessage)

        setProperties(HASH propertyMap)

        This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

        +

        Parameters

        • propertyMap : HASH

          Map of properties I want to set

          +

          • Object : STRING

        Synchronous Return:

        • Void

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.setProperties(HASH propertyMap)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.setProperties(HASH propertyMap)
          • Ruby: Rho::MobilePayment.setProperties(HASH propertyMap)

        setProperty(STRING propertyName, STRING propertyValue)

        This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

        +

        Parameters

        • propertyName : STRING

          The one property name that I want to set

          +

        • propertyValue : STRING

          The one property value that I want to set

          +

        Synchronous Return:

        • Void

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.setProperty(STRING propertyName, STRING propertyValue)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.setProperty(STRING propertyName, STRING propertyValue)
          • Ruby: Rho::MobilePayment.setProperty(STRING propertyName, STRING propertyValue)

        validateMac(STRING u8MACBlock, INTEGER langCode, STRING u8TPKKey, STRING u8TAKKey, STRING message1, STRING message2, STRING u8MACData, CallBackHandler callback)

        Validates the response MAC and displays any authorization messages returned by the host. This method is made Asynchronous call because it is taking more processing time and response will be returned via callback.

        +

        Parameters

        • u8MACBlock : STRING

          8-character MAC Block to verify. This is the mac block returned by createMac api.

          +

        • langCode : INTEGER

          Numeric value denoting the language code to use. Refer to the constants section to see what code to use. Currently only 0 is supported.

          +

        • u8TPKKey : STRING

          PIN (TPK) Key

          +

        • u8TAKKey : STRING

          MAC (TAK) Key

          +

        • message1 : STRING

          Message Line 1 (0-16 characters)

          +

        • message2 : STRING

          Message Line 2 (0-16 characters)

          +

        • u8MACData : STRING

          Buffer to hold all data to be MACd

          +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • status : STRING

            SUCCESS or ERROR.

            +

          • errorName : STRING

            If the status is error, this contains the ErrorName associated with that error.

            +

        Synchronous Return:

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.validateMac(STRING u8MACBlock, INTEGER langCode, STRING u8TPKKey, STRING u8TAKKey, STRING message1, STRING message2, STRING u8MACData, CallBackHandler callback)
        • Default Instance: This method can be accessed via the default instance object of this class.
          • JavaScript: Rho.MobilePayment.validateMac(STRING u8MACBlock, INTEGER langCode, STRING u8TPKKey, STRING u8TAKKey, STRING message1, STRING message2, STRING u8MACData, CallBackHandler callback)
          • Ruby: Rho::MobilePayment.validateMac(STRING u8MACBlock, INTEGER langCode, STRING u8TPKKey, STRING u8TAKKey, STRING message1, STRING message2, STRING u8MACData, CallBackHandler callback)
        + +

        Constants

        + +
        SWIPE

        swipe Read Mode for use in readCardData

        +
        INSERT

        insert Read Mode for use in readCardData

        +
        TOUCH

        touch Read Mode for use in readCardData. Currently this is not supported.

        +
        MANUAL

        Manual Mode for use in readCardData

        +
        ALL

        all Read Mode for use in readCardData

        +
        HOST_AUTHORIZED

        Host Decision is HOST_AUTHORIZED

        +
        HOST_DECLINE

        Host Decision is HOST_DECLINE

        +
        CONNECT_FAILED

        Host Decision is CONNECT_FAILED

        +
        FORCE_DECLINE

        Merchant Decision is FORCE_DECLINE

        +
        FORCE_ONLINE

        Merchant Decision is FORCE_ONLINE

        +
        REQUEST_TC

        Merchant Decision is REQUEST_TC

        +
        USA
        FRANCE
        GERMANY
        UK
        DENMARK
        SWEDEN
        ITALY
        SPAIN
        JAPAN
        NORWAY
        DENMARK2
        CHINA
        ALREADY_CLOSED
        ALREADY_ENABLED
        AUTHENTICATION_FAILED
        AUTHORIZATION_FAILED
        CARD_INSERTION_ERROR
        CARD_REMOVED
        CHIP_READ_ERROR
        CHIP_READ_NO_APP_ERROR
        COMMUNICATION_ERROR
        DEVICE_DISCONNETED
        DEVICE_NOT_ENABLED
        DEVICE_NOT_PAIRED
        DISABLE_FAILED
        ENABLE_FAILED
        FAILURE
        FEATURE_NOT_SUPPORTED
        INVALID_CONFIGURATION
        INVALID_DATA_LENGTH
        INVALID_MAC_KEY_LENGTH
        INVALID_OBJECT
        INVALID_PIN_LENGTH
        INVALID_VALUE
        LOW_POWER_OPERATION_CANCELLED
        MAC_BLOCK_CREATE_ERROR
        MAC_KEY_CREATE_ERROR
        MAC_VALIDATION_ERROR
        NO_DATA_LISTENER
        NULL_POINTER
        OK_KEY_PRESSED
        CANCEL_KEY_PRESSED
        OPERATION_CANCELLED
        PREVIOUS_COMMAND_PENDING
        SUCCESS
        TIMED_OUT
        TLV_DATA_ERROR
        UNDEFINED
        + +

        Remarks

        + +
        ReadCardData

        In Android, while method readCardData is being executed, either we can provide “messageTitle”,“message1”,“message2” all NULL or all filled. When all null, it will invoke the corresponding method, without having the message.

        +
        General

        In Android, the behaviour of data returned by various APIS is totally dependent upon the version of binary installed in the PD40 device.

        +
        \ No newline at end of file diff --git a/docs/en/5.5/api/MobilePayment.xml b/docs/en/5.5/api/MobilePayment.xml new file mode 100644 index 00000000..36646a78 --- /dev/null +++ b/docs/en/5.5/api/MobilePayment.xml @@ -0,0 +1,858 @@ + + + + The Mobile Payment module implements the functions required to work with the PD40 Bluetooth Payment MPOS. We need to include the emdk jar in the add-ons directory of android sdk in order to build it. + Before an application can use this module, the device must be paired via Bluetooth the mobile device requesting use. + If this is not done, no functions will work and the Open function will return an error of not paired. Only One PD40 device should be worked with one device. emdk3-manager extension has to be included before mobile_payment. + + ## Enabling the API + In order to use this API you must include the following extension in your `build.yml`. + :::ruby + extensions: ["mobile_payment"] + ## JavaScript Usage + Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + + ## Ruby Usage + Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + + + + + + + + + + + + swipe Read Mode for use in readCardData + + + insert Read Mode for use in readCardData + + + + touch Read Mode for use in readCardData. Currently this is not supported. + + + Manual Mode for use in readCardData + + + all Read Mode for use in readCardData + + + + + Host Decision is HOST_AUTHORIZED + + + Host Decision is HOST_DECLINE + + + Host Decision is CONNECT_FAILED + + + + + Merchant Decision is FORCE_DECLINE + + + Merchant Decision is FORCE_ONLINE + + + Merchant Decision is REQUEST_TC + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Opens the PD40 Payment reader. Will fail if not paired manually beforehand. + + + The name of the PD40 device which is paired and to be worked with. + + + + + + Will contain either success or error. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + + + + + Close unitializes and disconnects the PD40 payment device. + + + + + Will contain either success or error. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + + + + Returns whether the PD40 device is enabled or not. + + Returns true if PD40 is opened,otherwise false. + + + + Reads the card data from the PAYMENT device through a swipe (MagStripe), insert (for smart cards). + This is asynchronous so the return data is passed back through the callback. + + + The properties associated with reading card data. + + + Amount for the transaction; this value is required to enable EMV contactless transactions. Allowed upto a maximum of 7 digits. + + + Any additional amount information for the transaction; this value is used only if EMV Contactless is supported. Allowed upto a maximum of 7 digits + + + Use the constants defined in the XML for use with READMODE + + + The message Title to be displayed on the card data request. The maximum length is 18 characters. The character "|" not allowed. Please see remarks section. + + + The custom message to be displayed on the card data request. The maximum length is 18 characters. The character "|" not allowed.Please see remarks section. + + + The custom message to be displayed on the card data request. The maximum length is 18 characters. The character "|" not allowed. + Please see remarks section. + + + + Read timeout in milliseconds. App can set the timeout, but value used must be within the threshold set by the payment device. + + + + + + + + + Will contain either success or error depending on outcome of call. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + + + + + + + + + + + + + + + + + + + + + + Requests for a PIN and gets the encrypted PIN block. The encrypted data will be returned only if a debit key is injected into the payment device. This is asynchronous call Note: The character "|" not allowed in the message strings for PD40-100 payment device and it is used as special character in the in the EMDK for PD40-100 device. Requesting promptPin() continuously may pop up the timer on PD40-100 payment device for security reasons and application should wait for this before performing any other actions. + + + The properties associated with promptPin. + + + + The account number used with the entered PIN to create the encrypted PIN Block (8 to 19 alphanumeric digits inclusive). + + + + Minimum PIN Length. A minimum length of 4 digits is required. + + + + Maximum PIN Length. A maximum length of 12 digits is allowed. + + + isPinOptional is always false. It is kept for future modification. + + + + + Message 1 to be displayed on the PINPad (alternates with Message 2). Maximum message length 21 characters. + + + + Message 2 to be displayed on the PINPad (alternates with Message 1). Maximum message length 21 characters. + + + + Message Title to be displayed during PIN entry. + + + + Read timeout in milliseconds. App can set the timeout, but value must be within threshold set by the payment device. + + + + + + + + + + Success for Error depending upon the outcome of the call. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + returns the pin block string + + + Returns the serial number + + + returns true or false on whether the pin is entered by the user or not + + + + + + + Displays two lines of messages on the PAYMENT device and provides a menu with a maximum of 4 choices. This is asynchronous call. The character "|" not allowed in the message strings and it is used as special character in the EMDK for PD40-100. + + + The properties associated with the promptMessage function. + + + Message Line1 to display on the PINPad screen. Maximum characters allowed for Choice + Message = 18 characters. + For example, if Choice is 6 characters, maximum message length is 12 characters. + Messages longer than maximum message length will be truncated. + + + Message Line2 to display on the PINPad screen. Maximum characters allowed for Choice + Message = 18 characters. + For example, if Choice is 6 characters, maximum message length is 12 characters. + Messages longer than maximum message length will be truncated. + + + Choice text for selection from the PINPad using the function keys. + Choice string can consist of up to 8 characters. + + + Choice text for selection from the PINPad using the function keys. + Choice string can consist of up to 8 characters. + + + Choice text for selection from the PINPad using the function keys. + Choice string can consist of up to 8 characters. + + + Choice text for selection from the PINPad using the function keys. + Choice string can consist of up to 8 characters. + + + Timeout in milliseconds. App can set the timeout, + but value must be within threshold set by the payment device. + + + + + + + + + Success or Failure depending upon the outcome of the function + + + The choice that was decided by the user on status is success. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + + + + + Requests the user to confirm the amount and surcharge passed by the application and prompts the user to provide tip and cashback. The tip, cashback values and the confirmation if surcharge was accepted, will be returned to the application via callback. If the user presses OK or CANCEL keys, or the call times out, the corresponding message is returned. This is asynchronous call. + + + The properties associated with the promptMessage function. + + + Transaction amount value that is displayed, valid range is from 0.01 to 999999.99 + + + Numeric value denoting the language code for determining language of the pre-defined prompt. Languages currently supported are listed in the constants section. Other languages can be used, but all information relating to that is the responsibility of the calling application. Currenly supported only 0 i.e. US + + + Indicates whether or not to prompt for tip and return the amount desired. + + + Indicates whether or not to prompt for cashback and return the amount selected. The user would select cashback amount from 4 pre-defined - $20, $40, $60 and $100. These choices cannot be modified. + + + An optional surcharge amount that is to be displayed and confirmed (valid range is from 0.01 to 99.99). A zero amount will cause this prompt to be bypassed. + + + Read timeout in milliseconds. The app can set the timeout, but the value must be within the threshold set by the payment device. + + + + + + + + + Success or Failure depending upon outcome of function + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + If a tip was input, this will contain that value, 0.00 otherwise + + + If cashback is asked for, this contains the amount given. + + + + + + + + + Displays a maximum of 4 line messages on the PAYMENT device. This method also allows a user confirmation. + This can be done by setting the 5th parameter to true, in which case a string containing OK, CANCEL, CORR or TIMEOUT (after 15 seconds). + This is an asynchronous call and all data is returned in the callback. + + + The properties associated with the promptMessage function. + + + A message to display on line 1 of the PINPad screen, may consist of up to 16 characters. + + + A message to display on line 1 of the PINPad screen, may consist of up to 16 characters. + + + A message to display on line 1 of the PINPad screen, may consist of up to 16 characters. + + + A message to display on line 1 of the PINPad screen, may consist of up to 16 characters. + + + true or false. Allows the user to press OK (Enter Key), CANCEL or CORR keys in response to the displayed message. If getUserConfirmation is false, this is a synchronous call. + + + Read timeout in milliseconds. The app can set the timeout, but the value must be within the threshold set by the payment device. + + + + + + + + + Success or Error depending on outcome of function. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + Will contain OK, CANCEL or CORR depending upon what the user pressed. + + + + + + + Cancel previously issued method and display welcome screen on PAYMENT device. + + + + Success or Failure depending on outcome of function. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + + + + + Query the battery level of the payment device. + + + + + success or error. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + If the status is success, this contains the battery level. Value would be 1,2,3,4. + + + + + + + Returns information about the payment device. + + + + success or error. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + Application Version of PD40. + + + + Firmware Version of PD40. + + + + Connection Type Version of PD40. + + + + Device Type of PD40. + + + + Friendlyname of PD40. + + + + + + + + + This is a required transaction for Canada. Accepts a String of data to be MACed using the ANSI x9.91 standard and the MAC Working Key. This is used for MACing credit transactions when the PINPad is configured to support both credit and debit. This is synchronous call. + + + String of data to be MACed. The length of the key should be 16 or 32 or 48 in HEX format. + + + + This is a required transaction for Canada. Accepts a String of data to be MACed using the ANSI x9.91 standard and the MAC Working Key. This is used for MACing credit transactions when the PINPad is configured to support both credit and debit. + + + + SUCCESS or ERROR. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + If the status is succes, it returns macBlock. + + + + + + + + + Validates the response MAC and displays any authorization messages returned by the host. This method is made Asynchronous call because it is taking more processing time and response will be returned via callback. + + + 8-character MAC Block to verify. This is the mac block returned by createMac api. + + + Numeric value denoting the language code to use. Refer to the constants section to see what code to use. Currently only 0 is supported. + + + PIN (TPK) Key + + + MAC (TAK) Key + + + Message Line 1 (0-16 characters) + + + Message Line 2 (0-16 characters) + + + Buffer to hold all data to be MACd + + + + + + + SUCCESS or ERROR. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + + + + + + Completes an online EMV transaction for PIN management. The application must call authorizeCard before calling this API. This is an asynchronous call. After the processing, the response (i.e., EmvData object) is returned through the registered Callback. + + + HostDecision enum value which is the decision indicator from the host response. Use the constants "HOST DEFINED" defined in the XML document. + + + Indicator to note whether or not to display the final response message. False for Do not display and true to Display. + + + List of EMV data which contains EMV tag and its values. + + + + + + + + Either SUCCESS or ERROR + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + An array of the returned Tags requested. + + + + + + + + Gets tag information from the inserted card. This is an asynchronous call. After the processing, the response (TagData contains TLV raw data as per EMV specification)and also its parsed tag, length and value format is returned through the registered Callback.Before calling this method,readcarddata has to be called. + + + Array containing EMV tag IDs to be retrieved from the inserted card. Refer to the EMV Tags section in the documentation to + know which TAG IDs can be requested with this call. Any number of Tag IDs are allowed and the number of Tag IDs will match the number of tag values. + + + + + + + Either SUCCESS or ERROR + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + An array of the returned Tags requested. + + + + + + + + Sets tag information for the inserted card. Valid EMV tag IDs and tag values should be passed. Passing invalid EMV tag IDs or tag values may cause the payment device to go into unstable state or unknown behavior. The payment device has to be rebooted in order to continue normal operation.Before calling this method,readcarddata has to be called. + + + Array containing valid EMV tag IDs to be set on the inserted card.Before calling this method,readcarddata has to be called. + + + + + + Either SUCCESS or ERROR + + + + If the status is error, this contains the ErrorName associated with that error. + + + + + + + + Authorizes the EMV transaction amounts using the inserted chip (EMV) card. This is an asynchronous call. Before calling this method,readcarddata has to be called. + + + Transaction amount value. + + + Other transaction amount value. + + + The merchant decision notes additional handling for the EMV request based on required processor handling. + Please use the constants for Merchant Decision. + + + EMV tags that are required at this transaction stage to be retrieved. + + + true or false. Display result on Payment device. + + + true or false. Displays when PIN tries have exceeded value on Payment device. + + + true or false. Displays amount of Payment device. + + + true or false. Displays if app is expired on Payement display. + + + Card authorization timeout. Application must set the timeout. + + + + + + + Either SUCCESS or ERROR + + + If the status is error, this contains the ErrorName associated with that error. + + + + An array of the returned Tags requested. + + + key Serial no + + + pin block + + + + + + Instruct the user to remove the EMV card inserted in the payment device. This call prompts the user to remove the inserted EMV chip card and also clears the EMV data saved by readCardData method. If the card is NOT inserted, it will give success. + + + The message which gives the information of type of card. + + + The message which gives instructions to user for the removal of the card. + + + + + The results describes the succesfulness of the operation. + + + Either SUCCESS or ERROR + + If the status is error, this contains the ErrorName associated with that error. + + + + + + + Gets the acceptable low battery level. If the battery drops below this value, the device will not execute any of the selected commands.. + + + + + success or error. + + + + If the status is error, this contains the ErrorName associated with that error. + + + + If the status is success, this contains the battery level. Value would be 1,2,3,4. + + + + + + + + Sets the acceptable low battery percent. If the battery drops below this value, the device will not execute some of the commands. + and it will return the error code indicating the battery is low. + + + + Battery threshold value. Below this value, some of the commands will not execute + + + The message to be displayed when the battery level goes below the low threshold. + + + + + The results object which contains the error code and the description if applicable. + + + Either SUCCESS or ERROR + + If the status is error, this contains the ErrorName associated with that error. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1.0.0 + Android + + diff --git a/docs/en/5.5/api/NativeMenubar.md b/docs/en/5.5/api/NativeMenubar.md new file mode 100644 index 00000000..eea44c36 --- /dev/null +++ b/docs/en/5.5/api/NativeMenubar.md @@ -0,0 +1,97 @@ +#NativeMenubar +
        +

        The NativeMenubar API lets you customize the Windows Mobile/CE native menu buttons.

        +

        Enabling the API

        + +

        This API is part of the coreapi extension that is included automatically.

        + +
        :::ruby
        +extensions: ["coreapi"]
        +
        + +

        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.

        + + + +

        Properties

        + +

        defaultMainMenu : ARRAY Read Only

        This will return what the default right menu should be. This is a read-only property.

        +

      • Object : HASH

      • Property Access:

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

        extraButton : HASH

        Defined behavior of the Left menu button for Windows Mobile applications. This takes the same HASH as a menu item {label: ‘Left Button’, action: ‘alert(“You pressed the left button”)’}. If your menu is using menu items via mainMenu, then be sure to not set an action for the extraButton. Setting an action for the extraButton will cause the mainMenu setting to be ignored.

        +

        Property Access:

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

        extraMenu : ARRAY

        The Left menu items for Windows Mobile applications. This defines the list of menu choices when the extraButton is pressed.

        +

      • Object : HASH

        Same values as for mainMenu.

        +

      • Property Access:

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

        mainButton : HASH

        Defined behavior of the Right menu button for Windows Mobile applications. This takes the same HASH as a menu item {label: ‘Right Button’, action: ‘javascript: alert(“You pressed the right button”);’}. If your menu is using menu items via mainMenu, then be sure to not set an action for the mainButton. Setting an action for the mainButton will cause the mainMenu setting to be ignored.

        +

        Property Access:

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

        mainMenu : ARRAY

        The Right menu items in Windows Mobile applications. This defines the list of menu choices when the mainButton is pressed.

        +

      • Object : HASH

        • label : STRING

          Visible label.

          +

        • action : STRING

          URL to page which will be loaded into tab. It may be path to Ruby controller action; i.e. ‘/app/Account’ would load the Account index action. For ruby callback use ‘callback:/app/Account’ Or JavaScript method to call: ‘javascript: methodOnTab();’. Or path to html page to load.

          +

        • disabled : BOOLEAN Default: false

          Menu item will be displayed as disabled.

          + Platforms:WM

        Property Access:

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

        Examples

        + +
        Customize the extra menu
        +
        :::javascript
        +
        +                  
        +Rho.NativeMenubar.extraButton = {
        +    label: "Extra"
        +};
        +
        +Rho.NativeMenubar.extraMenu = [
        +  {
        +      label: "Show alert 1",
        +      action: javascript:show_alert_1();,
        +  },
        +  {
        +      label: "Show alert 2",
        +      action: javascript:show_alert_2();,
        +  },
        +  {
        +      label: "Win the lottery",
        +      disabled: true
        +  }
        +];
        +                  
        +                 
        :::ruby
        +
        +                  
        +Rho::NativeMenubar.extraButton = {
        +  :label => "Extra"
        +}
        +
        +Rho::NativeMenubar.extraMenu = [
        +  {
        +    :label => "Show alert 1",
        +    :action => url_for(:action => :show_alert_1)
        +  },
        +  {
        +    :label => "Show alert 2",
        +    :action => url_for(:action => :show_alert_2)
        +  },
        +  {
        +    :label => "Win the lottery",
        +    :disabled => true
        +  }
        +]
        +                  
        +                 
        Clear the main menu
        +
        :::javascript
        +
        +                  
        +function remove_menuitems() {
        +    Rho.NativeMenubar.mainMenu = [];
        +}
        +                  
        +                 
        :::ruby
        +
        +                  
        +def remove_menuitems
        +  Rho::NativeMenubar.mainMenu = []
        +end
        +                  
        +                 
        \ No newline at end of file diff --git a/docs/en/5.5/api/NativeMenubar.xml b/docs/en/5.5/api/NativeMenubar.xml new file mode 100644 index 00000000..8b70939e --- /dev/null +++ b/docs/en/5.5/api/NativeMenubar.xml @@ -0,0 +1,183 @@ + + + + + The NativeMenubar API lets you customize the Windows Mobile/CE native menu buttons. + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the NativeMenubar API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the NativeMenubar API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.nativemenubar.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + WM + + + + + + + The Right menu items in Windows Mobile applications. This defines the list of menu choices when the mainButton is pressed. + + + + Visible label. + + + URL to page which will be loaded into tab. It may be path to Ruby controller action; i.e. '/app/Account' would load the Account index action. For ruby callback use 'callback:/app/Account' Or JavaScript method to call: 'javascript: methodOnTab();'. Or path to html page to load. + URL to page which will be loaded into tab. It may be a JavaScript method to call: 'javascript: methodOnTab();'. Or path to html page to load. + + + Menu item will be displayed as disabled. + WM + + + + WM + + + The Left menu items for Windows Mobile applications. This defines the list of menu choices when the extraButton is pressed. + WM + + Same values as for mainMenu. + + + + + Defined behavior of the Right menu button for Windows Mobile applications. This takes the same HASH as a menu item {label: 'Right Button', action: 'javascript: alert("You pressed the right button");'}. If your menu is using menu items via mainMenu, then be sure to not set an action for the mainButton. Setting an action for the mainButton will cause the mainMenu setting to be ignored. + WM + + + Defined behavior of the Left menu button for Windows Mobile applications. This takes the same HASH as a menu item {label: 'Left Button', action: 'alert("You pressed the left button")'}. If your menu is using menu items via mainMenu, then be sure to not set an action for the extraButton. Setting an action for the extraButton will cause the mainMenu setting to be ignored. + WM + + + + + This will return what the default right menu should be. This is a read-only property. + + WM + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + + + + +
        + + + "Extra" +} + +Rho::NativeMenubar.extraMenu = [ + { + :label => "Show alert 1", + :action => url_for(:action => :show_alert_1) + }, + { + :label => "Show alert 2", + :action => url_for(:action => :show_alert_2) + }, + { + :label => "Win the lottery", + :disabled => true + } +] + ]]> + + + + + +
        +
        +
        + + +
        + + + + + + + + +
        +
        +
        +
        +
        +
        \ No newline at end of file diff --git a/docs/en/5.5/api/NativeTabbar.md b/docs/en/5.5/api/NativeTabbar.md new file mode 100644 index 00000000..bc7322dd --- /dev/null +++ b/docs/en/5.5/api/NativeTabbar.md @@ -0,0 +1,133 @@ +#NativeTabbar +
        +

        The NativeTabbar methods let you use multiple instances of the RhoMobile webview in separate tabs.

        +

        On Android, iOS and WIndows Phone 8 the tabs are true Native Tabbar controls to give your application a native look and feel.No more than 4 tabs can be created in the Windows Phone 8 tabbar. A tabbar separator doesn’t exist in Windows Phone 8. On Windows Mobile/CE there are no visible tabs. Either Tabbar or Toolbar should be used in an application – Tabbar and Toolbar shouldnot be used simultaneously.

        + +

        Enabling the API

        + +

        This API is part of the coreapi extension that is included automatically.

        + +
        :::ruby
        +extensions: ["coreapi"]
        +
        + +

        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

        + +

        create(ARRAY tabElements, HASH tabBarProperties, CallBackHandler callback)

        Removes the current tabbar and replaces it with this one. Callback will be called when tab is switched. Whilst the actual number of tabs you can create will depend on the memory available on your device there is an absolute upper limit of 30 tabs in any one application.

        +

        Parameters

        • tabElements : ARRAY

          Array of Tab elements.

          +

          • tabElement : HASH

            Properties of Tab elements.

            +

            • label : STRING

              Visible label to display on the tabbar.

              +

            • action : STRING

              URL to page which will be loaded into tab. Predefined actions are not supported. It may be path to Ruby controller action; i.e. ‘/app/Account’ would load the Account index action. For ruby callback use ‘callback:/app/Account’ Or javascript method to call: ‘javascript: methodOnTab();’. Or path to html page to load.

              +

            • icon : STRING

              Relative path to tabbar item icon in your application; typically located in /public/images/.

              + Platforms:Win32, Android, iOS, WP8

            • reload : BOOLEAN Default: false

              When tab is activated – page in tab will be reloaded.

              +

            • selectedColor : INTEGER

              Change the selected color of this tab. On Android this works only if you setup selectedColor for all tabs and also setup backgroundColor for the whole Tabbar. This property change background color on Android and icon’s color on iOS according to the platform’s UI-style specifications.

              + Platforms:Win32, Android, iOS, WP8

            • disabled : BOOLEAN Default: false

              Tab will be displayed as disabled.

              + Platforms:Win32, Android, iOS, WP8

            • backgroundColor : INTEGER

              Background color for tab. Use when your application background color is not white for removing blink during switch tabs.

              + Platforms:Win32, Android, iOS, WP8

            • useCurrentViewForTab : BOOLEAN Default: false

              Gives a smooth transfer to a newly opened tab from the current view into this Tab and make this Tab active. Only one Tab can have this parameter.

              + Platforms:WM, CE, Win32, Android, iOS

            • perishable : BOOLEAN Default: false

              Sets whether this tab is allowed to be destroyed when a memory limit is reached (Windows Mobile)

              + Platforms:WM

            • createOnInit : BOOLEAN Default: false

              Create tab immediately when TabBar is created. Action also will be executed. If false, the tab will be created when it is switched to. Don’t use this parameter on the devices with a small amount of RAM.

              + Platforms:WM

        • tabBarProperties : HASH

          Properties of TabBar.

          +

          • verticalOrientation : BOOLEAN Default: false

            Creates a vertical tabbar on the iPad.

            + Platforms:iOS

          • backgroundColor : INTEGER

            Background color of the tabbar.

            + Platforms:Win32, Android, iOS, WP8

          • hiddenTabs : BOOLEAN Default: true

            Do not display Tabs with labels.Only hiddenTab=true is currently supported.

            + Platforms:WM

          • createOnInit : BOOLEAN Default: false

            Create tabs immediately when TabBar is created. Action also will be executed. If false, then each tab will be created when first switch to the tab is executed. Don’t use this parameter on the devices with a small amount of RAM.

            + Platforms:WM

          • placeTabsBottom : BOOLEAN

            Place TabBar to bottom instead of default top – only for Android.

            + Platforms:Android

        • callback : CallBackHandler Optional

        Async Callback Returning Parameters: HASH

          • tab_index : INTEGER

            New tab index.

            +

          • newTabIndex : INTEGER

            New tab index.

            + Platforms:WM

          • oldTabIndex : INTEGER

            New tab index. If you switched to first activated tab, when oldTabIndex will be -1, which means that there was no old tab index exists.

            + Platforms:WM

          • tabEvent : STRING

            Platforms:WM

            Possible Values :

            onTabFocus

            Fires when a tab gains focus.

            +
            onTabNewError

            Fires when a new tab cannot be created.

            +

        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.NativeTabbar.create(ARRAY tabElements, HASH tabBarProperties, CallBackHandler callback)
          • Ruby: Rho::NativeTabbar.create(ARRAY tabElements, HASH tabBarProperties, CallBackHandler callback)

        currentTabIndex()

        Replaces: get_current_tab

        Returns the current tab 0-based index.

        +

        Synchronous Return:

        • INTEGER

        Method Access:

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

        remove()

        Removes all tabbar except the default tabbar whose index value is 0. Does nothing if there is no active tabbar other than tab 0.

        +

        Synchronous Return:

        • Void

        Method Access:

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

        removeTab(INTEGER tabIndex)

        Removes the Tab by index. Method will remove the WebView for the specific tab, it will not remove the tab from the tab array, so all indexes will remain the same.You cannot delete the tab with useCurrentViewForTab flag.If you switch to previously removed tab, tab will be recreated.

        +

        Parameters

        • tabIndex : INTEGER

          The index for tab (index numbered from 0) to delete.

          +

        Synchronous Return:

        • Void

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.NativeTabbar.removeTab(INTEGER tabIndex)
          • Ruby: Rho::NativeTabbar.removeTab(INTEGER tabIndex)

        setTabBadge(INTEGER tabIndex, STRING badge)

        Set the iPhone badge to tab.

        +

        Parameters

        • tabIndex : INTEGER

          The index for this tab (index numbered from 0). You can also set -1 to select current tab for set badge.

          +

        • badge : STRING

          String for iPhone badge, such as ‘12’.

          +

        Synchronous Return:

        • Void

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.NativeTabbar.setTabBadge(INTEGER tabIndex, STRING badge)
          • Ruby: Rho::NativeTabbar.setTabBadge(INTEGER tabIndex, STRING badge)

        switchTab(INTEGER tabIndex)

        Switch active tab.

        +

        Parameters

        • tabIndex : INTEGER

          The index for this tab (index numbered from 0).

          +

        Synchronous Return:

        • Void

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.NativeTabbar.switchTab(INTEGER tabIndex)
          • Ruby: Rho::NativeTabbar.switchTab(INTEGER tabIndex)
        + +

        Examples

        + +
        Create native tabbar
        +

        Create a platform-native tabbar. Tabs can link to internal application links (such as those built with “url_for”) as well as external URLs.

        +
        :::javascript
        +
        +           
        +function create_tabbar() {
        +    Rho.NativeTabbar.create([{
        +            label: "Home",
        +            action: "/app"
        +        }, {
        +            label: "example.com"
        +            action: "http://www.example.com"
        +        }], {}, tabbar_callback
        +    );
        +}
        +
        +function tabbar_callback(params) {
        +    alert("Switching to tab "+params["tab_index"]);
        +}
        +                   
        +                 
        :::ruby
        +
        +           
        +def create_tabbar
        +    Rho::NativeTabbar.create([{
        +      :label => "Home",
        +      :action => url_for(Rho::Application.startURI)
        +      },
        +      {
        +      :label => "example.com",
        +      :action => "http://www.example.com",
        +      }], {}, url_for(:action => :tabbar_callback)
        +    )
        +end
        +
        +def tabbar_callback
        +    Alert.show_popup("Switching to tab #{@params["rab_index"]}")
        +end
        +                   
        +                 
        Switch tab
        +

        Switch the active tab.

        +
        :::javascript
        +
        +           
        +// Make the third tab active
        +Rho.NativeTabbar.switchTab(2);
        +                   
        +                 
        :::ruby
        +
        +           
        +# Make the third tab active
        +Rho::NativeTabbar.switchTab(2);
        +                   
        +                 
        Remove tabbar
        +

        Remove the tabbar.

        +
        :::javascript
        +
        +           
        +Rho.NativeTabbar.remove();
        +                   
        +                 
        :::ruby
        +
        +           
        +Rho::NativeTabbar.remove
        +                   
        +                 
        + +

        Remarks

        + +
        Device Limitations With Multiple Tabs

        Please consider the limitations of the device when creating multiple tabs with the Native TabBar. The number of tabs that can be created will depend on the resources of the device and the complexities of the pages displayed in those tabs but, as a general rule, a maximum of 10 tabs on an MC75a should be enforced. Also consider setting the createOnInit property to false so that not all tabs are initialized when the TabBar is first created and using the in-process engine for a more responsive experience.

        +
        \ No newline at end of file diff --git a/docs/en/5.5/api/NativeTabbar.xml b/docs/en/5.5/api/NativeTabbar.xml new file mode 100644 index 00000000..b77b746d --- /dev/null +++ b/docs/en/5.5/api/NativeTabbar.xml @@ -0,0 +1,322 @@ + + + + + The NativeTabbar methods let you use multiple instances of the RhoMobile webview in separate tabs. + On Android, iOS and WIndows Phone 8 the tabs are true Native Tabbar controls to give your application a native look and feel.No more than 4 tabs can be created in the Windows Phone 8 tabbar. A tabbar separator doesn't exist in Windows Phone 8. On Windows Mobile/CE there are no visible tabs. Either Tabbar or Toolbar should be used in an application - Tabbar and Toolbar shouldnot be used simultaneously. +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + On Android, the tabs are true Native Tabbar controls to give your application a native look and feel. On Windows Mobile/CE there are no visible tabs, but can be used in conjunction with shortcuts to run multiple 'applications' from a single instance. Either Tabbar or Toolbar should be used in an application - Tabbar and Toolbar shouldnot be used simultaneously. +## Enabling the API +There are two methods of enabling the NativeTabbar API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the NativeTabbar API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.nativetabbar.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + + + + + + Removes the current tabbar and replaces it with this one. Callback will be called when tab is switched. Whilst the actual number of tabs you can create will depend on the memory available on your device there is an absolute upper limit of 30 tabs in any one application. + + + Array of Tab elements. + + + Properties of Tab elements. + + + Visible label to display on the tabbar. + + + URL to page which will be loaded into tab. Predefined actions are not supported. It may be path to Ruby controller action; i.e. '/app/Account' would load the Account index action. For ruby callback use 'callback:/app/Account' Or javascript method to call: 'javascript: methodOnTab();'. Or path to html page to load. + URL to page which will be loaded into tab. It may be JavaScript method to call: 'javascript: methodOnTab();'. Or path to html page to load. + + + Relative path to tabbar item icon in your application; typically located in /public/images/. + Icon Relative path (from Enterprise Browser application) to local files on the device. + Win32, Android, iOS, WP8 + Win32, Android + + + When tab is activated - page in tab will be reloaded. + + + Change the selected color of this tab. On Android this works only if you setup selectedColor for all tabs and also setup backgroundColor for the whole Tabbar. This property change background color on Android and _icon's_ color on iOS according to the platform's UI-style specifications. + Change the selected color of this tab. On Android this works only if you setup selectedColor for all tabs and also setup backgroundColor for the whole Tabbar. This property change background color on Android according to the platform's UI-style specifications. + Win32, Android, iOS, WP8 + Win32, Android + + + Tab will be displayed as disabled. + Win32, Android, iOS, WP8 + Win32, Android + + + Background color for tab. Use when your application background color is not white for removing blink during switch tabs. + Win32, Android, iOS, WP8 + Win32, Android + + + Gives a smooth transfer to a newly opened tab from the current view into this Tab and make this Tab active. Only one Tab can have this parameter. + WM, CE, Win32, Android, iOS + WM, CE, Win32, Android + + + + Sets whether this tab is allowed to be destroyed when a memory limit is reached (Windows Mobile) + WM + + + + WM + Create tab immediately when TabBar is created. Action also will be executed. If false, the tab will be created when it is switched to. Don't use this parameter on the devices with a small amount of RAM. + + + + + + + Properties of TabBar. + + + Creates a vertical tabbar on the iPad. + iOS + + + Background color of the tabbar. + Win32, Android, iOS, WP8 + Win32, Android + + + WM + Do not display Tabs with labels.Only hiddenTab=true is currently supported. + + + WM + Create tabs immediately when TabBar is created. Action also will be executed. If false, then each tab will be created when first switch to the tab is executed. Don't use this parameter on the devices with a small amount of RAM. + + + Android + Place TabBar to bottom instead of default top - only for Android. + + + + + + + Information about tab changes. + + + New tab index. + + + New tab index. + WM + + + New tab index. If you switched to first activated tab, when oldTabIndex will be -1, which means that there was no old tab index exists. + WM + + + + WM + + + Fires when a tab gains focus. + + + Fires when a new tab cannot be created. + + + + + + + + + Returns the current tab 0-based index. + + + + + + Removes all tabbar except the default tabbar whose index value is 0. Does nothing if there is no active tabbar other than tab 0. + + + + Removes the Tab by index. Method will remove the WebView for the specific tab, it will not remove the tab from the tab array, so all indexes will remain the same.You cannot delete the tab with useCurrentViewForTab flag.If you switch to previously removed tab, tab will be recreated. + WM + + + The index for tab (index numbered from 0) to delete. + + + + + + Set the iPhone badge to tab. + iOS + + + The index for this tab (index numbered from 0). You can also set -1 to select current tab for set badge. + + + String for iPhone badge, such as '12'. + + + + + + Switch active tab. + + + The index for this tab (index numbered from 0). + + + + + + If Tabbar already created. + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + Please consider the limitations of the device when creating multiple tabs with the Native TabBar. The number of tabs that can be created will depend on the resources of the device and the complexities of the pages displayed in those tabs but, as a general rule, a maximum of 10 tabs on an MC75a should be enforced. Also consider setting the `createOnInit` property to false so that not all tabs are initialized when the TabBar is first created and using the in-process engine for a more responsive experience. + + + + + +
        + Create a platform-native tabbar. Tabs can link to internal application links (such as those built with "url_for") as well as external URLs. + + + "Home", + :action => url_for(Rho::Application.startURI) + }, + { + :label => "example.com", + :action => "http://www.example.com", + }], {}, url_for(:action => :tabbar_callback) + ) +end + +def tabbar_callback + Alert.show_popup("Switching to tab #{@params["rab_index"]}") +end + ]]> + + + + + +
        +
        +
        + + +
        + Switch the active tab. + + + + + + + + +
        +
        +
        + + +
        + Remove the tabbar. + + + + + + + + +
        +
        +
        +
        +
        +
        diff --git a/docs/en/5.5/api/NativeToolbar.md b/docs/en/5.5/api/NativeToolbar.md new file mode 100644 index 00000000..3c110b37 --- /dev/null +++ b/docs/en/5.5/api/NativeToolbar.md @@ -0,0 +1,98 @@ +#NativeToolbar +
        +

        The NativeToolbar method let you create and remove a toolbar at runtime.

        +

        Either Toolbar or Tabbar should be used in an application – Toolbar and Tabbar shouldnot be used simultaneously.

        + +

        Enabling the API

        + +

        This API is part of the coreapi extension that is included automatically.

        + +
        :::ruby
        +extensions: ["coreapi"]
        +
        + +

        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

        + +

        create(ARRAY toolbarElements, HASH toolBarProperties)

        Creates a new toolbar and removes the current toolbar and replaces it with this one. Any images used for UI elements should be specified by either an absolute path. i.e. ‘/sdcard/nmt/blabla.com.bla./data/public/img/button.png’

        +

        Parameters

        • toolbarElements : ARRAY

          Array of Toolbar elements. Do not create more than five elements for maximum portability.Toolbar elements are not scrollable, so if some buttons will not fit into the screen dimensions, they will be invisible.

          +

          • toolbarElement : HASH

            Properties of Toolbar elements. Either :icon or :label must be specified. If both are specified, :icon is drawn and :label is discarded.

            +

            • label : STRING

              Visible label to display instead of an icon.For predefined actions, icon will be displayed. Android, iOS note: for predefined actions no label will be displayed.

              +

            • action : STRING

              URL to call when button is pressed or special value.It may be path to Ruby controller action; i.e. ‘/app/Account’ would load the Account index action. For ruby callback use ‘callback:/app/Account’ Or javascript method to call: ‘javascript: methodOnButton();’.

              +

              Possible Values :

              separator

              Add a separator to the toolbar. If only one separator is specified, then elements after separator will be right-aligned. If more then one separator is added: on WM/CE, platform dependent separator will be displayed, on Android/iOS center-aligned groups will be created.

              + Platforms:

              WM, CE, Win32, iOS, Android

              +
              exit

              Exit the application.

              +
              close

              Exit the application.

              +
              options

              Navigate to Settings page, defined in configuration file.

              +
              home

              Navigate to Home page, defined in configuration file.

              +
              refresh

              Refresh current page.

              +
              back

              Perform back action or execute browser back.

              +
              log

              Display Log View window.

              + Platforms:

              WM, CE, Win32, iOS, Android

              +
              fullscreen

              Expand application window to full screen.

              + Platforms:

              WM, CE, Win32, Android, WP8

              +
              sync

              Run full sync command.

              +
              minimize

              Minimize application window.

              + Platforms:

              WM, CE, Win32

              +
              SIP

              Display software keyboard window.Set Rho.System.keyboardState to Rho.System.KEYBOARD_AUTOMATIC to use this element.

              + Platforms:

              WM

              +
            • icon : STRING

              Relative path to toolbar item icon in your rhodes app (typically located in ‘/public/images/’). Icon is ignored for predefined actions, icon will be displayed even if no icon specified. iPhone and Android: Icons must be no more than 30x30 pixels and must be in .png format. Windows Mobile: Icons can be any size, but all icons should have same size (default – 48x48). .png and .bmp formats are supported.

              +

            • coloredIcon : BOOLEAN Default: false

              Use colored icon in toolbar on iPhone instead of standard monochrome white icon (prepared from image alpha).

              + Platforms:iOS

            • width : INTEGER

              Button width in pixel. Used to define separator width when more than one separator specified.

              + Platforms:WM

        • toolBarProperties : HASH

          Properties of TabBar.

          +

          • backgroundColor : INTEGER

            Background color of the toolbar.

            +

          • maskColor : INTEGER Default: 0xFFFFFF

            Image mask color(transparent color).

            + Platforms:WM, CE, Win32

          • viewHeight : INTEGER

            Toolbar height in pixels.

            + Platforms:WM, CE, Win32

        Synchronous Return:

        • Void

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.NativeToolbar.create(ARRAY toolbarElements, HASH toolBarProperties)
          • Ruby: Rho::NativeToolbar.create(ARRAY toolbarElements, HASH toolBarProperties)

        remove()

        Removes the current toolbar. Does nothing if there is no active toolbar.

        +

        Synchronous Return:

        • Void

        Method Access:

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

        Examples

        + +
        Create native toolbar
        +

        Create a native Toolbar.

        +
        :::javascript
        +
        +           
        +Rho.NativeToolbar.create([{
        +        label: "Home",
        +        action: Rho.Application.startURI
        +    }, {
        +        label: "example.com",
        +        action: "http://www.example.org"
        +    }], {})
        +                   
        +                 
        :::ruby
        +
        +           
        +Rho::NativeToolbar.create([{
        +  :label => "Home",
        +  :action => url_for(Rho::Application.startURI)
        +  },
        +  {
        +  :label => "example.com",
        +  :action => "http://www.example.com",
        +  }
        +], {})
        +                   
        +                 
        Remove the toolbar
        +

        Remove the toolbar.

        +
        :::javascript
        +
        +           
        +Rho.NativeToolbar.remove();
        +                   
        +                 
        :::ruby
        +
        +           
        +Rho::NativeToolbar.remove
        +                   
        +                 
        \ No newline at end of file diff --git a/docs/en/5.5/api/NativeToolbar.xml b/docs/en/5.5/api/NativeToolbar.xml new file mode 100644 index 00000000..ceb414ba --- /dev/null +++ b/docs/en/5.5/api/NativeToolbar.xml @@ -0,0 +1,226 @@ + + + + + The NativeToolbar method let you create and remove a toolbar at runtime. + Either Toolbar or Tabbar should be used in an application - Toolbar and Tabbar shouldnot be used simultaneously. +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the Nativetoolbar API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Nativetoolbar API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.nativetoolbar.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + + + + + Creates a new toolbar and removes the current toolbar and replaces it with this one. Any images used for UI elements should be specified by either an absolute path. i.e. '/sdcard/nmt/blabla.com.bla./data/public/img/button.png' + + + Array of Toolbar elements. Do not create more than five elements for maximum portability.Toolbar elements are not scrollable, so if some buttons will not fit into the screen dimensions, they will be invisible. + + Properties of Toolbar elements. Either :icon or :label must be specified. If both are specified, :icon is drawn and :label is discarded. + + + Visible label to display instead of an icon.For predefined actions, icon will be displayed. Android, iOS note: for predefined actions no label will be displayed. + Visible label to display instead of an icon.For predefined actions, icon will be displayed. Android note: for predefined actions no label will be displayed. + + + URL to call when button is pressed or special value.It may be path to Ruby controller action; i.e. '/app/Account' would load the Account index action. For ruby callback use 'callback:/app/Account' Or javascript method to call: 'javascript: methodOnButton();'. + URL to call when button is pressed or special value.It may be a JavaScript method to call: 'javascript: methodOnButton();'. + + Add a separator to the toolbar. If only one separator is specified, then elements after separator will be right-aligned. If more then one separator is added: on WM/CE, platform dependent separator will be displayed, on Android/iOS center-aligned groups will be created. + Add a separator to the toolbar. If only one separator is specified, then elements after separator will be right-aligned. If more then one separator is added: on WM/CE, platform dependent separator will be displayed, on Android center-aligned groups will be created. + WM, CE, Win32, iOS, Android + WM, CE, Win32, Android + + + Exit the application. + + + Exit the application. + + + Navigate to Settings page, defined in configuration file. + + + Navigate to Home page, defined in configuration file. + + + Refresh current page. + + + Perform back action or execute browser back. + + + Display Log View window. + WM, CE, Win32, iOS, Android + WM, CE, Win32, Android + + + Expand application window to full screen. + WM, CE, Win32, Android, WP8 + WM, CE, Win32, Android + + + Run full sync command. + + + Minimize application window. + WM, CE, Win32 + + + Display software keyboard window.Set `Rho.System.keyboardState` to `Rho.System.KEYBOARD_AUTOMATIC` to use this element. + Display software keyboard window.Set `EB.System.keyboardState` to `EB.System.KEYBOARD_AUTOMATIC` to use this element. + + WM + + + + + Relative path to toolbar item icon in your rhodes app (typically located in '/public/images/'). Icon is ignored for predefined actions, icon will be displayed even if no icon specified. iPhone and Android: Icons must be no more than 30x30 pixels and must be in .png format. Windows Mobile: Icons can be any size, but all icons should have same size (default - 48x48). .png and .bmp formats are supported. + Icon absolute path, from root of the device. For example, on Android your path would look somethin like "/mnt/internal/filename.png" and for Windows Mobile it would look like "/Program Files/filename.png". If the path is not set correctly, the toolbar may not display correctly. Android: Icons must be no more than 30x30 pixels and must be in .png format. Windows Mobile: Icons can be any size, but all icons should have same size (default - 48x48). .png and .bmp formats are supported. + + + Use colored icon in toolbar on iPhone instead of standard monochrome white icon (prepared from image alpha). + iOS + + + Button width in pixel. Used to define separator width when more than one separator specified. + WM + + + + + + + Properties of TabBar. + + + Background color of the toolbar. + + + Image mask color(transparent color). + WM, CE, Win32 + + + Toolbar height in pixels. + WM, CE, Win32 + + + + + + + + Removes the current toolbar. Does nothing if there is no active toolbar. + + + + Check if Toolbar already exists. + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + + + +
        + Create a native Toolbar. + + + "Home", + :action => url_for(Rho::Application.startURI) + }, + { + :label => "example.com", + :action => "http://www.example.com", + } +], {}) + ]]> + + + + + +
        +
        +
        + + +
        + Remove the toolbar. + + + + + + + + +
        +
        +
        +
        +
        +
        \ No newline at end of file diff --git a/docs/en/5.5/api/Navbar.md b/docs/en/5.5/api/Navbar.md new file mode 100644 index 00000000..aefb94b2 --- /dev/null +++ b/docs/en/5.5/api/Navbar.md @@ -0,0 +1,35 @@ +#Navbar +
        +

        The NavBar API supports a native navigation bar for iOS devices.

        +

        Enabling the API

        + +

        This API is part of the coreapi extension that is included automatically.

        + +
        :::ruby
        +extensions: ["coreapi"]
        +
        + +

        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

        + +

        create(HASH navBarProperties)

        Removes the current NavBar and replaces it with this one.

        +

        Parameters

        • navBarProperties : HASH

          HASH with NavBar elements.

          +

          • left : HASH

            Left button with :action and :label defined.

            +

            • label : STRING

              Label for the button.

              +

            • action : STRING

              URL to call when button is pressed.It may be path to Ruby controller action; i.e. ‘/app/Account’ would load the Account index action. For ruby callback use ‘callback:/app/Account’ Or javascript method to call: ‘javascript: methodOnButton();’.

              +

          • right : HASH

            (optional) Right button with :action and :label defined.

            +

            • label : STRING

              Label for the button.

              +

            • action : STRING

              URL to call when button is pressed.It may be path to Ruby controller action; i.e. ‘/app/Account’ would load the Account index action. For ruby callback use ‘callback:/app/Account’ Or javascript method to call: ‘javascript: methodOnButton();’.

              +

          • title : STRING

            Title of the navigation bar.

            +

        Synchronous Return:

        • Void

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.Navbar.create(HASH navBarProperties)
          • Ruby: Rho::Navbar.create(HASH navBarProperties)

        remove()

        Removes the current navigation bar. Does nothing if there is no active navigation bar.

        +

        Synchronous Return:

        • Void

        Method Access:

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

        started()

        Return true is navbar is started (used only for automatic tests)

        +

        Synchronous Return:

        • BOOLEAN

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.Navbar.started()
          • Ruby: Rho::Navbar.started()
        \ No newline at end of file diff --git a/docs/en/5.5/api/Navbar.xml b/docs/en/5.5/api/Navbar.xml new file mode 100644 index 00000000..39c836fb --- /dev/null +++ b/docs/en/5.5/api/Navbar.xml @@ -0,0 +1,87 @@ + + + + + The NavBar API supports a native navigation bar for iOS devices. + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +### JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +### Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + iOS + + + + + + + + + Removes the current NavBar and replaces it with this one. + + + HASH with NavBar elements. + + Left button with :action and :label defined. + + + Label for the button. + + + URL to call when button is pressed.It may be path to Ruby controller action; i.e. '/app/Account' would load the Account index action. For ruby callback use 'callback:/app/Account' Or javascript method to call: 'javascript: methodOnButton();'. + + + + + + (optional) Right button with :action and :label defined. + + + Label for the button. + + + URL to call when button is pressed.It may be path to Ruby controller action; i.e. '/app/Account' would load the Account index action. For ruby callback use 'callback:/app/Account' Or javascript method to call: 'javascript: methodOnButton();'. + + + + + + Title of the navigation bar. + + + + + iOS + + + + + Removes the current navigation bar. Does nothing if there is no active navigation bar. + iOS + + + + Return true is navbar is started (used only for automatic tests) + + iOS + + + + 1.0.0 + + + + + + + + + \ No newline at end of file diff --git a/docs/en/5.5/api/Network.md b/docs/en/5.5/api/Network.md new file mode 100644 index 00000000..b1b589eb --- /dev/null +++ b/docs/en/5.5/api/Network.md @@ -0,0 +1,342 @@ +#Network +
        +

        This API class allows you to interact with either the WAN or WiFI network of the device.

        +

        Enabling the API

        + +

        This API is part of the coreapi extension that is included automatically.

        + +
        :::ruby
        +extensions: ["coreapi"]
        +
        + +

        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

        + +

        cancel(CallBackHandler callback)

        Cancel the request identified by callback. If callback is not specified then all requests will be canceled.

        +

        Parameters

        • callback : CallBackHandler Optional

        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.Network.cancel(CallBackHandler callback)
          • Ruby: Rho::Network.cancel(CallBackHandler callback)

        connectWan(STRING connectionDestination, CallBackHandler callback)

        Connects the device to a Wide Area Network. The connection destination must be first configured through the Connection Manager (on the device) and the destination name provided to this method. If a connection is already established, you must first call disconnectWan before attempting another connection. A list of available connection destinations is written to the log file when either connectWan or disconnectWan are first specified. Specify the connection as ‘Internet’ to use the default internet connection defined on the device. If the specified destination does not exist no connection attempt will be made and an entry will be made in the log file.

        +

        Parameters

        • connectionDestination : STRING

          The connection in the Windows Connection manager to use, specify ‘Internet’ to use the default internet connection.

          +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • phoneSignalStrength : STRING

            The signal strength of the phone as a percentage of maximum strength. Returned as a number between 0 and 100. If there is no phone service this field will be 0.

            +

          • networkOperator : STRING

            The name of the current network operator associated with the SIM card.

            +

          • connectionTypeAvailable : STRING

            The current data connection type available to RhoElements as provided by the Network. Values can be ‘Unavailable’, GPRS, 1XRTT, EVDO, EDGE, UMTS, EVDV or HSDPA.

            +

          • connectionTypeConnected : STRING

            The data connection type to which the device is currently connected. The values returned are identical to connectionTypeAvailable, with the exception that ‘Not Connected’ replaces ‘Unavailable’.

            +

          • connectionManagerMessage : STRING

            This is the last received status from the Connection Manager. Do NOT use this parameter to determine if you are able to physically send / receive data to a remote host, it only provides an indication of whether the Connection Manager believes the connection is available. To determine if you are connected to a remote host use the detectConnection method.

            +

        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.Network.connectWan(STRING connectionDestination, CallBackHandler callback)
          • Ruby: Rho::Network.connectWan(STRING connectionDestination, CallBackHandler callback)

        detectConnection(HASH propertyMap, CallBackHandler callback)

        Begins polling the specified host on the specified URL to check if there is a network connection available. The connection status is reported back via the provided callback. Note that callback will be called only if connection status has changed compared to previous polling. Multiple concurrent detectionConnection is not supported.

        +

        Parameters

        • propertyMap : HASH

          Properties map.

          +

          • host : STRING Default: www.motorolasolutions.com

            When detecting a network connection, this is the URL or IP address of the server to attempt to connect to.

            +

          • port : INTEGER Default: 80

            When detecting a network connection, this is the port on the host to connect to.

            +

          • pollInterval : INTEGER Default: 30000

            The time, in milliseconds, between each check for a connection. Note that the actual connection report interval will be the sum of the poll interval and the detection timeout. The minimum allowed value is 5000ms.

            +

          • detectionTimeout : INTEGER Default: 1000

            The amount of time to attempt to connect to the specified URL before giving up and assuming ‘disconnected’. Value is specified in milliseconds.

            +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • connectionInformation : STRING

            Whether the device is connected to the specified host and port. Either ‘Connected’ or ‘Disconnected’.

            +

          • failureMessage : STRING

            If the device is disconnected this field will contain information about why the connection failed.

            +

        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.Network.detectConnection(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::Network.detectConnection(HASH propertyMap, CallBackHandler callback)

        disconnectWan()

        Disconnects the current WAN connection. DisconnectWan will only affect connections established by RhoElements so if you have not previously called connectWan this function will have no effect.

        +

        Synchronous Return:

        • Void

        Method Access:

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

        downloadFile(HASH propertyMap, CallBackHandler callback)

        Download a file to the specified filename. Note: if ‘overwriteFile’ flag is default or false, the HEAD request to the server will be performed before actual download to retrieve ‘last-modified’ header which is used to support resuming interrupted download. If targeted server doesn’t support HEAD requests, ‘overwriteFile’ should be set to true.

        +

        Parameters

        • propertyMap : HASH

          Properties to be used in this request.

          +

          • url : STRING

            URL of file to be downloaded. HTTP and HTTPS protocols are supported.

            +

          • filename : STRING

            The path and name of the file to be uploaded.

            +

          • overwriteFile : BOOLEAN Default: false

            OverWriteFile will overwrite the destination file if it already exists.

            +

          • createFolders : BOOLEAN Default: false

            CreateFolders can automatically create the directory path.

            +

        • callback : CallBackHandler Optional

        Async Callback Returning Parameters: HASH

          • body : STRING

            The body of the HTTP response.

            +

          • headers : HASH

            A hash containing the response headers.

            +

          • cookies : STRING

            The server cookies, parsed and usable for subsequent requests.

            +

          • http_error : INTEGER

            HTTP error code if response code was not 200.

            +

          • fileExists : BOOLEAN

            When overwriteFile is false and file exists, when error return and this flag set to true.

            +

        Synchronous Return:

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

            The body of the HTTP response.

            +

          • headers : HASH

            A hash containing the response headers.

            +

          • cookies : STRING

            The server cookies, parsed and usable for subsequent requests.

            +

          • http_error : INTEGER

            HTTP error code if response code was not 200.

            +

          • fileExists : BOOLEAN

            When overwriteFile is false and file exists, when error return and this flag set to true.

            +

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.Network.downloadFile(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::Network.downloadFile(HASH propertyMap, CallBackHandler callback)

        get(HASH propertyMap, CallBackHandler callback)

        Perform a HTTP GET request.

        + +

        Note: This method will perform a POST if you send a body with it. If performing a GET, do not add a body to the call.

        +

        Parameters

        • propertyMap : HASH

          Properties map.

          + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

        • callback : CallBackHandler Optional

        Async Callback Returning Parameters: HASH

          • body : STRING

            The body of the HTTP response.

            +

          • headers : HASH

            A hash containing the response headers.

            +

          • cookies : STRING

            The server cookies, parsed and usable for subsequent requests.

            +

          • http_error : INTEGER

            HTTP error code if response code was not 200.

            +

        Synchronous Return:

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

            The body of the HTTP response.

            +

          • headers : HASH

            A hash containing the response headers.

            +

          • cookies : STRING

            The server cookies, parsed and usable for subsequent requests.

            +

          • http_error : INTEGER

            HTTP error code if response code was not 200.

            +

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.Network.get(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::Network.get(HASH propertyMap, CallBackHandler callback)

        hasCellNetwork()

        Returns true if the device is connected to a cell network. Not supported on Windows CE.

        +

        Synchronous Return:

        • BOOLEAN

        Method Access:

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

        hasNetwork()

        Returns true if the device is connected to a network. Not supported on Windows CE.

        +

        Synchronous Return:

        • BOOLEAN

        Method Access:

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

        hasWifiNetwork()

        Returns true if the device is connected to a WiFi network. Not supported on Windows CE.

        +

        Synchronous Return:

        • BOOLEAN

        Method Access:

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

        post(HASH propertyMap, CallBackHandler callback)

        Perform a HTTP Post.

        +

        Parameters

        • propertyMap : HASH

          The properties for the Network module can be used in this hash along with the following:

          +

          • body : STRING

            The message body of the HTTP request.

            +

        • callback : CallBackHandler Optional

        Async Callback Returning Parameters: HASH

          • body : STRING

            The body of the HTTP response.

            +

          • headers : HASH

            A hash containing the response headers.

            +

          • cookies : STRING

            The server cookies, parsed and usable for subsequent requests.

            +

          • http_error : INTEGER

            HTTP error code if response code was not 200.

            +

        Synchronous Return:

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

            The body of the HTTP response.

            +

          • headers : HASH

            A hash containing the response headers.

            +

          • cookies : STRING

            The server cookies, parsed and usable for subsequent requests.

            +

          • http_error : INTEGER

            HTTP error code if response code was not 200.

            +

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.Network.post(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::Network.post(HASH propertyMap, CallBackHandler callback)

        startStatusNotify(INTEGER pollInterval, CallBackHandler callback)

        Start network status notifications. Notifications are sent when WiFi or Cell network appear / disappear. To check real Internet connectivity use detectConnection method. Not supported on Windows CE.

        +

        Parameters

        • pollInterval : INTEGER Default: 20

          The network status polling period for systems that can not notify network status change immediately. In seconds. Currently applies to iOS only as immediate status notification is not available on this platform.

          +

        • callback : CallBackHandler Mandatory

        Async Callback Returning Parameters: HASH

          • current_status : STRING

            Current status of network connection. Can be “connected” or “disconnected”.

            +

          • prev_status : STRING

            Previous status of network connection. Can be “connected”, “disconnected” or “unknown”."

            +

        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.Network.startStatusNotify(INTEGER pollInterval, CallBackHandler callback)
          • Ruby: Rho::Network.startStatusNotify(INTEGER pollInterval, CallBackHandler callback)

        stopDetectingConnection(CallBackHandler callback)

        Ceases network detection. Callback is no longer supported; it has been made optional to preserve backward compatibility.

        +

        Parameters

        • callback : CallBackHandler Optional

        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.Network.stopDetectingConnection(CallBackHandler callback)
          • Ruby: Rho::Network.stopDetectingConnection(CallBackHandler callback)

        stopStatusNotify()

        Stop network status notifications. Not supported on Windows CE.

        +

        Synchronous Return:

        • Void

        Method Access:

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

        uploadFile(HASH propertyMap, CallBackHandler callback)

        Upload the specified file using HTTP POST.

        +

        Parameters

        • propertyMap : HASH

          The properties for the Network module can be used in this hash along with the following:

          +

          • filename : STRING

            The path and name of the file to be uploaded.

            +

          • body : STRING

            The message body of the HTTP request.

            +

          • fileContentType : STRING

            Content-Type header for the file, defaults to “application/octet-stream”.

            +

          • multipart : ARRAY

            Array of hashes containing file information.

            +

            • Object : HASH

              Multipart properties.

              +

              • filename : STRING

                The path and name of the file to be uploaded.

                +

              • contentType : STRING

                Content-Type header, defaults to “application/octet-stream”.

                +

              • filenameBase : STRING

                Base directory containing the :filename.

                +

              • name : STRING

                File type, defaults to “blob”.

                +

        • callback : CallBackHandler Optional

        Async Callback Returning Parameters: HASH

          • body : STRING

            The body of the HTTP response.

            +

          • headers : HASH

            A hash containing the response headers.

            +

          • cookies : STRING

            The server cookies, parsed and usable for subsequent requests.

            +

          • http_error : INTEGER

            HTTP error code if response code was not 200.

            +

        Synchronous Return:

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

            The body of the HTTP response.

            +

          • headers : HASH

            A hash containing the response headers.

            +

          • cookies : STRING

            The server cookies, parsed and usable for subsequent requests.

            +

          • http_error : INTEGER

            HTTP error code if response code was not 200.

            +

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.Network.uploadFile(HASH propertyMap, CallBackHandler callback)
          • Ruby: Rho::Network.uploadFile(HASH propertyMap, CallBackHandler callback)
        + +

        Properties

        + + + +NOTE: The properties of this API Class cannot be accessed via setter or getter methods (unless otherwise noted). However they can be used in methods that allow a HASH or Array of properties to be passed in. + +

        authPassword : STRING

        Password for basic authentication. You must also specify `authType=‘basic’

        +

        Property Access:

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

        This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

        authType : STRING

        Type of authentication used for this request. Check the list of available options below. Leaving blank will result in no authentication type.

        +

        Possible Values (STRING):

        Constant: Rho.Network.AUTH_BASIC (For Ruby use "::" for all "." when referencing constants)
        String: basic

        Basic Authentication Type. uses authUser and authPassword.

        +

        Property Access:

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

        This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

        authUser : STRING

        User name for basic authentication. You must also specify authType='basic'

        +

        Property Access:

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

        This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

        headers : HASH

        List of HTTP headers to be used in the network request.

        +

        Property Access:

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

        This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

        httpVerb : STRING

        Replaces:http_command

        HTTP verb to be used in the network request.

        +

        Property Access:

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

        This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

        responseTimeout : INTEGER

        Timeout of network requests in seconds. This property has module scope. Do not pass it as hash parameter to methods, use property accessors instead.

        +

        Default: 30

        Property Access:

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

        url : STRING

        URL of the request. This should be fully formatted URL like http://domain.com/

        +

        Property Access:

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

        verifyPeerCertificate : BOOLEAN

        Replaces:ssl_verify_peer

        Verify SSL certificates. When set to false it will allow untrusted certificates.

        +

        Default: true

        Property Access:

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

        Examples

        + +
        Request a notification from the system when network availability changes
        +

        When you need to be notified of changes in the status of the network (connected / disconnected), use Network.startStatusNotify.

        +
        :::javascript
        +
        +           
        +    function status_notify_callback(params) {
        +      alert("Network status changed from "+params["prev_status"]+" to "+params["current_status"]);
        +    }
        +
        +    function start_status_notify() {
        +      # Request the system to check every 3 seconds and call us back if there is a change in network connectivity
        +      Rho.Network.startStatusNotify(3000, status_notify_callback);
        +    }
        +
        +    function stop_status_notify() {
        +      // Stop network status notifications
        +      Rho.Network.stopStatusNotify();
        +    }
        +
        +                   
        +                 
        :::ruby
        +
        +           
        +  def start_status_notify
        +    # Request the system to check every 3 seconds and call us back if there is a change in network connectivity
        +    Rho::Network.startStatusNotify(3000, url_for(:action => :status_notify_callback))
        +    Alert.show_popup "Started network status notifications"
        +  end
        +
        +  # This is our notification that the status of the network changed. old_status and new_status can be "disconnected" or "connected"
        +  def status_notify_callback
        +    Alert.show_popup("Network status changed from #{@params["prev_status"]} to #{@params["current_status"]}")
        +  end
        +
        +
        +  def stop_status_notify
        +    # Stop network status notifications
        +    Rho::Network.stopStatusNotify
        +    Alert.show_popup "Stopped network status notifications"
        +  end
        +                   
        +                 
        Check whether the network is available
        +

        You can check whether the mobile, WiFi or other network is available. This can be useful for example if you only want to perform large data transfers on WiFi and avoid doing them while on the cell network.

        +
        :::javascript
        +
        +           
        +    function network_availability() {
        +      // shows the network availability for...
        +      // Cell network
        +      var cell_network = Rho.Network.hasCellNetwork()
        +      // Wi-Fi network
        +      var wifi_network = Rho.Network.hasWifiNetwork()
        +      // Any network
        +      var network = Rho.Network.hasNetwork()
        +
        +      alert("Cell network: "+cell_network+"\nWi-Fi network: "+wifi_network+"\nNetwork: "+network);
        +    }
        +                   
        +                 
        :::ruby
        +
        +           
        +    # check the network availability for...
        +    # Cell network
        +    cell_network = Rho::Network.hasCellNetwork
        +    # Wi-Fi
        +    wifi_network = Rho::Network.hasWifiNetwork
        +    # Any network
        +    network = Rho::Network.hasNetwork
        +                   
        +                 
        Download file and save it to permanent storage
        +

        Download any file from an external server and store it in your device.

        +
        :::javascript
        +
        +           
        +function download_file_callback(params) {
        +  if (params["status"] == "ok") {
        +    alert("Download Succeeded, path is /public/images/sample.png");
        +  } else {
        +    alert("Download Failed");
        +  }
        +}
        +
        +function download_file() {
        +  // Download a file to the specified filename. Be careful with the overwriteFile parameter!
        +  downloadfileProps = {
        +    url: "http://www.google.com/images/icons/product/chrome-48.png",
        +    filename: Rho.Application.publicFolder+"/images/sample.png",
        +    overwriteFile: true
        +  };
        +  Rho.Network.downloadFile(downloadfileProps, download_file_callback);
        +}
        +                   
        +                 
        :::ruby
        +
        +           
        +  def download_file
        +      #Download a file to the specified filename.
        +      downloadfileProps = Hash.new
        +      downloadfileProps["url"]='http://www.google.com/images/icons/product/chrome-48.png'
        +      downloadfileProps["filename"] = Rho::Application.publicFolder+"/images/sample.png"
        +      downloadfileProps["overwriteFile"] = true
        +      Rho::Network.downloadFile(downloadfileProps, url_for(:action => :download_file_callback))
        +  end
        +
        +  def download_file_callback
        +    if @params["status"] == "ok"
        +        Alert.show_popup "Download Success,path is /public/images/sample.png "
        +    else
        +        Alert.show_popup "Download Failed"
        +    end
        +  end
        +
        +                   
        +                 
        Upload files via HTTP POST
        +

        You can upload any file to an external server via HTTP POST and be notified whether the transfer succeeded or not.

        +
        :::javascript
        +
        +           
        +function upload_file_callback(params) {
        +  // Check the result of the upload and act accordingly
        +  if (params["status"] == "ok") {
        +    alert("Upload Succeeded.");
        +  } else {
        +    alert("Upload Failed.");
        +  }
        +}
        +
        +function upload_file() {
        +    // Upload the specified file using HTTP POST.
        +    uploadfileProps = {
        +      url: "http://www.example.com",
        +      filename: Rho.Application.publicFolder+"/images/backButton.png",
        +      body: "uploading file",
        +      fileContentType: "image/png"
        +    };
        +
        +    Rho.Network.uploadFile(uploadfileProps, upload_file_callback);
        +}
        +                   
        +                 
        :::ruby
        +
        +           
        +  def upload_file
        +    # Upload the specified file using HTTP POST.
        +    uploadfileProps = Hash.new
        +    uploadfileProps['url'] = "http://www.example.com"
        +    uploadfileProps['filename'] = Rho::Application.publicFolder+"/images/backButton.png"
        +    uploadfileProps['body'] = "uploading file"
        +    uploadfileProps['fileContentType']="image/png"
        +    Rho::Network.uploadFile(uploadfileProps, url_for(:action => :upload_file_callback))
        +  end
        +
        +  def upload_file_callback
        +    if @params['status'] == "ok"
        +        Alert.show_popup "Upload Succeeded."
        +    else
        +        Alert.show_popup "Upload Failed."
        +    end
        +  end
        +                   
        +                 
        Network POST Using Ruby's Lambda
        +

        You can also define network request callbacks with this API using Ruby’s lambda functions, similar to how you would use a JavaScript anonymous function for a callback. Simply define your callback, using lambda, in place of the callback parameter in the method call as such.

        +
        :::ruby
        +
        +Rho::Network.post(
        +  {
        +    url:      url,
        +    headers:  { 'Content-Type' => 'application/json', 'Accept' => 'application/json' },
        +    body:     json
        +  },
        +  lambda do |response; body, headers, cookies, http_status|
        +
        +    body = response['body']
        +    headers = response['headers']
        +    cookies = response['cookies']
        +    http_status = response['http_status']
        +
        +    app_info "TESTING got POST callback"
        +    app_info "body = #{body.inspect}"
        +    app_info "headers = #{headers.inspect}"
        +    app_info "cookies = #{cookies.inspect}"
        +    app_info "http_error = #{http_error.class} #{http_error.inspect}"
        +    app_info "testing lambda context, url = '#{url}'"
        +  end
        +)
        +                                
        +                            
        + +

        Remarks

        + +
        Detecting a connection through proxies

        Because the detectConnection method is protocol agnostic, it will not communicate through HTTP proxies to reach a specified URL. In order to determine if you are connected when sitting behind a proxy you should call the method to attempt to connect to your proxy on the appropriate port. A successful connection to the proxy should be taken to assume the device is connected to a network. When configuring your WAN connection bear in mind that the proxy settings defined in the RhoElements configuration file will take precedence.

        +
        Detecting a connection over WAN

        When detecting a network connection over WAN bear in mind if you specify a low networkPollInterval your device will frequently have an active data connection and may prevent the device occasionally from accepting incoming calls.

        +
        Preventing access to the device (WEH / WM)

        Receiving phone calls or texts whilst running RhoElements will cause the start button to be displayed on Windows Embedded Handheld devices, potentially offering users access to the operating system. It is recommended to set the following registry keys to disable Operating System access on Windows Embedded Handheld as required. The registry keys will be applied after a warm boot, omit them entirely to restore the Start and ‘X’ icons.

        + +
        +[HKEY_LOCAL_MACHINE\Software\Microsoft\Shell\BubbleTiles]   Location in Registry
        +"HardwareStartKeyEnabled"=dword:00000001                    Prevents the Start icon from appearing in the bottom left
        +"HardwareDoneKeyEnabled"=dword:00000001                     Prevents the 'X' icon from appearing in the bottom right
        +
        + + + +
        SSL Connection Failure in iOS Platform

        Due to a limitation in curl for iOS, an appropriate timeout is not used in ‘select’ system calls for a curl SSL conection. To avoid this SSL connection issue, it is recommended that the iOS native Network library be used instead of curl. To do this, add the two lines below to the rhoconfig.txt file.

        + +

        For more information, please refer to Avoiding Common Networking Mistakes in the Apple developer reference.

        + +
        +ios_net_curl = 0
        +ios_direct_local_requests = 0
        +
        + + + +
        \ No newline at end of file diff --git a/docs/en/5.5/api/Network.xml b/docs/en/5.5/api/Network.xml new file mode 100644 index 00000000..896248ac --- /dev/null +++ b/docs/en/5.5/api/Network.xml @@ -0,0 +1,653 @@ + + + + + This API class allows you to interact with either the WAN or WiFI network of the device. + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the Network API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Network API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.network.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + + + + URL of the request. This should be fully formatted URL like http://domain.com/ + + + + Type of authentication used for this request. Check the list of available options below. Leaving blank will result in no authentication type. + + + Basic Authentication Type. uses authUser and authPassword. + + + + + User name for basic authentication. You must also specify `authType='basic'` + + + Password for basic authentication. You must also specify `authType='basic' + + + Verify SSL certificates. When set to false it will allow untrusted certificates. + WM, CE, Android, iOS, Win32 + WM, CE, Win32, Android + + + HTTP verb to be used in the network request. + + + List of HTTP headers to be used in the network request. + + + + Timeout of network requests in seconds. This property has module scope. Do not pass it as hash parameter to methods, use property accessors instead. + + + + + + + + + Cancel the request identified by callback. If callback is not specified then all requests will be canceled. + + + + Download a file to the specified filename. Note: if 'overwriteFile' flag is default or false, the HEAD request to the server will be performed before actual download to retrieve 'last-modified' header which is used to support resuming interrupted download. If targeted server doesn't support HEAD requests, 'overwriteFile' should be set to true. + + + Properties to be used in this request. + + + URL of file to be downloaded. HTTP and HTTPS protocols are supported. + + + The path and name of the file to be uploaded. + + + OverWriteFile will overwrite the destination file if it already exists. + + + CreateFolders can automatically create the directory path. + + + + + + + + + The body of the HTTP response. + + + A hash containing the response headers. + + + The server cookies, parsed and usable for subsequent requests. + + + HTTP error code if response code was not 200. + + + When overwriteFile is false and file exists, when error return and this flag set to true. + + + + + + + Perform a HTTP GET request. + +> Note: This method will perform a POST if you send a body with it. If performing a GET, do not add a body to the call. + + + Properties map. + + + + + + The body of the HTTP response. + + + A hash containing the response headers. + + + The server cookies, parsed and usable for subsequent requests. + + + HTTP error code if response code was not 200. + + + + + + + Perform a HTTP Post. + + + The properties for the Network module can be used in this hash along with the following: + + + The message body of the HTTP request. + + + + + + + + The body of the HTTP response. + + + A hash containing the response headers. + + + The server cookies, parsed and usable for subsequent requests. + + + HTTP error code if response code was not 200. + + + + + + + Upload the specified file using HTTP POST. + + + The properties for the Network module can be used in this hash along with the following: + + + The path and name of the file to be uploaded. + + + The message body of the HTTP request. + + + Content-Type header for the file, defaults to "application/octet-stream". + + + Array of hashes containing file information. + + Multipart properties. + + + The path and name of the file to be uploaded. + + + Content-Type header, defaults to "application/octet-stream". + + + Base directory containing the :filename. + + + File type, defaults to "blob". + + + + + + + + + + + The body of the HTTP response. + + + A hash containing the response headers. + + + The server cookies, parsed and usable for subsequent requests. + + + HTTP error code if response code was not 200. + + + + + + + Returns true if the device is connected to a network. Not supported on Windows CE. + WM, Android, iOS + WM, Android + Not supported on Windows CE + + + + Returns true if the device is connected to a WiFi network. Not supported on Windows CE. + WM, Android, iOS + WM, Android + Not supported on Windows CE + + + + Returns true if the device is connected to a cell network. Not supported on Windows CE. + WM, Android, iOS + WM, Android + Not supported on Windows CE + + + + + Start network status notifications. Notifications are sent when WiFi or Cell network appear / disappear. To check real Internet connectivity use detectConnection method. Not supported on Windows CE. + WM, Android, iOS + WM, Android + Not supported on Windows CE + + + The network status polling period for systems that can not notify network status change immediately. In seconds. Currently applies to iOS only as immediate status notification is not available on this platform. + + + + Network status notification information. + + + Current status of network connection. Can be "connected" or "disconnected". + + + Previous status of network connection. Can be "connected", "disconnected" or "unknown"." + + + + + + + Stop network status notifications. Not supported on Windows CE. + WM, Android, iOS + WM, Android + Not supported on Windows CE + + + + 4.0.0 + Begins polling the specified host on the specified URL to check if there is a network connection available. The connection status is reported back via the provided callback. Note that callback will be called only if connection status has changed compared to previous polling. Multiple concurrent detectionConnection is not supported. + + + Properties map. + + + When detecting a network connection, this is the URL or IP address of the server to attempt to connect to. + + + When detecting a network connection, this is the port on the host to connect to. + + + The time, in milliseconds, between each check for a connection. Note that the actual connection report interval will be the sum of the poll interval and the detection timeout. The minimum allowed value is 5000ms. + + + The amount of time to attempt to connect to the specified URL before giving up and assuming 'disconnected'. Value is specified in milliseconds. + + + + + + Information related to the connection to the specified URL. + + + Whether the device is connected to the specified host and port. Either 'Connected' or 'Disconnected'. + + + If the device is disconnected this field will contain information about why the connection failed. + + + + + + + 4.0.0 + Ceases network detection. Callback is no longer supported; it has been made optional to preserve backward compatibility. + + + + Connects the device to a Wide Area Network. The connection destination must be first configured through the Connection Manager (on the device) and the destination name provided to this method. If a connection is already established, you must first call disconnectWan before attempting another connection. A list of available connection destinations is written to the log file when either connectWan or disconnectWan are first specified. Specify the connection as 'Internet' to use the default internet connection defined on the device. If the specified destination does not exist no connection attempt will be made and an entry will be made in the log file. + WM + This method only applies to platforms with the Windows Mobile connection manager + 1.0.3 + + + The connection in the Windows Connection manager to use, specify 'Internet' to use the default internet connection. + + + + Notifies the user whenever any parameter associated with data connectivity changes. This callback is called when the connectWan method is first called (for the initial state) and again whenever any of the associated parameters change. + + + The signal strength of the phone as a percentage of maximum strength. Returned as a number between 0 and 100. If there is no phone service this field will be 0. + + + The name of the current network operator associated with the SIM card. + + + The current data connection type available to RhoElements as provided by the Network. Values can be 'Unavailable', GPRS, 1XRTT, EVDO, EDGE, UMTS, EVDV or HSDPA. + + + The data connection type to which the device is currently connected. The values returned are identical to connectionTypeAvailable, with the exception that 'Not Connected' replaces 'Unavailable'. + + + This is the last received status from the Connection Manager. Do NOT use this parameter to determine if you are able to physically send / receive data to a remote host, it only provides an indication of whether the Connection Manager believes the connection is available. To determine if you are connected to a remote host use the detectConnection method. + + + + + + + 1.0.3 + Disconnects the current WAN connection. DisconnectWan will only affect connections established by RhoElements so if you have not previously called connectWan this function will have no effect. + WM + This method only applies to platforms with the Windows connection manager + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + + + + + + + +[HKEY_LOCAL_MACHINE\Software\Microsoft\Shell\BubbleTiles] Location in Registry +"HardwareStartKeyEnabled"=dword:00000001 Prevents the Start icon from appearing in the bottom left +"HardwareDoneKeyEnabled"=dword:00000001 Prevents the 'X' icon from appearing in the bottom right + + + ]]> + + + Avoiding Common Networking Mistakes in the Apple developer reference. + +
        +ios_net_curl = 0
        +ios_direct_local_requests = 0
        +
        + ]]>
        +
        +
        + + + +
        + When you need to be notified of changes in the status of the network (connected / disconnected), use Network.startStatusNotify. + + + :status_notify_callback)) + Alert.show_popup "Started network status notifications" + end + + # This is our notification that the status of the network changed. old_status and new_status can be "disconnected" or "connected" + def status_notify_callback + Alert.show_popup("Network status changed from #{@params["prev_status"]} to #{@params["current_status"]}") + end + + + def stop_status_notify + # Stop network status notifications + Rho::Network.stopStatusNotify + Alert.show_popup "Stopped network status notifications" + end + ]]> + + + + + +
        +
        + +
        + + + +
        + You can check whether the mobile, WiFi or other network is available. This can be useful for example if you only want to perform large data transfers on WiFi and avoid doing them while on the cell network. + + + + + + + + +
        +
        +
        + + +
        + Download any file from an external server and store it in your device. + + + :download_file_callback)) + end + + def download_file_callback + if @params["status"] == "ok" + Alert.show_popup "Download Success,path is /public/images/sample.png " + else + Alert.show_popup "Download Failed" + end + end + + ]]> + + + + + +
        +
        +
        + + +
        + You can upload any file to an external server via HTTP POST and be notified whether the transfer succeeded or not. + + + :upload_file_callback)) + end + + def upload_file_callback + if @params['status'] == "ok" + Alert.show_popup "Upload Succeeded." + else + Alert.show_popup "Upload Failed." + end + end + ]]> + + + + + +
        +
        +
        + + +
        + You can also define network request callbacks with this API using Ruby's lambda functions, similar to how you would use a JavaScript anonymous function for a callback. Simply define your callback, using lambda, in place of the callback parameter in the method call as such. + + 'application/json', 'Accept' => 'application/json' }, + body: json + }, + lambda do |response; body, headers, cookies, http_status| + + body = response['body'] + headers = response['headers'] + cookies = response['cookies'] + http_status = response['http_status'] + + app_info "TESTING got POST callback" + app_info "body = #{body.inspect}" + app_info "headers = #{headers.inspect}" + app_info "cookies = #{cookies.inspect}" + app_info "http_error = #{http_error.class} #{http_error.inspect}" + app_info "testing lambda context, url = '#{url}'" + end +) + ]]> + + +
        +
        +
        +
        +
        +
        diff --git a/docs/en/5.5/api/NewORM.md b/docs/en/5.5/api/NewORM.md new file mode 100644 index 00000000..ebcf9e83 --- /dev/null +++ b/docs/en/5.5/api/NewORM.md @@ -0,0 +1,109 @@ +#NewORM +
        +

        ORM CoreAPI module

        +

        New implementation of the RHOM. +NOTE: BETA VERSION – This API has not been officially released. It should not be used in a production environment.

        + +

        Enabling the API

        + +

        This API is part of the coreapi extension that is included automatically.

        + +
        :::ruby
        +extensions: ["coreapi"]
        +
        + +

        JavaScript Usage

        + +

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

        + +

        If you are going to be using the JS ORM API, you’ll also need to include these lines in any files that will be using it:

        + +
        :::html
        +<script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-ORM.js"></script>
        +<script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-ORMHelper.js"></script>
        +<script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-Ruby-RunTime.js"></script>
        +
        + +

        Ruby Usage

        + +

        For Ruby access to the RHOM database please see the Rhom Ruby API guide.

        + + + +

        Methods

        + +

        addModel( Anoynomous Function methods)

        Creates an ORM model reference.

        +

        Parameters

        • Anoynomous Function methods :

          • enable("value") : STRING Optional

            Enables Model Properties.

            +

            Possible Values :

            sync

            If set then model is set for RhoConnect Sync.

            +
            propertyBag

            (Default) Model will be of type propertyBag.

            +
            fixedSchema

            Model will be of type fixedSchema.

            +
            full_update

            Instruct ORM to send all attributes to RhoConnect when an object is updated. By Default it is disabled.

            +
            pass_through

            RhoConnect provides a simple way to keep data out of redis. If you have sensitive data that you do not want saved in redis, add the pass_through option in settings/settings.yml for each source.

            +
          • setModelproperty("name","type","option") : STRING,STRING,STRING Optional

            Used to create properties on your model.

            +

            • name : STRING

              The name of the property.

              +

            • type : STRING

              The type of property. Possible values are: String, Float, integer, Varchar, Blob. String is default.

              +

            • option : STRING Optional Default: Null

              Possible Values :

              overwrite

              Overwrite client copy of blob with the new copy from server. This is useful when RhoConnect modifies images sent from Rhodes, for example zooming or cropping.

              +
          • set("property","value") : STRING,VALUE Optional

            Sets the Behavior of this model. Possible ‘property’ options and the corresponding ‘value’s are passed as the parameter.

            +

            • partition : STRING

              The partition to use for this model. Partitions can be used to segment the data and keep non-synched data separate from synched models.

              +

              Possible Values :

              local

              This partition is used automatically if the model is not a sync model.

              +
              user

              This partition is used automatically if the model is a sync model.

              +
              app

              This partition is used to store the application related information.

              +
            • sync_type : STRING

              Sets the type of sync it will be.

              +

              Possible Values :

              none

              If data model is not a sync model.

              +
              incremental

              Used when the data model is a sync model. Just syncs changes.

              +
              bulk_only

              If the model is used only for bulk sync.

              +
            • sync_priority : INTEGER

              This number determines the order in which the models are processed and synchronised. Priority starts from lower value 1. Lower the number, higher is the priority. Default value is 1000.

              +

            • freezed : BOOLEAN

              To make the model Freezed.

              +

            • schema_version : FLOAT

              This is used for data migration of the application.

              +

        Synchronous Return:

        • Model

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.NewORM.addModel( Anoynomous Function methods)

        databaseClientReset(BOOLEAN resetLocalModels)

        Resets client info and sync models (optionally, local models as well)

        +

        Parameters

        • resetLocalModels : BOOLEAN Default: true

          Whether or not to reset Local Models.

          +

        Synchronous Return:

        • Void

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.NewORM.databaseClientReset(BOOLEAN resetLocalModels)
          • Ruby: Rho::NewORM.databaseClientReset(BOOLEAN resetLocalModels)

        databaseFullReset(BOOLEAN resetClientInfo, BOOLEAN resetLocalModels)

        Resets selected models, client info and local models.

        +

        Parameters

        • resetClientInfo : BOOLEAN Optional Default: false

          Whether or not to reset Client Info.

          +

        • resetLocalModels : BOOLEAN Optional Default: true

          Whether or not to reset Local Models.

          +

        Synchronous Return:

        • Void

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.NewORM.databaseFullReset(BOOLEAN resetClientInfo, BOOLEAN resetLocalModels)
          • Ruby: Rho::NewORM.databaseFullReset(BOOLEAN resetClientInfo, BOOLEAN resetLocalModels)

        databaseFullResetAndLogout()

        Resets sync models, client info and local models and does the user logout.

        +

        Synchronous Return:

        • Void

        Method Access:

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

        databaseFullResetEx(ARRAY models, BOOLEAN resetClientInfo, BOOLEAN resetLocalModels)

        Resets selected models, client info and local models.

        +

        Parameters

        • models : ARRAY

          List of models to reset.

          +

        • resetClientInfo : BOOLEAN

          Whether or not to reset Client Info.

          +

        • resetLocalModels : BOOLEAN

          Whether or not to reset Local Models.

          +

        Synchronous Return:

        • Void

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.NewORM.databaseFullResetEx(ARRAY models, BOOLEAN resetClientInfo, BOOLEAN resetLocalModels)
          • Ruby: Rho::NewORM.databaseFullResetEx(ARRAY models, BOOLEAN resetClientInfo, BOOLEAN resetLocalModels)

        databaseFullclientResetAndLogout()

        Resets sync models, client info and local models and does the user logout.

        +

        Synchronous Return:

        • Void

        Method Access:

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

        databaseLocalReset()

        Resets local database.

        +

        Synchronous Return:

        • Void

        Method Access:

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

        getClientId()

        Returns current Client Id.

        +

        Synchronous Return:

        • STRING

        Method Access:

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

        haveLocalChanges()

        Returns TRUE whenever there are any local (non-synced) changes.

        +

        Synchronous Return:

        • BOOLEAN

        Method Access:

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

        useNewOrm()

        Returns TRUE if NewORM is enabled in rhoconfig.txt.

        +

        Synchronous Return:

        • BOOLEAN

        Method Access:

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

        Examples

        + +
        addModel
        +

        This example describes creating model and adding model object.

        +
        :::javascript
        +
        +                				
        +var Customer = function(model){
        +  model.enable("sync");
        +  model.setModelProperty("name","string","");
        +  model.setModelProperty("brand","string","");
        +  model.setModelProperty("price","float","");
        +  model.set("partition","user");
        +  model.set("schema_version",'1.1');
        +};
        +var custobj = Rho.ORM.addModel("Customer", Customer);
        +// create model object and save it to database
        +var customer = custobj.createObject({
        +  brand: "Apple",
        +  name: "iPhone5",
        +  price: 199.99});
        +
        +                            
        databaseFullResetEx
        +

        This example clears the local model’s passed through the array only. It doesn’t reset the client_info table.

        +
        :::javascript
        +
        +                
        +var ary = ['Product','Product2'];				
        +Rho.ORM.databaseFullResetEx(ary, false, true);
        +                            
        :::ruby
        +
        +				
        +ary = ['Product','Product2']				
        +Rho.ORM.databaseFullResetEx(ary, false, true) 			
        +							
        \ No newline at end of file diff --git a/docs/en/5.5/api/NewORM.xml b/docs/en/5.5/api/NewORM.xml new file mode 100644 index 00000000..775808ed --- /dev/null +++ b/docs/en/5.5/api/NewORM.xml @@ -0,0 +1,256 @@ + + + + + ORM CoreAPI module + New implementation of the RHOM. +NOTE: BETA VERSION - This API has not been officially released. It should not be used in a production environment. +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +If you are going to be using the JS ORM API, you'll also need to include these lines in any files that will be using it: + + :::html + <script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-ORM.js"></script> + <script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-ORMHelper.js"></script> + <script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-Ruby-RunTime.js"></script> + +## Ruby Usage +For Ruby access to the RHOM database please see the [Rhom Ruby API guide](/api/rhom-api). + + + + + + Returns TRUE if NewORM is enabled in rhoconfig.txt. + + + + + Returns current Client Id. + + + + + Returns TRUE whenever there are any local (non-synced) changes. + + + + + Resets local database. + + + + + + Whether or not to reset Local Models. + + + Resets client info and sync models (optionally, local models as well) + + + + + + List of models to reset. + + + Whether or not to reset Client Info. + + + Whether or not to reset Local Models. + + + Resets selected models, client info and local models. + + + + + + + Whether or not to reset Client Info. + + + + Whether or not to reset Local Models. + + + Resets selected models, client info and local models. + + + + Resets sync models, client info and local models and does the user logout. + + + + Resets sync models, client info and local models and does the user logout. + + + Creates an ORM model reference. + + + + + + Enables Model Properties. + + + If set then model is set for RhoConnect Sync. + + + (Default) Model will be of type propertyBag. + + + Model will be of type fixedSchema. + + + Instruct ORM to send all attributes to RhoConnect when an object is updated. By Default it is disabled. + + + RhoConnect provides a simple way to keep data out of redis. If you have sensitive data that you do not want saved in redis, add the pass_through option in settings/settings.yml for each source. + + + + + + + Used to create properties on your model. + + + The name of the property. + + + The type of property. Possible values are: String, Float, integer, Varchar, Blob. String is default. + + + + + + Overwrite client copy of blob with the new copy from server. This is useful when RhoConnect modifies images sent from Rhodes, for example zooming or cropping. + + + + + + + + + Sets the Behavior of this model. Possible 'property' options and the corresponding 'value's are passed as the parameter. + + + + + The partition to use for this model. Partitions can be used to segment the data and keep non-synched data separate from synched models. + + + This partition is used automatically if the model is not a sync model. + + + This partition is used automatically if the model is a sync model. + + + This partition is used to store the application related information. + + + + + Sets the type of sync it will be. + + + If data model is not a sync model. + + + Used when the data model is a sync model. Just syncs changes. + + + If the model is used only for bulk sync. + + + + + This number determines the order in which the models are processed and synchronised. Priority starts from lower value 1. Lower the number, higher is the priority. Default value is 1000. + + + To make the model Freezed. + + + This is used for data migration of the application. + + + + + + + + + + Returns newly generated unique object Id. + + + + + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + + +
        + This example describes creating model and adding model object. + + + + + +
        +
        +
        + + +
        + This example clears the local model's passed through the array only. It doesn't reset the client_info table. + + + + + + + + +
        +
        +
        +
        +
        +
        diff --git a/docs/en/5.5/api/NewORMModel.md b/docs/en/5.5/api/NewORMModel.md new file mode 100644 index 00000000..94574381 --- /dev/null +++ b/docs/en/5.5/api/NewORMModel.md @@ -0,0 +1,285 @@ +#NewORMModel +
        +

        NewORMModel CoreAPI module

        +

        New implementation of the RHOM Model. +NOTE: BETA VERSION – This API has not been officially released. It should not be used in a production environment.

        + + + +

        Methods

        + +

        anyChangedObjects()

        Checks whether the model has any changed objects.

        +

        Synchronous Return:

        • BOOLEAN

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.anyChangedObjects()

        canModify(STRING objId)

        Checks whether the object can be modified.

        +

        Parameters

        • objId : STRING

        Synchronous Return:

        • BOOLEAN

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.canModify(STRING objId)

        can_modify(STRING objId)

        Deprecated

        Checks whether the object can be modified.

        +

        Parameters

        • objId : STRING

        Synchronous Return:

        • BOOLEAN

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.can_modify(STRING objId)

        changed?()

        Deprecated

        Returns true if a Rhodes model object has local database changes that need to be synchronized, false otherwise.

        +

        Synchronous Return:

        • BOOLEAN

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.changed?()

        client_id()

        Deprecated

        Returns the current sync client id.

        +

        Synchronous Return:

        • STRING

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.client_id()

        count()

        Deprecated

        Returns the number of objects in the named model.

        +

        Synchronous Return:

        • INTEGER

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.count()

        create(HASH attrs)

        Create a new Rhodes model object and save it to the database. This is the fastest way to insert a single item into the database.

        +

        Parameters

        • attrs : HASH

          List of attributes assigned to the new model object, such as {name : “ABC Inc.”,address: “555 5th St.”}.

          +

        Synchronous Return:

        • OBJECT

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.create(HASH attrs)

        deleteAll(HASH params)

        Deprecated

        Delete all Rhodes model objects for a source filtering by conditions. This method accepts parameters as key-value pairs. It accept conditions as a parameter.

        +

        Parameters

        • params : HASH

          A hash-map with deleteAll arguments.

          +

          • conditions : HASH Optional

            The attribute names and its respective values are passed as a key-value pair in this HASH. This will delete only the objects matching the criteria passed in the HASH.

            +

        Synchronous Return:

        • Void

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.deleteAll(HASH params)

        delete_all(HASH params)

        Delete all Rhodes model objects for a source filtering by conditions. This method accepts parameters as key-value pairs. It accepts 2 keys- conditions and op.

        +

        Parameters

        • params : HASH

          A hash-map with deleteAll arguments.

          +

          • conditions : HASH or ARRAY Optional

            The attribute names and its respective values are passed as a key-value pair in this HASH. This will delete only the objects matching the criteria passed in the HASH.Also supports sql fragment with binding(i.e. [“name=?”, “company_name”]

            +

        Synchronous Return:

        • Void

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.delete_all(HASH params)

        enable(STRING propertyName)

        Sets model’s Boolean property to true (enables model’s property)

        +

        Parameters

        • propertyName : STRING

          Possible Values :

          fixed_schema

          To set the type of model as Fixed_schema.

          +
          sync

          To make the model as user model.

          +
          full_update

          To send all the attributes(changed/unchanged) to Rhoconnect when an object is updated.

          +
          pass_through

          To keep the sensitive data out of redis server.

          +

        Synchronous Return:

        • Void

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.enable(STRING propertyName)

        find(STRING queryType, HASH queryOptions)

        Find model objects.

        +

        Parameters

        • queryType : STRING

          Possible Values :

          all

          returns all objects; can use optional :conditions.

          +
          first

          returns first object matching :conditions.

          +
          count

          returns the number of objects matching these :conditions.

          +
        • queryOptions : HASH

          An object of selection options

          +

          • conditions : HASH or ARRAY Optional

            The attribute names and its respective values are passed as a key-value pair in this HASH that is required to find. Ex: conditions { name:‘Symbol’}. Also supports sql fragment with binding(i.e. [“name=?”, “company_name”]).

            +

            • propertyName :

            • propertyValue :

          • order : STRING or ARRAY Optional

            Attribute(s) to order the list.

            +

          • orderdir : STRING or ARRAY Optional

            Order direction.

            +

            Possible Values :

            ASC

            Ascending order. (Default)

            +
            DESC

            Descending Order

            +
          • select : ARRAY Optional

            Array of string attributes to return with the object. Useful if your model has many attributes and your query only needs a few of them.

            +

        Synchronous Return:

        • ARRAY

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.find(STRING queryType, HASH queryOptions)

        find_all()

        Deprecated

        find(‘all’) replaces the legacy ruby method find_all.

        +

        Synchronous Return:

        • HASH

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.find_all()

        find_by_sql(STRING sqlQuery)

        Returns array of objects for the given model queried according to the specified SQL.

        +

        Parameters

        • sqlQuery : STRING

        Synchronous Return:

        • ARRAY

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.find_by_sql(STRING sqlQuery)

        get(STRING propertyName)

        Get the value of a property of the current model.Ex: myModel.get(‘name’); See also the vars() method.

        +

        Parameters

        • propertyName : STRING

          The name of the property you are trying to retrieve.

          +

        Synchronous Return:

        • STRING :

          Value of the specified property from the database.

          +

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.get(STRING propertyName)

        getAllProperties(CallBackHandler callback)

        This method will return all of object/value pairs for the propertyNames of the API class.

        +

        Parameters

        • callback : CallBackHandler Optional

        Async Callback Returning Parameters: HASH

          • : STRING

        Synchronous Return:

        • HASH :

          Map of all available properties

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.getAllProperties(CallBackHandler callback)

        getBackendRefreshTime()

        Replaces: backend_refresh_time

        Returns time string when the source has been synced.

        +

        Synchronous Return:

        • STRING

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.getBackendRefreshTime()

        getBelongsTo(STRING propertyName)

        Returns info about model’s relationships with other models.

        +

        Parameters

        • propertyName : STRING

        Synchronous Return:

        • ARRAY

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.getBelongsTo(STRING propertyName)

        getCount()

        Replaces: count

        Returns total number of objects for the model.

        +

        Synchronous Return:

        • INTEGER

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.getCount()

        getModel(STRING modelName)

        getModel method returns instance of the ORMModel.

        +

        Parameters

        • modelName : STRING

          Name of the model you want returned.

          +

        Synchronous Return:

        • STRING :

          NewORMModel object.

          +
          • Object : SELF_INSTANCE: Rho.NewORMModel

        Method Access:

        • Class Method: This method can only be accessed via the API class object.
          • JavaScript: Rho.NewORMModel.getModel(STRING modelName)
          • Ruby: Rho::NewORMModel.getModel(STRING modelName)

        getModelProperty(STRING propertyName)

        Returns info about model’s field property.

        +

        Parameters

        • propertyName : STRING

          The name of the property.

          +

        Synchronous Return:

        • HASH :

          Returns property name,type and option in the form of an HASH.

          +

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.getModelProperty(STRING propertyName)

        getProperties(ARRAY arrayofNames, CallBackHandler callback)

        This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

        +

        Parameters

        • arrayofNames : ARRAY

          List of properties I want to know about

          +

          • Object : STRING

        • callback : CallBackHandler Optional

        Async Callback Returning Parameters: HASH

          • : STRING

        Synchronous Return:

        • HASH :

          Map of properties I want to know about

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

        Method Access:

        • Instance Method: This method can be accessed via an instance object of this class:
          • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)

        getProperty(STRING propertyName, CallBackHandler callback)

        This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

        +

        Parameters

        • propertyName : STRING

          The property to return info about.

          +

        • callback : CallBackHandler Optional

        Async Callback Returning Parameters: STRING

          Synchronous Return:

          • STRING :

            The property to return info about.

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

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.getProperty(STRING propertyName, CallBackHandler callback)

          get_source_id()

          Deprecated

          Returns the source id number for this Rhodes model object.

          + +
                          Please use the model property source_id.
          +
          +

          Synchronous Return:

          • HASH

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.get_source_id()

          get_source_name()

          Deprecated

          Returns the source name for this Rhodes model object.

          + +
                          Please use the model property model_name.
          +
          +

          Synchronous Return:

          • HASH

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.get_source_name()

          has(STRING propertyName)

          Returns true if the model has the propertyName given.

          +

          Parameters

          • propertyName : STRING

            The name of the property you are checking for its existence.

            +

          Synchronous Return:

          • BOOLEAN

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.has(STRING propertyName)

          hasChanges(STRING objId)

          Checks whether the object has any changes. Returns true when an object is created or updated.

          +

          Parameters

          • objId : STRING

          Synchronous Return:

          • BOOLEAN

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.hasChanges(STRING objId)

          make()

          Create a new ORM model object JavaScript reference but does not save it to the database. To save this reference to the database, you will need to execute the .save() method.

          +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.make()

          new(STRING modelName)

          Initializes new model’s instance.

          +

          Parameters

          • modelName : STRING

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.new(STRING modelName)

          onSyncCreateError(ARRAY objects, STRING action)

          Handles sync create errors.

          +

          Parameters

          • objects : ARRAY

          • action : STRING

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.onSyncCreateError(ARRAY objects, STRING action)

          onSyncDeleteError(STRING objId, HASH attrHash, STRING action)

          Handles sync delete errors for the object.

          +

          Parameters

          • objId : STRING

          • attrHash : HASH

          • action : STRING

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.onSyncDeleteError(STRING objId, HASH attrHash, STRING action)

          onSyncUpdateError(STRING objId, HASH attrHash, HASH rollbackHash, STRING action)

          Handles sync update errors for the object.

          +

          Parameters

          • objId : STRING

          • attrHash : HASH

          • rollbackHash : HASH

          • action : STRING

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.onSyncUpdateError(STRING objId, HASH attrHash, HASH rollbackHash, STRING action)

          paginate(HASH params)

          The paginate method takes care of setting the proper page limit and offset when a large number of records are fetched. This method accepts parameters as key-value pairs.

          +

          Parameters

          • params : HASH

            A hash-map with paginate arguments.

            +

            • page : INTEGER Optional

              This value is an offset which indicates the prevailing page number.

              +

            • per_page : INTEGER Optional

              This value specifies number of records to be returned. The default value of per_page is 10.

              +

            • conditions : ARRAY or HASH Optional

              hash of attribute/values. Also supports sql fragment with binding(i.e. [“name=?”, “company_name”]).

              +

            • order : STRING or ARRAY Optional

              The attribute names to order the list.

              +

            • orderdir : STRING or ARRAY Optional

              Order direction: ‘ASC’ ascending, ‘DESC’ descending. Default = ‘ASC’.

              +

            • select : STRING Optional

              The array of string attributes to return with the object.

              +

          Synchronous Return:

          • ARRAY

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.paginate(HASH params)

          pushChanges()

          Pushes all changes for the source. For details push_changes

          +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.pushChanges()

          push_changes()

          Deprecated

          Pushes all changes for the source.

          +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.push_changes()

          save()

          Saves the object’s attributes in the DB.

          +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.save()

          set(STRING propertyName, STRING propertyValue)

          Sets model’s property to value with additional processing for :sync property.

          +

          Parameters

          • propertyName : STRING

            • partition : STRING

              The partition to use for this model. Partitions can be used to segment the data and keep non-synched data separate from synched models.

              +

              Possible Values :

              local

              This partition is used automatically if the model is not a sync model.

              +
              user

              This partition is used automatically if the model is a sync model.

              +
              app

              This partition is used to store the application related information.

              +
            • sync_type : STRING

              Sets the type of sync it will be.

              +

              Possible Values :

              none

              If data model is not a sync model.

              +
              incremental

              Used when the data model is a sync model. Just syncs changes.

              +
              bulk_only

              If the model is used only for bulk sync.

              +
            • sync_priority : INTEGER

              This number determines the order in which the models are processed and synchronised. Priority starts from lower value 1. Lower the number, higher is the priority. Default value is 1000.

              +

            • freezed : BOOLEAN

              To make the model Freezed.

              +

            • schema_version : FLOAT

              This is used for data migration of the application.

              +

          • propertyValue : STRING

            The property names takes the corresponding property values, as mentioned above .

            +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.set(STRING propertyName, STRING propertyValue)

          setBelongsTo(STRING propertyName, STRING sourceName)

          Using this method, you can set sync association between models. For details Associations

          +

          Parameters

          • propertyName : STRING

          • sourceName : STRING

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.setBelongsTo(STRING propertyName, STRING sourceName)

          setModelProperty(STRING propertyName, STRING propertyType, STRING propOption)

          Initializes new model’s field property.

          +

          Parameters

          • propertyName : STRING

            The name of the property.

            +

          • propertyType : STRING

            The type of property. Possible values are: String, Float, integer, Boolean, Varchar, Blob. String is default.

            +

          • propOption : STRING Optional Default: Null

            Possible Values :

            overwrite

            Overwrite client copy of blob with the new copy from server. This is useful when RhoConnect modifies images sent from Rhodes, for example zooming or cropping.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.setModelProperty(STRING propertyName, STRING propertyType, STRING propOption)

          setProperties(HASH propertyMap)

          This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

          +

          Parameters

          • propertyMap : HASH

            Map of properties I want to set

            +

            • Object : STRING

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.setProperties(HASH propertyMap)

          setProperty(STRING propertyName, STRING propertyValue)

          This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

          +

          Parameters

          • propertyName : STRING

            The one property name that I want to set

            +

          • propertyValue : STRING

            The one property value that I want to set

            +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.setProperty(STRING propertyName, STRING propertyValue)

          setSchemaIndex(STRING indexName, ARRAY indexCols, BOOLEAN is_unique)

          Initializes new model’s schema index.

          +

          Parameters

          • indexName : STRING

            To define a named index on a set of attributes.

            +

          • indexCols : ARRAY

            A set of attributes which need a indexName are passed through this array.

            +

          • is_unique : BOOLEAN

            To make the indexCols as unique column is_unique is set to true. This will prevent inserting duplicate records.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.setSchemaIndex(STRING indexName, ARRAY indexCols, BOOLEAN is_unique)

          updateAttributes(HASH attributes)

          Deprecated

          Updates the current Rho model object attributes and saves it to the database. This is the fastest way to add or update model attributes.

          +

          Parameters

          • attributes : HASH

            List of attributes and their updated values are passed as a key-value pair in this HASH.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.updateAttributes(HASH attributes)

          update_attributes(HASH attributes)

          Updates the current Rho model object attributes and saves it to the database. This is the fastest way to add or update model attributes.

          +

          Parameters

          • attributes : HASH

            List of attributes and their updated values are passed as a key-value pair in this HASH.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.update_attributes(HASH attributes)

          vars()

          Returns an object containing all propertyName and values for the model. You can use myModel.vars().name instead of myModel.get(‘name’).

          +

          Synchronous Return:

          • HASH

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.vars()
          + +

          Properties

          + +

          associations : STRING

          Returns model’s associations.

          +

          Property Access:

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

          fixed_schema : BOOLEAN

          Returns true if the model’s type is of fixed schema.

          +

          Property Access:

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

          freezed : BOOLEAN

          Returns true if the model is frozen.

          +

          Property Access:

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

          loaded : BOOLEAN

          Returns true if model is loaded.

          +

          Property Access:

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

          model_name : STRING

          Returns model’s name.

          +

          Property Access:

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

          partition : STRING

          Returns model’s Db partition.

          +

          Possible Values (STRING):

          local

          This partition is used automatically if the model is not a sync model.

          +
          user

          This partition is used automatically if the model is a sync model.

          +
          app

          This partition is used to store the application related information.

          +

          Property Access:

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

          source_id : INTEGER

          Returns model’s source_id.

          +

          Property Access:

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

          sync_priority : INTEGER

          This number determines the order in which the models are processed and synchronised. Priority starts from lower value 1. Lower the number, higher is the priority. Default value is 1000.

          +

          Property Access:

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

          sync_type : STRING

          Returns model’s Sync type.

          +

          Default: none

          Possible Values (STRING):

          none

          If data model is not a sync model.

          +
          incremental

          Used when the data model is a sync model. Just syncs changes.

          +
          bulk_only

          If the model is used only for bulk sync.

          +

          Property Access:

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

          Examples

          + +
          find_by_sql
          +

          Finds the objects of a specific model using the SQL query statements.

          +
          :::javascript
          +
          +                
          +var stdobjData = stdObj.find_by_sql("SELECT * FROM Student WHERE department = 'Mechanical'");  
          +                            
          :::ruby
          +
          +                
          +result = stdObj.find_by_sql("SELECT * FROM Student WHERE department = 'Electronics'")  
          +                            
          create
          +

          To create a model’s object including initialization.

          +
          :::javascript
          +
          +                
          +var accounts = Account.create({"name":"Craig", "age":"20"}); 
          +                            
          :::ruby
          +
          +                
          +accounts = Account.create({"name"=>"Craig","age"=>"20"}) 
          +                            
          setSchemaIndex
          +

          To set an index name to a set of attributes and indicating whether it is unique or not.

          +
          :::javascript
          +
          +                
          +model.setSchemaIndex("p1", ["name","price"], false); 
          +                            
          :::ruby
          +
          +                 
          +model.setSchemaIndex("p1", ["name","price"], false)          
          +                            
          setBelongsTo
          +

          Using this method, you can set sync association between models.

          +
          :::javascript
          +
          +                
          +var prdobjData = model.setBelongsTo("itemName", "Product");
          +                            
          :::ruby
          +
          +                
          +prdobjData = model.setBelongsTo("itemName", "Product") 
          +                            
          paginate Method Examples
          +

          To fetch the first 10 records.

          +
          :::javascript
          +
          +                
          +var accounts = Account.paginate({page:0});  
          +                            
          :::ruby
          +
          +                
          +accounts = Account.paginate({:page=>0})  
          +                            
          +

          To fetch the records numbered 21-40.

          +
          :::javascript
          +
          +                
          +var accounts = Account.paginate({page:1,per_page:20});  
          +                            
          :::ruby
          +
          +                
          +accounts = Account.paginate({:page=>1,:per_page=>20})  
          +                            
          +

          To fetch the records based on some conditions and ordering them as well.

          +
          :::javascript
          +
          +                
          +var accounts = Account.paginate({ page:5,
          +                    conditions:{'name':'Fred','salary':4000},
          +                    order: 'salary'
          +                    });  
          +                            
          :::ruby
          +
          +                
          +accounts = Account.paginate({ :page=>5,
          +                    :conditions=>{'name'=>'Fred','salary'=>4000},
          +                    :order=> 'salary'
          +                    })  
          +                            
          save
          +

          Saves the current model object to the database.

          +
          :::javascript
          +
          +                           
          +var account = Account.make({"name": "Motorola", "industry": "electronics"});
          +                account.save(); 
          +                                    
          :::ruby
          +
          +                           
          +account = Account.make({"name"=>"Motorola", "industry"=>"electronics"});
          +                account.save() 
          +                                    
          update_attributes
          +

          Updates the current model object’s attributes and saves it to the database.

          +
          :::javascript
          +
          +                           
          +var account = Account.create({'name': 'Motorola', 'industry': 'electronics'});
          +            account.update_attributes({'name':'ABB','industry':'robotics'});
          +            account.get("industry"); //"robotics"   
          +                                    
          :::ruby
          +
          +                           
          +account = Account.create({'name'=> 'Motorola', 'industry'=> 'electronics'})
          +            account.update_attributes({'name'=>'ABB','industry'=>'robotics'})
          +            account.get("industry") //"robotics"    
          +                                    
          destroy
          +

          Destroy a model object from database.

          +
          :::javascript
          +
          +                
          +var account = Account.find('first');
          +            account.destroy(); 
          +                            
          :::ruby
          +
          +                
          +account = Account.find(:first)
          +            account.destroy() 
          +                            
          has
          +

          Checks whether the propertyName exists in the model.

          +
          :::javascript
          +
          +                
          +var account = Account.find('first');
          +            account.has('salary'); 
          +                            
          :::ruby
          +
          +                
          +account = Account.find(:first)
          +            account.has('salary') 
          +                            
          vars
          +

          Returns all the propertyNames and it’s values for the model.

          +
          :::javascript
          +
          +                
          +var accounts = Account.create({"name":"Craig", "age":20});
          +            account.vars(); 
          +                            
          :::ruby
          +
          +                
          +accounts = Account.create({"name"=>"Craig", "age"=>20})
          +            account.vars() 
          +                            
          \ No newline at end of file diff --git a/docs/en/5.5/api/NewORMModel.xml b/docs/en/5.5/api/NewORMModel.xml new file mode 100644 index 00000000..44c1dbc1 --- /dev/null +++ b/docs/en/5.5/api/NewORMModel.xml @@ -0,0 +1,1031 @@ + + + + + NewORMModel CoreAPI module + New implementation of the RHOM Model. +NOTE: BETA VERSION - This API has not been officially released. It should not be used in a production environment. + + + + + + + + List of properties supported by instance of object. + + Returns true if model is loaded. + + + Returns model's name. + + + Returns model's Sync type. + + + If data model is not a sync model. + + + Used when the data model is a sync model. Just syncs changes. + + + If the model is used only for bulk sync. + + + + + This number determines the order in which the models are processed and synchronised. Priority starts from lower value 1. Lower the number, higher is the priority. Default value is 1000. + + + Returns model's Db partition. + + + This partition is used automatically if the model is not a sync model. + + + This partition is used automatically if the model is a sync model. + + + This partition is used to store the application related information. + + + + + Returns model's source_id. + + + Returns true if the model's type is of fixed schema. + + + Returns true if the model is frozen. + + + Returns model's associations. + + + + + + enumerate method returns array of ORMModel objects. + + Array of NewORMModel objects. + + + + + getModel method returns instance of the ORMModel. + + + Name of the model you want returned. + + + + NewORMModel object. + + + + + + Initializes new model's instance. + + + + + + + Initializes model's internal DB. + + + + Using this method, you can set sync association between models. For details [Associations](guide/rhom_ruby#associations) + + + + + + + + Returns info about model's relationships with other models. + + + + + + + + Sets model's property to value with additional processing for :sync property. + + + + + The partition to use for this model. Partitions can be used to segment the data and keep non-synched data separate from synched models. + + + This partition is used automatically if the model is not a sync model. + + + This partition is used automatically if the model is a sync model. + + + This partition is used to store the application related information. + + + + + Sets the type of sync it will be. + + + If data model is not a sync model. + + + Used when the data model is a sync model. Just syncs changes. + + + If the model is used only for bulk sync. + + + + + This number determines the order in which the models are processed and synchronised. Priority starts from lower value 1. Lower the number, higher is the priority. Default value is 1000. + + + To make the model Freezed. + + + This is used for data migration of the application. + + + + + The property names takes the corresponding property values, as mentioned above . + + + + + + + Sets model's Boolean property to true (enables model's property) + + + + + To set the type of model as Fixed_schema. + + + To make the model as user model. + + + To send all the attributes(changed/unchanged) to Rhoconnect when an object is updated. + + + To keep the sensitive data out of redis server. + + + + + + + + Initializes new model's field property. + + + The name of the property. + + + The type of property. Possible values are: String, Float, integer, Boolean, Varchar, Blob. String is default. + + + + + + Overwrite client copy of blob with the new copy from server. This is useful when RhoConnect modifies images sent from Rhodes, for example zooming or cropping. + + + + + + + + Returns info about model's field property. + + + The name of the property. + + + + Returns property name,type and option in the form of an HASH. + + + + + Initializes new model's schema index. + + + To define a named index on a set of attributes. + + + A set of attributes which need a indexName are passed through this array. + + + To make the indexCols as unique column is_unique is set to true. This will prevent inserting duplicate records. + + + + + + Destroys model's instance. + + + + Initializes model's object and stores it in the DB. + + + The attribute names and its respective values are passed as a key-value pair through this HASH. + + + + + + + Creates model's instance and initializes model's object but doesn't store it in DB. + + + The attribute names and its respective values are passed as a key-value pair through this HASH. + + + + + + + Checks whether the model has any changed objects. + + + + + Checks whether the object has any changes. Returns true when an object is created or updated. + + + + + + + + Checks whether the object can be modified. + + + + + + + + Updates object's attributes in the DB. + + + + + + + + + + Saves (creates if necessary or updates if already exists) object's attributes in the DB. + + + + + + + + + Deletes object's attributes from the DB. + + + + + + + Deletes all object's according to the specified conditions.It is applicable only for Fixed_schema Model. + + + This HASH takes only one key-value pair for which the key is `conditions` and the value is the attribute name. For multiple attribute names, OR/AND/IN operator is used. + + + This Array takes the values as String for the attribute names passed in the "strOptions" parameter. + + + + + + Deletes all objects for the given Property Bag model according to the specified conditions. It is applicable only for Property bag Model. + + + The attribute names and its respective values are passed as a key-value pair in this HASH. + + + This HASH is passed as an empty HASH. + + + + + + + Deletes all objects for the given Property Bag model according to the specified conditions. It is applicable only for Property bag Model. + + + The attribute names are passed as a string. + + + This Array takes the values as String for the attribute names passed in the "conditions" parameter. + + + This HASH is passed as an empty HASH. + + + + + + + Returns total number of objects for the model. + + + + + Returns time string when the source has been synced. + + + + + Returns array of objects for the given model queried according to the specified conditions. It is applicable only for Fixed_schema Model. + + + It defines the type of find operation to be performed. + + + Finds all Objects matching the 'conditions' for a specific Model. + + + Returns the number of Objects matching the 'conditions' in a specific Model. + + + Returns the first Object matching the 'conditions' in a specific Model. + + + + + This HASH takes only three key-value pairs for which the first key is `conditions` and the value is the attribute name. For multiple attribute names, OR/AND/IN operator is used. The second key is `offset` and the value is an integer which indicates the number of records to skip before returning. The third key is `per_page` and the value is an integer which specifies number of records to be returned. + + + This Array takes the values as String for the attribute names passed in the "strOptions" parameter. + + + This Array takes the attribute names as string.Useful if the model has many attributes and your query only needs a few of them. + + + This Array is formed using attribute name followed by Order direction for that attribute. Order direction: 'ASC' ascending, 'DESC' descending. Default = 'ASC'. + + + + + + + Returns array of objects for the given Property Bag model queried according to the specified conditions. It is applicable only for Property bag Model. + + + It defines the type of find operation to be performed. + + + Finds all Objects matching the 'conditions' for a specific Model. + + + Returns the number of Objects matching the 'conditions' in a specific Model. + + + Returns the first Object matching the 'conditions' in a specific Model. + + + + + The attribute names and its respective values are passed as a key-value pair in this HASH. + + + This HASH is passed as an empty HASH. + + + This Array takes the attribute names as string. Note: You must include the column name which is there in condition string and others. + + + + + + + Returns array of objects for the given Property Bag model queried according to the specified conditions. It is applicable only for Property bag Model. + + + It defines the type of find operation to be performed. + + + Finds all Objects matching the 'conditions' for a specific Model. + + + Returns the number of Objects matching the 'conditions' in a specific Model. + + + Returns the first Object matching the 'conditions' in a specific Model. + + + + + The attribute names are passed as a string. + + + This Array takes the values as String for the attribute names passed in the "conditions" parameter. + + + This HASH is passed as an empty HASH. + + + This Array takes the attribute names as string. Note: You must include the column name which is there in condition string and others. + + + + + + + Returns array of objects for the given model queried according to the specified SQL. + + + + + + + + Validates object's frozen attribute. + + + + + + + + Validates all object's frozen attributes. + + + + + + + + Aux function. + + + + + + + + + + + Aux function. + + + + + + + + + Aux function. + + + + + + + + + Aux function. Internally used to make order string. + + + + + + + + + Aux function. + + + + + + + + + This method clears all the models and the associated tables with the models. It is used only for testing purpose and not for the developing. + + + + Handles sync delete errors for the object. + + + + + + + + + Handles sync update errors for the object. + + + + + + + + + + Handles sync create errors. + + + + + + + + Pushes all changes for the source. For details [push_changes](api/rhom-api#pushchanges) + + + + Create a new ORM model object JavaScript reference but does not save it to the database. To save this reference to the database, you will need to execute the .save() method. + + + + + Initializes new model's instance. + + + + + + Create a new Rhodes model object and save it to the database. This is the fastest way to insert a single item into the database. + + + List of attributes assigned to the new model object, such as {name : "ABC Inc.",address: "555 5th St."}. + + + + + + Returns true if a Rhodes model object has local database changes that need to be synchronized, false otherwise. + + + + + + Returns the current sync client id. + + + + + + Returns the number of objects in the named model. + + + + + Checks whether the object can be modified. + + + + + + + + Updates the current Rho model object attributes and saves it to the database. This is the fastest way to add or update model attributes. + + + + List of attributes and their updated values are passed as a key-value pair in this HASH. + + + + + + Updates the current Rho model object attributes and saves it to the database. This is the fastest way to add or update model attributes. + + + List of attributes and their updated values are passed as a key-value pair in this HASH. + + + + + + The paginate method takes care of setting the proper page limit and offset when a large number of records are fetched. This method accepts parameters as key-value pairs. + + + + A hash-map with paginate arguments. + + + This value is an offset which indicates the prevailing page number. + + + + This value specifies number of records to be returned. The default value of per_page is 10. + + + + hash of attribute/values. Also supports sql fragment with binding(i.e. ["name=?", "company_name"]). + + + + The attribute names to order the list. + + + + Order direction: 'ASC' ascending, 'DESC' descending. Default = 'ASC'. + + + + The array of string attributes to return with the object. + + + + + + + + + + find('all') replaces the legacy ruby method find_all. + + + + + Saves the object's attributes in the DB. + + + Delete all Rhodes model objects for a source filtering by conditions. This method accepts parameters as key-value pairs. It accept conditions as a parameter. + + + + A hash-map with deleteAll arguments. + + + The attribute names and its respective values are passed as a key-value pair in this HASH. This will delete only the objects matching the criteria passed in the HASH. + + + + + + + + Returns true if the model has the propertyName given. + + + + The name of the property you are checking for its existence. + + + + + + + Returns an object containing all propertyName and values for the model. You can use myModel.vars().name instead of myModel.get('name'). + + + + + + Returns the source id number for this Rhodes model object. + Please use the model property source_id. + + + + + + Returns the source name for this Rhodes model object. + Please use the model property model_name. + + + + + + Get the value of a property of the current model.Ex: myModel.get('name'); See also the vars() method. + + + + The name of the property you are trying to retrieve. + + + + Value of the specified property from the database. + + + + Pushes all changes for the source. + + + + Delete all Rhodes model objects for a source filtering by conditions. This method accepts parameters as key-value pairs. It accepts 2 keys- conditions and op. + + + A hash-map with deleteAll arguments. + + + The attribute names and its respective values are passed as a key-value pair in this HASH. This will delete only the objects matching the criteria passed in the HASH.Also supports sql fragment with binding(i.e. ["name=?", "company_name"] + + + + + + + + + Find model objects. + + + + + returns all objects; can use optional :conditions. + + + returns first object matching :conditions. + + + returns the number of objects matching these :conditions. + + + + + An object of selection options + + + The attribute names and its respective values are passed as a key-value pair in this HASH that is required to find. Ex: conditions { name:'Symbol'}. Also supports sql fragment with binding(i.e. ["name=?", "company_name"]). + + + + + + + + Attribute(s) to order the list. + + + + Order direction. + + + Ascending order. (Default) + + + Descending Order + + + + + + Array of string attributes to return with the object. Useful if your model has many attributes and your query only needs a few of them. + + + + + + + + + + + + + + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + + +
          + Finds the objects of a specific model using the SQL query statements. + + + + + + + + +
          +
          +
          + + +
          + To create a model's object including initialization. + + + + + + "Craig","age"=>"20"}) ]]> + + +
          +
          +
          + + +
          + To set an index name to a set of attributes and indicating whether it is unique or not. + + + + + + + + +
          +
          +
          + + +
          + Using this method, you can set sync association between models. + + + + + + + + +
          +
          +
          + + +
          + To fetch the first 10 records. + + + + + + 0}) ]]> + + +
          +
          + To fetch the records numbered 21-40. + + + + + + 1,:per_page=>20}) ]]> + + +
          +
          + To fetch the records based on some conditions and ordering them as well. + + + + + + 5, + :conditions=>{'name'=>'Fred','salary'=>4000}, + :order=> 'salary' + }) ]]> + + +
          +
          +
          + + +
          + Saves the current model object to the database. + + + + + + "Motorola", "industry"=>"electronics"}); + account.save() ]]> + + +
          +
          +
          + + + +
          + Updates the current model object's attributes and saves it to the database. + + + + + + 'Motorola', 'industry'=> 'electronics'}) + account.update_attributes({'name'=>'ABB','industry'=>'robotics'}) + account.get("industry") //"robotics" ]]> + + +
          +
          +
          + + +
          + Destroy a model object from database. + + + + + + + + +
          +
          +
          + + +
          + Checks whether the propertyName exists in the model. + + + + + + + + +
          +
          +
          + + +
          + Returns all the propertyNames and it's values for the model. + + + + + + "Craig", "age"=>20}) + account.vars() ]]> + + +
          +
          +
          +
          +
          +
          diff --git a/docs/en/5.5/api/Notification.Led._xml b/docs/en/5.5/api/Notification.Led._xml new file mode 100644 index 00000000..aa7c2385 --- /dev/null +++ b/docs/en/5.5/api/Notification.Led._xml @@ -0,0 +1,161 @@ + + + + The LED API is a child of the Notification API and allows access to the LEDs on your device + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +### JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +### Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + + +## Enabling the API +There are two methods of enabling the Notification.Led API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Notification.Led API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.notification.led.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + iOS, Android, WM + + + + + + + + + + 1.0.0 + Human readable name for the notification object, e.g. 'Green LED'. + WM, CE, Android, iOS + + + + + + + + Used to return the LEDs present on the device, you can then subsequently illuminate or extinguish them. + iOS, Android, WM + + Array of LED objects, one for each hardware LED on the device. + + + + + + Called on an LED object returned from the enumerate method, the specified LED will be illuminated. + iOS, Android, WM + + + + Called on an LED object returned from the enumerate method, the specified LED will be extinguished. + iOS, Android, WM + + + + Called on an LED object returned from the enumerate method, the specified LED will be flashed. + iOS, Android, WM + + + The properties associated with the LED flash. + + + When flashing, the LED will remain on for this number of milliseconds + + + When flashing, the LED will remain off for this number of milliseconds + + + The LED will flash this number of times. + + + + + + + + + + + + + + + + + + +
          + + Enumerating the LEDs will return an array objects which will map to the real LEDs on the device, using these returned objects you can control the device LEDs + + + + + <% $leds.each_with_index do |led, index| %> +
        • <%= led.name %>
        • + <% end %> + + ]]> +
          +
          +
          +
          +
          +
          +
          +
          \ No newline at end of file diff --git a/docs/en/5.5/api/Notification.md b/docs/en/5.5/api/Notification.md new file mode 100644 index 00000000..dbde2734 --- /dev/null +++ b/docs/en/5.5/api/Notification.md @@ -0,0 +1,121 @@ +#Notification +
          +

          The Notification API allows you to provide feedback to the user, either auditory, tactile or visual. Use this API to give a visual popup window, sound the device beeper or illuminate the device LEDs (hardware permitting).

          +

          Enabling the API

          + +

          This API is part of the ‘coreapi’ extension that is included automatically.

          + +
          :::ruby
          +extensions: ["coreapi"]
          +
          + +

          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

          + +

          beep(HASH propertyMap)

          If the device is equipped with a beeper then a beep will be emitted. Not supported on iOS devices.

          +

          Parameters

          • propertyMap : HASH

            The properties associated with the beep.

            +

            • frequency : Integer Default: 2000

              The frequency of the beep, in Hz.

              +

            • volume : Integer Default: 1

              A number between 0 and 3. 0 represents minimum volume and 3 is maximum volume, the decibels each volume level represents is device dependent.

              +

            • duration : Integer Default: 1000

              The duration of the beep, in milliseconds.

              +

          Synchronous Return:

          • Void

          Method Access:

          • Class Method: This method can only be accessed via the API class object.
            • JavaScript: Rho.Notification.beep(HASH propertyMap)
            • Ruby: Rho::Notification.beep(HASH propertyMap)

          hidePopup()

          Closes the current popup window. On Windows Mobile/CE, Windows and RhoSimulators only Status window, displayed by showStatus can be hide.

          +

          Synchronous Return:

          • Void

          Method Access:

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

          playFile(STRING path, STRING media_type)

          Play an audio file if that media type is supported by the device.

          +

          Parameters

          • path : STRING

            The full absolute path to the file, ending in the file name and extension.

            +

          • media_type : STRING Optional Default:

            Media type can be specified explicitly, or can be recognized from the file extension. The known file extensions are “.mp3” – “audio/mpeg” and “.wav” – “audio/x-wav”.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Class Method: This method can only be accessed via the API class object.
            • JavaScript: Rho.Notification.playFile(STRING path, STRING media_type)
            • Ruby: Rho::Notification.playFile(STRING path, STRING media_type)

          showPopup(HASH propertyMap, CallBackHandler callback)

          Bring the application up front and show a message in a popup window. The message can be passed as a string or a hash. The popup window closes after you click on one of the buttons in the ‘button’ array. All custom icons' paths must be absolute paths to the icon file. Icon is not supported on iOS devices.

          +

          Parameters

          • propertyMap : HASH

            The properties associated with the popup.

            +

            • message : String Default:

              Text displayed in the popup window.

              +

            • title : String Default:

              Title of the popup window.

              +

            • icon : String Default:

              Icon to be displayed in the popup window. path to an image, or :alert for ! icon, :question for ? icon, :info for information icon. On Windows Mobile/CE, Windows and RhoSimulators only predefined icons are supported.

              + Platforms:Android

            • buttons : Array Default:

              Array of buttons. Specify each button either by hash with :id and :title keys or string.When using strings, the ‘id’ and ‘title’ will have the same value. +For example:

              + +
              :::javascript
              +buttonHash = [{id:'yes',title:'Ok to Delete'},{id:'no',title:'No'}];
              +buttonString = ['Yes', 'No'];
              +
              + +

              NOTE: For Android, if TYPE_NOTIFICATION_DIALOG is used, every button in the notification uses an icon. By default a star icon is used. If the button id is ‘accept’ then the system accept icon is used. If the button id is ‘cancel’ then the system cancel icon is used.

              +

            • types : Array

              List which notification kinds will be shown. Several types may be listed at same time. ‘TYPE_NOTIFICATION’ and ‘TYPE_NOTIFICATION_DIALOG’ take no effect if application is in the foreground. By default ‘[Rho.Notification.TYPE_DIALOG, Rho.Notification.TYPE_NOTIFICATION]’ is used. +Example:

              + +
              :::javascript
              +typeToast = [Rho.Notification.TYPE_DIALOG, Rho.Notification.TYPE_TOAST];
              +
              +

              Possible Values :

              Constant: Rho::Notification.TYPE_DIALOG (For Ruby use "::" for all "." when referencing constants)
              String:dialog

              Show common dialog window with buttons visible if application is active.

              +
              Constant: Rho::Notification.TYPE_NOTIFICATION (For Ruby use "::" for all "." when referencing constants)
              String:notification

              Show message in Android notification bar if application is at background. Touch the message opens the application.

              +
              Constant: Rho::Notification.TYPE_NOTIFICATION_DIALOG (For Ruby use "::" for all "." when referencing constants)
              String:notificationDialog

              This is the same as ‘TYPE_DIALOG’ + ‘TYPE_NOTIFICATION’.

              + +

              NOTE: In Android 4.1 and above, buttons are also added to the notification message so the user can interact with the application without application activation (dialog window is not shown if user pressed button in notification). Buttons are not always displayed in the notification area – this depends on screen size and layout and system decides whether to show buttons. You need to drag notification to make buttons appear.

              +
              Constant: Rho::Notification.TYPE_TOAST (For Ruby use "::" for all "." when referencing constants)
              String:toast

              Show toast window with message at foreground for a short time. The toast is visible nevertheless the application is at background or foreground but is not shown same time with any foreground pop-up.

              +
          • callback : CallBackHandler Optional

          Async Callback Returning Parameters: HASH

            • button_id : STRING

              ID assigned to the button when showing the popup.

              +

            • button_title : STRING

              Button text.

              +

            • button_index : STRING

              The index in the ‘buttons’ array.

              +

          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.Notification.showPopup(HASH propertyMap, CallBackHandler callback)
            • Ruby: Rho::Notification.showPopup(HASH propertyMap, CallBackHandler callback)

          showStatus(STRING title, STRING status_text, STRING hide_button_label)

          Display a window containing a status message. The window closes after the user clicks on its hide button. Note: Android will show a toast message for a short time in addition to a dialog window.

          +

          Parameters

          • title : STRING Optional

            The title on the status message popup window.

            +

          • status_text : STRING

            The status message displayed in the popup status window.

            +

          • hide_button_label : STRING

            The label text for the hide button in the popup status window. On Windows Mobile/CE, Windows and RhoSimulators Windows Close icon used to hide the status window.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Class Method: This method can only be accessed via the API class object.
            • JavaScript: Rho.Notification.showStatus(STRING title, STRING status_text, STRING hide_button_label)
            • Ruby: Rho::Notification.showStatus(STRING title, STRING status_text, STRING hide_button_label)

          vibrate(Integer duration)

          Vibrate the device’s pager hardware. Need ‘vibrate’ capability set at build.yml for Android.

          +

          Parameters

          • duration : Integer Optional Default: 1000

            The duration of the vibration, in milliseconds. Note you may also need to add the vibration capability to your build.yml file. See remarks for maximum duration. iOS devices have fixed system vibration time. It could not be changed. Android and Windows devices have default vibration time 1000 ms.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Class Method: This method can only be accessed via the API class object.
            • JavaScript: Rho.Notification.vibrate(Integer duration)
            • Ruby: Rho::Notification.vibrate(Integer duration)
          + +

          Examples

          + +
          Sound the device beeper
          +

          Not every device is equipped with a hardware beeper but if present this code snippet will cause the beeper to sound.

          +
          :::ruby
          +
          +           
          +# ---------------
          +# controller.rb
          +# ---------------
          +
          +def sound_beeper
          +  # Obtain list of available leds on the device.
          +  beeperProps = Hash.new
          +  beeperProps['frequency'] = 3000;
          +  beeperProps['volume'] = 2;
          +  beeperProps['duration'] = 1500;
          +  Rho::Notification.beep(beeperProps)
          +end
          +                   
          +                 
          Show an alert
          +

          This example shows how to show an alert in JavaScript.

          +
          :::javascript
          +
          +           
          +function show_alert()
          +{
          +    //creates a popup with a message and two buttons
          +    Rho.Notification.showPopup({
          +        title:'My Popup',
          +        message:'Do you really want to delete this record',
          +        buttons:[
          +            {id:'yes',title:'Ok to Delete'},
          +            {id:'no',title:'No'}]
          +        },
          +            function(e){
          +                if(e.button_id == "yes")
          +                {
          +                    // go ahead and delete the record
          +                }
          +            }
          +    );
          +}
          +                   
          +                 
          + +

          Remarks

          + +
          Maximum vibrate duration

          On Android, the maximum duration for vibrate is 15 seconds (15000ms).

          +
          Spuriously reported hardware

          Some Windows Mobile or CE devices may report hardware which is not present on the device such as a pager or LEDs. This is a limitation of the underlying driver layer reporting spurious results to the application, though all real hardware will be controllable.

          +
          Maximum Button text size

          It is recommend to use maximum 15 Character for the button text in pop up , above to this limit it behave as per OS Behavior.

          +
          \ No newline at end of file diff --git a/docs/en/5.5/api/Notification.xml b/docs/en/5.5/api/Notification.xml new file mode 100644 index 00000000..a58ea8e9 --- /dev/null +++ b/docs/en/5.5/api/Notification.xml @@ -0,0 +1,295 @@ + + + + The Notification API allows you to provide feedback to the user, either auditory, tactile or visual. Use this API to give a visual popup window, sound the device beeper or illuminate the device LEDs (hardware permitting). + +## Enabling the API +This API is part of the 'coreapi' extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the Notification API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the '/Enterprise Browser/JavaScript Files/Enterprise Browser' directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the 'ebapi.js' in your HTML as well as the API file you want to use. For instance, to use the Notification API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.notification.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + iOS, Android, WM + Android, WM + + + + + + + Bring the application up front and show a message in a popup window. The message can be passed as a string or a hash. The popup window closes after you click on one of the buttons in the 'button' array. All custom icons' paths must be absolute paths to the icon file. Icon is not supported on iOS devices. + Bring the application up front and show a message in a popup window. The message can be passed as a string or a hash. The popup window closes after you click on one of the buttons in the 'button' array. All custom icons' paths must be absolute paths to the icon file. + WM, CE, Android, iOS, Win32 + WM, CE, Android, Win32 + + + The properties associated with the popup. + + + Text displayed in the popup window. + + + Title of the popup window. + + + Icon to be displayed in the popup window. path to an image, or :alert for ! icon, :question for ? icon, :info for information icon. On Windows Mobile/CE, Windows and RhoSimulators only predefined icons are supported. + Icon to be displayed in the popup window. path to an image, or :alert for ! icon, :question for ? icon, :info for information icon. On Windows Mobile/CE only predefined icons are supported. The file that you are playing must be located on the device or the icon may not display properly. + Android + + + Array of buttons. Specify each button either by hash with :id and :title keys or string.When using strings, the 'id' and 'title' will have the same value. +For example: + + :::javascript + buttonHash = [{id:'yes',title:'Ok to Delete'},{id:'no',title:'No'}]; + buttonString = ['Yes', 'No']; + +>NOTE: For Android, if TYPE_NOTIFICATION_DIALOG is used, every button in the notification uses an icon. By default a star icon is used. If the button id is 'accept' then the system accept icon is used. If the button id is 'cancel' then the system cancel icon is used. + + + + List which notification kinds will be shown. Several types may be listed at same time. 'TYPE_NOTIFICATION' and 'TYPE_NOTIFICATION_DIALOG' take no effect if application is in the foreground. By default '[Rho.Notification.TYPE_DIALOG, Rho.Notification.TYPE_NOTIFICATION]' is used. +Example: + + :::javascript + typeToast = [Rho.Notification.TYPE_DIALOG, Rho.Notification.TYPE_TOAST]; +List which notification kinds will be shown. Several types may be listed at same time. 'TYPE_NOTIFICATION' and 'TYPE_NOTIFICATION_DIALOG' take no effect if application is in the foreground. By default '[EB.Notification.TYPE_DIALOG, Rho.Notification.TYPE_NOTIFICATION]' is used. + +Example: + + :::javascript + typeToast = [EB.Notification.TYPE_DIALOG, Rho.Notification.TYPE_TOAST]; + + Android + + + Show common dialog window with buttons visible if application is active. + + + Show message in Android notification bar if application is at background. Touch the message opens the application. + + + This is the same as 'TYPE_DIALOG' + 'TYPE_NOTIFICATION'. + +>NOTE: In Android 4.1 and above, buttons are also added to the notification message so the user can interact with the application without application activation (dialog window is not shown if user pressed button in notification). Buttons are not always displayed in the notification area - this depends on screen size and layout and system decides whether to show buttons. You need to drag notification to make buttons appear. + + + Show toast window with message at foreground for a short time. The toast is visible nevertheless the application is at background or foreground but is not shown same time with any foreground pop-up. + + + + + + + + A hash/object is returned indicated which button was pressed. + + + ID assigned to the button when showing the popup. + + + Button text. + + + The index in the 'buttons' array. + + + + + + + Closes the current popup window. On Windows Mobile/CE, Windows and RhoSimulators only Status window, displayed by showStatus can be hide. + Closes the current popup window. On Windows Mobile/CE only Status window, displayed by showStatus can be hide. + WM, CE, Android, iOS, Win32 + WM, CE, Android, Win32 + + + + Display a window containing a status message. The window closes after the user clicks on its hide button. Note: Android will show a toast message for a short time in addition to a dialog window. + WM, CE, Android, iOS, Win32 + WM, CE, Android, Win32 + + + + The title on the status message popup window. + + + The status message displayed in the popup status window. + + + The label text for the hide button in the popup status window. On Windows Mobile/CE, Windows and RhoSimulators Windows Close icon used to hide the status window. + The label text for the hide button in the popup status window. On Windows Mobile/CE Close icon used to hide the status window. + iOS, Android, WP8 + Android + + + + + + Play an audio file if that media type is supported by the device. + iOS, Android, WM + Android, WM + + + The full absolute path to the file, ending in the file name and extension. + The full absolute path to the file, ending in the file name and extension. The file that you are playing must be located on the device or the file may not play correctly. + + + + Media type can be specified explicitly, or can be recognized from the file extension. The known file extensions are ".mp3" - "audio/mpeg" and ".wav" - "audio/x-wav". + iOS, Android + Android + + + + + + If the device is equipped with a beeper then a beep will be emitted. Not supported on iOS devices. + If the device is equipped with a beeper then a beep will be emitted. + Android, WM + + + The properties associated with the beep. + + + The frequency of the beep, in Hz. + + + A number between 0 and 3. 0 represents minimum volume and 3 is maximum volume, the decibels each volume level represents is device dependent. + + + The duration of the beep, in milliseconds. + + + + + + + + Vibrate the device's pager hardware. Need 'vibrate' capability set at build.yml for Android. + iOS, Android, WM + Android, WM + + + + The duration of the vibration, in milliseconds. Note you may also need to add the vibration capability to your build.yml file. See remarks for maximum duration. iOS devices have fixed system vibration time. It could not be changed. Android and Windows devices have default vibration time 1000 ms. + The duration of the vibration, in milliseconds. Note you may also need to add the vibration capability to your build.yml file. See remarks for maximum duration. Android and Windows devices have default vibration time 1000 ms. + + + + + + + + + + 1.0.0 + + + + +
          + Not every device is equipped with a hardware beeper but if present this code snippet will cause the beeper to sound. + + + + + +
          +
          +
          + + +
          + This example shows how to show an alert in JavaScript. + + + + + +
          +
          +
          +
          + + + On Android, the maximum duration for vibrate is 15 seconds (15000ms). + + + Some Windows Mobile or CE devices may report hardware which is not present on the device such as a pager or LEDs. This is a limitation of the underlying driver layer reporting spurious results to the application, though all real hardware will be controllable. + + + It is recommend to use maximum 15 Character for the button text in pop up , above to this limit it behave as per OS Behavior. + + +
          +
          diff --git a/docs/en/5.5/api/Orm.md b/docs/en/5.5/api/Orm.md new file mode 100644 index 00000000..8d4cb0a9 --- /dev/null +++ b/docs/en/5.5/api/Orm.md @@ -0,0 +1,134 @@ +#ORM +
          +

          This JavaScript API class allows you to interact with the local RHOM database and programatically add models or get references to models.

          +

          Enabling the API

          + +

          This API is part of the coreapi extension that is included automatically.

          + +
          :::ruby
          +extensions: ["coreapi"]
          +
          + +

          JavaScript Usage

          + +

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

          + +

          If you are going to be using the JS ORM API, you’ll also need to include these lines in any files that will be using it:

          + +
          :::html
          +<script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-ORM.js"></script>
          +<script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-ORMHelper.js"></script>
          +<script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-Ruby-RunTime.js"></script>
          +
          + +

          Ruby Usage

          + +

          For Ruby access to the RHOM database please see the Rhom Ruby API guide.

          + + + +

          Methods

          + +

          addModel( Anoynomous Function methods)

          Creates an ORM model reference.

          +

          Parameters

          • Anoynomous Function methods :

            • modelName("value") : STRING

              The name of your model.

              +

            • enable("value") : STRING Optional

              Enables Model Properties.

              +

              Possible Values :

              sync

              If set then model is set for RhoConnect Sync.

              +
              propertyBag

              (Default) Model will be of type propertyBag.

              +
              fixedSchema

              Model will be of type fixedSchema.

              +
            • property("name","type") : STRING,STRING Optional

              Used to create properties on your model.

              +

              • name : STRING

                The name of the property.

                +

              • type : STRING

                The type of property value: String, Float, integer, Varchar, Blob – String is default.

                +

            • addIndex("name",[colArray]) : STRING, ARRAY Optional

              Add an index to your fixedSchema model.

              +

              • name : STRING

                The name of the index.

                +

              • colArray : ARRAY

                Array of model column names to use in index, Ex: [‘name’,‘qty’]

                +

            • addUniqueIndex("name",[colArray]) : STRING, ARRAY Optional

              Add an index to your fixedSchema model.

              +

              • name : STRING

                The name of the index.

                +

              • colArray : ARRAY

                Array of model column names to use in index, Ex: [‘name’,‘qty’]

                +

            • belongs_to("name") : STRING Optional

              Add belongs_to association to another defined model, for sync models. Comma-separated String for more than one model.

              +

            • set(property,value) : STRING,VALUE Optional

              Set Behavior of this model. Possible property options and corresponding values.

              +

              • partition : STRING

                The partition to use for this model. Partitions can be used to segment the data and keep non-synched data separate from synched models. Possible values.

                +

                Possible Values :

                local

                This partition is used automatically if the model is not a sync model.

                +
                user

                This partition is used automatically if the model is a sync model.

                +
              • sync_type : STRING

                Sets the type of sync it will be.

                +

                Possible Values :

                none

                If data model is not a sync model.

                +
                incremental

                Used when the data model is a sync model. Just syncs changes.

                +
              • sync_priority : INTEGER

                Determines how frequently to check for changes. In seconds. Default is 1000.

                +

          Synchronous Return:

          • Model

          Method Access:

          • Class Method: This method can only be accessed via the API class object.
            • JavaScript: Rho.ORM.addModel( Anoynomous Function methods)

          databaseFullReset(BOOLEAN resetClientInfo, BOOLEAN resetLocalModels)

          Deletes all records from the property bag and model tables.

          +

          Parameters

          • resetClientInfo : BOOLEAN Optional

            True to clean the client_info table, false otherwise.

            +

            False on default.

            +

          • resetLocalModels : BOOLEAN Optional

            True to clean local (non-synced) models, false otherwise.

            +

            Reset all models.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Class Method: This method can only be accessed via the API class object.
            • JavaScript: Rho.ORM.databaseFullReset(BOOLEAN resetClientInfo, BOOLEAN resetLocalModels)

          databaseFullResetAndLogout()

          Deletes all records from the property bag and model tables. Logout the user from RhoConnectClient. For examples, see Resetting the Database in Using the Local Database with ORM.

          +

          Synchronous Return:

          • Void

          Method Access:

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

          databaseFullResetEx(HASH propertyMap)

          Deletes all records from the property bag and model tables for the model names passed in parameters.

          +

          Parameters

          • propertyMap : HASH

            Properties map.

            +

            • models : ARRAY

              Array of models names to reset.

              +

            • reset_client_info : BOOLEAN Optional

              If set to true, client_info table will be cleaned.

              +

              False on default.

              +

            • reset_local_models : BOOLEAN Optional Default: false

              If set to true, local(non-synced models) will be cleaned.

              +

              Reset all models.

              +

          Synchronous Return:

          • Void

          Method Access:

          • Class Method: This method can only be accessed via the API class object.
            • JavaScript: Rho.ORM.databaseFullResetEx(HASH propertyMap)

          databaseFullclientResetAndLogout()

          Deletes all records from the property bag and model tables. Logout the user from RhoConnectClient and erase all RhoConnectClient device information. Equivalent to ORM::ORM.databaseFullReset(true) followed by RhoConnectClient.logout.

          +

          Synchronous Return:

          • Void

          Method Access:

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

          databaseLocalReset()

          Reset only local (non-sync-enabled) models.

          +

          Synchronous Return:

          • Void

          Method Access:

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

          export()

          Deprecated

          Export db.

          +

          Synchronous Return:

          • STRING

          Method Access:

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

          getClientId()

          Returns the current sync client id.

          +

          Synchronous Return:

          • STRING

          Method Access:

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

          getModel(String modelName)

          Returns a model.

          +

          Parameters

          • modelName : String

            Name of the model you want returned.

            +

          Synchronous Return:

          • Model

          Method Access:

          • Class Method: This method can only be accessed via the API class object.
            • JavaScript: Rho.ORM.getModel(String modelName)

          haveLocalChanges()

          Returns true if any of the Rhodes model objects have local database changes that need to be synchronized, false otherwise.

          +

          Synchronous Return:

          • BOOLEAN

          Method Access:

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

          import(STRING zipName)

          Deprecated

          Import db.

          +

          Parameters

          • zipName : STRING

            The name of the zip file.

            +

          Synchronous Return:

          • BOOLEAN

          Method Access:

          • Class Method: This method can only be accessed via the API class object.
            • JavaScript: Rho.ORM.import(STRING zipName)
          + +

          Examples

          + +
          Add ORM model, create ORM object
          +

          This example describes creating model and adding model object.

          +
          :::javascript
          +
          +                
          +var productModel = Rho.ORM.addModel(function(model){
          +  model.modelName("Product");
          +  model.enable("sync");
          +  model.property("name","string");
          +  model.property("brand","string");
          +  model.property("price","float");
          +  model.set("partition","user");
          +});
          +
          +// create model object and save it to database
          +var product = productModel.create({
          +  brand: 'Apple',
          +  name: 'iPhone5',
          +  price: 199.99});
          +
          +// read product from database
          +var product = productModel.find('first');
          +product.get('brand'); // Apple
          +product.get('name'); // iPhone5
          +
          +                        
          Get Model by name
          +

          Get a model.

          +
          :::javascript
          +
          +   
          +// The model 'Product' must have been defined in JavaScript execution earlier
          +// in order for 'getModel' to work properly.
          +
          +// The models generated in RhoStudio, are not accessible in JavaScript unless
          +// the classes are defined via the  Rho.ORM.addModel api
          +
          +
          +// Get a model by its name after it has been added
          +var productModel = Rho.ORM.getModel("Product");
          +
          +           
          +                    
          ORM databaseFullResetEx Method Examples
          +

          Delete all Rhodes model objects for a source, filtering by conditions.

          +
          :::javascript
          +
          +                
          +Rho.ORM.databaseFullResetEx({'models' : ['Product', 'Customer'], 'reset_client_info' : true, 'reset_local_models' : true} 
          +                            
          + +

          Remarks

          + +
          Performance Findings Using Property Bag Vs Fixed Schema

          In our testing, we have found that, overall, the Fixed Schema database model has much better performance that the same tests run using Property Bag, concerning complex data sets. We strongly recommend that enterprise-grade apps use the Fixed Schema model for their app databases as we have seen test results upwards of 10 times faster using the Fixed Schema model. The only current drawback to Fixed Schema is that it is more complex to initially setup. If your dataset is fairly simple in construction, Property Bag should prove sufficient.

          +
          \ No newline at end of file diff --git a/docs/en/5.5/api/Orm.xml b/docs/en/5.5/api/Orm.xml new file mode 100644 index 00000000..2cb68ab3 --- /dev/null +++ b/docs/en/5.5/api/Orm.xml @@ -0,0 +1,330 @@ + + + + + This JavaScript API class allows you to interact with the local RHOM database and programatically add models or get references to models. + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +If you are going to be using the JS ORM API, you'll also need to include these lines in any files that will be using it: + + :::html + <script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-ORM.js"></script> + <script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-ORMHelper.js"></script> + <script type="text/javascript" charset="utf-8" src="/public/api/rhoapi-modules-Ruby-RunTime.js"></script> + +## Ruby Usage +For Ruby access to the RHOM database please see the [Rhom Ruby API guide](/api/rhom-api). + + + + + + + + + + + + + Deletes all records from the property bag and model tables. + + + + True to clean the client_info table, false otherwise. + false + + False on default. + + + + True to clean local (non-synced) models, false otherwise. + false + + Reset all models. + + + + + + + Import db. + + + + The name of the zip file. + + + + + + + Returns the current sync client id. + + + + + + Returns true if any of the Rhodes model objects have local database changes that need to be synchronized, false otherwise. + + + + + + Export db. + + + + + + Deletes all records from the property bag and model tables. Logout the user from RhoConnectClient. For examples, see Resetting the Database in Using the Local Database with ORM. + + + + + Reset only local (non-sync-enabled) models. + + + + + Deletes all records from the property bag and model tables. Logout the user from RhoConnectClient and erase all RhoConnectClient device information. Equivalent to ORM::ORM.databaseFullReset(true) followed by RhoConnectClient.logout. + + + + + Deletes all records from the property bag and model tables for the model names passed in parameters. + + + + Properties map. + + + Array of models names to reset. + + + If set to true, client_info table will be cleaned. + + False on default. + + + + If set to true, local(non-synced models) will be cleaned. + + Reset all models. + + + + + + + + Returns a model. + + + Name of the model you want returned. + + + + + + + Creates an ORM model reference. + + + + + + The name of your model. + + + Enables Model Properties. + + + If set then model is set for RhoConnect Sync. + + + (Default) Model will be of type propertyBag. + + + Model will be of type fixedSchema. + + + + + + + Used to create properties on your model. + + + The name of the property. + + + The type of property value: String, Float, integer, Varchar, Blob - String is default. + + + + + + + Add an index to your fixedSchema model. + + + The name of the index. + + + Array of model column names to use in index, Ex: ['name','qty'] + + + + + + + Add an index to your fixedSchema model. + + + The name of the index. + + + Array of model column names to use in index, Ex: ['name','qty'] + + + + + + + Add belongs_to association to another defined model, for sync models. Comma-separated String for more than one model. + + + + + Set Behavior of this model. Possible `property` options and corresponding values. + + + + + The partition to use for this model. Partitions can be used to segment the data and keep non-synched data separate from synched models. Possible `values`. + + + This partition is used automatically if the model is not a sync model. + + + This partition is used automatically if the model is a sync model. + + + + + Sets the type of sync it will be. + + + If data model is not a sync model. + + + Used when the data model is a sync model. Just syncs changes. + + + + + Determines how frequently to check for changes. In seconds. Default is 1000. + + + + + + + + + + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + +
          + This example describes creating model and adding model object. + + + + + +
          +
          +
          + + +
          + Get a model. + + + + + +
          +
          +
          + + +
          + Delete all Rhodes model objects for a source, filtering by conditions. + + + + + +
          +
          +
          +
          + + + + + +
          +
          \ No newline at end of file diff --git a/docs/en/5.5/api/OrmModel.md b/docs/en/5.5/api/OrmModel.md new file mode 100644 index 00000000..bfc61181 --- /dev/null +++ b/docs/en/5.5/api/OrmModel.md @@ -0,0 +1,200 @@ +#[Your-OrmModel] +
          +

          RhoMobile applications provide automatic JavaScript CRUD methods for any models that you have defined to interact with the database. You must define a model class by using the ORM.addModel method before you can use the API’s referenced here. See Orm to learn about defining and adding a model.

          + +

          All methods here are accessed from the model instance object that you have created. In places where you see [Your-OrmModel] on this page, you would use the instance object instead.

          + +
          :::js
          +var productModel = Rho.ORM.addModel(function(model){
          +  model.modelName("Product");
          +  model.enable("sync");
          +  model.property("name","string");
          +  model.property("brand","string");
          +  model.property("price","float");
          +  model.set("partition","user");
          +});
          +
          +// create model object and save it to database
          +var product = productModel.create({
          +  brand: 'Apple',
          +  name: 'iPhone5',
          +  price: 199.99});
          +
          +// read product from database
          +var product = productModel.find('first');
          +product.get('brand'); // Apple
          +product.get('name'); // iPhone5
          +
          +

          Enabling the API

          + +

          This API is part of the coreapi extension that is included automatically.

          + +
          :::ruby
          +extensions: ["coreapi"]
          +
          + +

          JavaScript Usage

          + +

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

          + +

          Ruby Usage

          + +

          For Ruby access to the RHOM database please see the Rhom Ruby API guide.

          + + + +

          Methods

          + +

          canModify()

          Deprecated

          Returns true if the Rhodes model object is not currently being synced (if it is being synced, you should disable editing of the object). Before displaying an edit page for an object, your application can check if the object is currently being accessed by the sync process. If it is, you should disable editing of the object. can_modify could return true, for example, on a new local record that was created and sent to the RhoConnect application, but no response has been received yet.

          +

          Synchronous Return:

          • BOOLEAN

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.canModify()

          create(HASH attributes)

          Create a new Rhodes model object and save it to the database. This is the fastest way to insert a single item into the database.

          +

          Parameters

          • attributes : HASH

            List of attributes assigned to the new model object, such as {name : “ABC Inc.”,address: “555 5th St.”}.

            +

          Synchronous Return:

          • OBJECT

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.create(HASH attributes)

          deleteAll()

          Delete all Rhodes model objects for a source.For JavaScript you cannot specify conditions.

          +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.deleteAll()

          destroy()

          Destroy a Rhodes model object and removes the record from the database.

          +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.destroy()

          find(STRING queryType, HASH queryOptions)

          Find model objects.

          +

          Parameters

          • queryType : STRING

            Possible Values :

            all

            returns all objects; can use optional :conditions.

            +
            first

            returns first object matching :conditions.

            +
            count

            returns the number of objects matching these :conditions.

            +
          • queryOptions : HASH

            An object of selection options

            +

            • conditions : HASH

              A name:value object that you want to find. Ex: conditions { name:‘Symbol’}.

              +

              • propertyName :

              • propertyValue :

            • order : STRING Optional

              Attribute(s) to order the list. This cannot be used when using a select parameter and you must pass a conditions hash.

              +

            • orderdir : STRING Optional

              Order direction. This cannot be used when using a select parameter and you must pass a conditions hash

              +

              Possible Values :

              ASC

              Ascending order. (Default)

              +
              DESC

              Descending Order

              +
            • select : ARRAY Optional

              Array of string attributes to return with the object. Useful if your model has many attributes and your query only needs a few of them. This cannot be used in combination with order or orderdir.

              +

          Synchronous Return:

          • ARRAY

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.find(STRING queryType, HASH queryOptions)

          get(STRING propertyName)

          Get the value of a property of the current model.Ex: myModel.get(‘name’); See also the vars() method.

          +

          Parameters

          • propertyName : STRING

            The name of the property you are trying to retrieve.

            +

          Synchronous Return:

          • STRING :

            Value of the specified property from the database.

            +

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.get(STRING propertyName)

          has(STRING propertyName)

          Returns true or false if the model has the propertyName given.

          +

          Parameters

          • propertyName : STRING

            The name of the property you are checking for validity. See also the vars() method.

            +

          Synchronous Return:

          • BOOLEAN

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.has(STRING propertyName)

          make(HASH attributes)

          Create a new Rhodes model object JavaScript reference but does not save it to the database. To save this reference to the database, you will need to execute the .save() method. See the ORM new example.

          +

          Parameters

          • attributes : HASH

            List of attributes assigned to the new model object, such as {name:“ABC Inc.”,address:“5555th St.”}.

            +

          Synchronous Return:

          • OBJECT

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.make(HASH attributes)

          object()

          Returns the unique ID for the data record. Use this to identify records. You can also use this in a .find() method for retrieving a specific record.

          +

          Synchronous Return:

          • STRING

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.object()

          save()

          Saves the current Rhodes model object to the database.

          +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.save()

          set(STRING propertyName, STRING propertyValue)

          Sets the value of a property of the current model. Ex: myModel.set(‘name’,‘new name’); This does not save to the database until you execute a myModel.save().

          +

          Parameters

          • propertyName : STRING

            The name of the property you are trying to set.

            +

          • propertyValue : STRING

            The value you are setting in the current model. After setting values you must issue a .save() in order for the data to be saved to the database.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.set(STRING propertyName, STRING propertyValue)

          updateAttributes(HASH attributes)

          Updates the current Rho model object attributes and saves it to the database. This is the fastest way to add or update model attributes.

          +

          Parameters

          • attributes : HASH

            List of attributes and their updated values, such as {name : “ABC Inc.”,address: “555 5th St.”}.

            +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.updateAttributes(HASH attributes)

          vars()

          Returns an object containing all propertyName and values for the model. You can use myModel.vars().name instead of myModel.get(‘name’).

          +

          Synchronous Return:

          • HASH

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.vars()
          + +

          Examples

          + +
          ORM Make and Create Method Examples
          +

          Use method make for creating a new ORM object and assign given attributes. Make does not save to the database until you execute a .save. To insert a new record right away use the create method instead.

          +
          :::javascript
          +
          +                
          +var account = Account.make({name: "ABC Inc.", address: "555 5th St."});
          +account.get("name") // "ABC Inc." 
          +                            
          +

          Use method Create for creating a new ORM object and save to the database.

          +
          :::javascript
          +
          +                
          +var account = Account.create({name: "some new record", industry: "electronics"})  
          +                            
          ORM DeleteAll Method Examples
          +

          Delete all Rhodes model objects for a source, filtering by conditions.

          +
          :::javascript
          +
          +                
          +Account.deleteAll();
          +                            
          ORM Find Method Examples
          +

          Find all objects for specific ORM model

          +
          :::javascript
          +
          +                
          +vat accounts = Account.find('all');
          +                            
          +

          Find all objects for specific ORM model with conditions

          +
          :::javascript
          +
          +                
          +var accounts = Account.find(
          +    'all',
          +    {
          +      conditions: {industry: 'Technology'}
          +    }
          +  ) 
          +                            
          +

          Use select option for retrieves some attributes of object. You must pass “conditions” hash with Javascript implementation.

          +
          :::javascript
          +
          +                
          +var accounts = Account.find(
          +    'all',
          +    {
          +      conditions: {name:'address'},
          +      select: ['name','address']
          +    }
          +  );
          +accounts[0].get("name");  // "A.G. Parr PLC 37862"
          +accounts[0].get("telephone"); // nil 
          +                            
          +

          Order option is used to sort objects by one or more attributes. You must pass a conditions hash to use ordering.

          +
          :::javascript
          +
          +                
          +var accounts = Account.find(
          +    'all',
          +    {
          +      conditions: {"name":"industry"},
          +      order: 'name',
          +      orderdir: 'DESC'
          +    }
          +  ) 
          +                            
          +

          Order by multiple attributes. You must pass conditions hash.

          +
          :::javascript
          +
          +                
          +var accounts = Account.find(
          +    'all',
          +    {
          +      conditions: {"name":"industry"},
          +      order: ['name', 'industry'],
          +      orderdir: ['ASC', 'DESC']
          +    }
          +  ); 
          +                            
          +

          Order by one attribute with an orderFunction.

          +
          :::javascript
          +
          +                
          +var accounts = Account.find(
          +    'all',
          +    {
          +      order: 'name',
          +      orderFunction: function (a, b) { return a <= b }
          +    }
          +  ); 
          +                            
          +

          Order with a block.

          +
          :::javascript
          +
          +                
          +var accounts = Account.find(
          +    'all',
          +    {
          +      orderFunction: function (item1, item2) { return item1.name <= item2.name }
          +    }
          +); 
          +                            
          ORM Destroy Method Examples
          +

          Destroy a Rhodes model object from database.

          +
          :::javascript
          +
          +                
          +var account = Account.find('first');
          +account.destroy();
          +                            
          ORM UpdateAttributes Method Example
          +

          Update the current ORM object’s attributes and saves it to the database.

          +
          :::javascript
          +
          +var account = Account.find("first", {conditions: {name: "ABC Inc."});
          +account.updateAttributes({name: "ABC Inc.", industry: "Technology"});
          +account.get("industry") // "Technology"
          ORM Save Method Example
          +

          Saves the current ORM object to the database.

          +
          :::javascript
          +
          +var account = Account.make({name: "some new record", industry: "electronics"});
          +account.save();
          \ No newline at end of file diff --git a/docs/en/5.5/api/OrmModel.xml b/docs/en/5.5/api/OrmModel.xml new file mode 100644 index 00000000..e68186ef --- /dev/null +++ b/docs/en/5.5/api/OrmModel.xml @@ -0,0 +1,404 @@ + + + + + RhoMobile applications provide automatic JavaScript CRUD methods for any models that you have defined to interact with the database. You must define a model class by using the [ORM.addModel](Orm#maddModel) method before you can use the API's referenced here. See [Orm](Orm) to learn about defining and adding a model. + +All methods here are accessed from the model instance object that you have created. In places where you see `[Your-OrmModel]` on this page, you would use the instance object instead. + + :::js + var productModel = Rho.ORM.addModel(function(model){ + model.modelName("Product"); + model.enable("sync"); + model.property("name","string"); + model.property("brand","string"); + model.property("price","float"); + model.set("partition","user"); + }); + + // create model object and save it to database + var product = productModel.create({ + brand: 'Apple', + name: 'iPhone5', + price: 199.99}); + + // read product from database + var product = productModel.find('first'); + product.get('brand'); // Apple + product.get('name'); // iPhone5 + + + Orm + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +For Ruby access to the RHOM database please see the [Rhom Ruby API guide](/api/rhom-api). + + + + + + + + + + + Delete all Rhodes model objects for a source.For JavaScript you cannot specify conditions. + + + + + Find model objects. + + + + + + returns all objects; can use optional :conditions. + + + returns first object matching :conditions. + + + returns the number of objects matching these :conditions. + + + + + An object of selection options + + + A name:value object that you want to find. Ex: conditions { name:'Symbol'}. + + + + + + + Attribute(s) to order the list. This cannot be used when using a select parameter and you must pass a conditions hash. + + + + Order direction. This cannot be used when using a select parameter and you must pass a conditions hash + + + Ascending order. (Default) + + + Descending Order + + + + + + Array of string attributes to return with the object. Useful if your model has many attributes and your query only needs a few of them. This cannot be used in combination with order or orderdir. + + + + + + + + + + Create a new Rhodes model object JavaScript reference but does not save it to the database. To save this reference to the database, you will need to execute the .save() method. See the ORM new example. + + + List of attributes assigned to the new model object, such as {name:"ABC Inc.",address:"5555th St."}. + + + + + + + + Create a new Rhodes model object and save it to the database. This is the fastest way to insert a single item into the database. + + + + List of attributes assigned to the new model object, such as {name : "ABC Inc.",address: "555 5th St."}. + + + + + + + Destroy a Rhodes model object and removes the record from the database. + + + + + Returns true if the Rhodes model object is not currently being synced (if it is being synced, you should disable editing of the object). Before displaying an edit page for an object, your application can check if the object is currently being accessed by the sync process. If it is, you should disable editing of the object. can_modify could return true, for example, on a new local record that was created and sent to the RhoConnect application, but no response has been received yet. + + + + + + Returns an object containing all propertyName and values for the model. You can use myModel.vars().name instead of myModel.get('name'). + + + + + + Returns the unique ID for the data record. Use this to identify records. You can also use this in a .find() method for retrieving a specific record. + + + + + + Returns true or false if the model has the propertyName given. + + + + The name of the property you are checking for validity. See also the vars() method. + + + + + + + Get the value of a property of the current model.Ex: myModel.get('name'); See also the vars() method. + + + The name of the property you are trying to retrieve. + + + + + Value of the specified property from the database. + + + + + Sets the value of a property of the current model. Ex: myModel.set('name','new name'); This does not save to the database until you execute a myModel.save(). + + + The name of the property you are trying to set. + + + The value you are setting in the current model. After setting values you must issue a .save() in order for the data to be saved to the database. + + + + + + + Saves the current Rhodes model object to the database. + + + + + Updates the current Rho model object attributes and saves it to the database. This is the fastest way to add or update model attributes. + + + List of attributes and their updated values, such as {name : "ABC Inc.",address: "555 5th St."}. + + + + + + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + +
          + Use method make for creating a new ORM object and assign given attributes. Make does not save to the database until you execute a .save. To insert a new record right away use the create method instead. + + + + + +
          +
          + Use method Create for creating a new ORM object and save to the database. + + + + + +
          +
          +
          + + + +
          + Delete all Rhodes model objects for a source, filtering by conditions. + + + + + +
          +
          +
          + + + +
          + Find all objects for specific ORM model + + + + + +
          +
          + Find all objects for specific ORM model with conditions + + + + + +
          +
          + Use select option for retrieves some attributes of object. You must pass "conditions" hash with Javascript implementation. + + + + + +
          +
          + Order option is used to sort objects by one or more attributes. You must pass a conditions hash to use ordering. + + + + + +
          +
          + Order by multiple attributes. You must pass conditions hash. + + + + + +
          +
          + Order by one attribute with an orderFunction. + + + + + +
          +
          + Order with a block. + + + + + +
          +
          +
          + + + +
          + Destroy a Rhodes model object from database. + + + + + +
          +
          +
          + + + +
          + Update the current ORM object’s attributes and saves it to the database. + + +var account = Account.find("first", {conditions: {name: "ABC Inc."}); +account.updateAttributes({name: "ABC Inc.", industry: "Technology"}); +account.get("industry") // "Technology" + +
          +
          +
          + + + +
          + Saves the current ORM object to the database. + + +var account = Account.make({name: "some new record", industry: "electronics"}); +account.save(); + +
          +
          +
          +
          +
          +
          \ No newline at end of file diff --git a/docs/en/5.5/api/Record.md b/docs/en/5.5/api/Record.md new file mode 100644 index 00000000..78376592 --- /dev/null +++ b/docs/en/5.5/api/Record.md @@ -0,0 +1,39 @@ +#Record +
          +

          NFC Record

          +

          This class representative Record object

          + +

          Enabling the API

          + +

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

          + +
          :::ruby
          +extensions: ["nfc"]
          +
          + +

          NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

          + + + +

          Methods

          + +

          close()

          Release resources.

          +

          Synchronous Return:

          • Void

          Method Access:

          • Instance Method: This method can be accessed via an instance object of this class:
            • myObject.close()

          create()

          Creates record.

          +

          Synchronous Return:

          • Rho.NFC.Record :

            Record object.

            +

          Method Access:

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

          Properties

          + +

          ID : STRING Read Only

          Object ID.

          +

          Property Access:

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

          payload : STRING

          Record payload(data buffer).

          +

          Property Access:

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

          recordId : STRING

          Optional field for NFC_NDEF_RTD_GENERAL record type.

          +

          Property Access:

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

          textCharEncoding : INTEGER

          Use if record type is NFC_NDEF_RTD_TEXT. Values see NFC Forum. For example UTF-8 is 2 and it will be set by default. This property will be ignored in read tag mode, you should find it in a payload.

          +

          Property Access:

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

          textLanguage : STRING

          Use if record type is NFC_NDEF_RTD_TEXT. This property will be ignored in read tag mode. This property will be ignored in read tag mode, you should find it in a payload.

          +

          Property Access:

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

          tnf : INTEGER

          When you create a new record then this field is needed for NFC_NDEF_RTD_GENERAL, for another types it will be set automatically.

          +

          Possible Values (false):

          Constant: Rho.Record.NDEF_TNF_EMPTY (For Ruby use "::" for all "." when referencing constants)
          String: 1
          Constant: Rho.Record.NDEF_TNF_WELL_KNOWN (For Ruby use "::" for all "." when referencing constants)
          String: 2
          Constant: Rho.Record.NDEF_TNF_MEDIA (For Ruby use "::" for all "." when referencing constants)
          String: 3
          Constant: Rho.Record.NDEF_TNF_ABSOLUTE_URI (For Ruby use "::" for all "." when referencing constants)
          String: 4
          Constant: Rho.Record.NDEF_TNF_EXTERNAL (For Ruby use "::" for all "." when referencing constants)
          String: 5
          Constant: Rho.Record.NDEF_TNF_UNKNOWN (For Ruby use "::" for all "." when referencing constants)
          String: 6
          Constant: Rho.Record.NDEF_TNF_UNCHANGED (For Ruby use "::" for all "." when referencing constants)
          String: 7
          Constant: Rho.Record.NDEF_TNF_ANY_TYPE (For Ruby use "::" for all "." when referencing constants)
          String: 8

          Property Access:

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

          type : INTEGER

          Record type. This property will be ignored in read tag mode. If you create a record you should set this property firstly.

          +

          Possible Values (false):

          Constant: Rho.Record.NDEF_RTD_TEXT (For Ruby use "::" for all "." when referencing constants)
          String: 1

          A text type record.

          +
          Constant: Rho.Record.NDEF_RTD_URI (For Ruby use "::" for all "." when referencing constants)
          String: 2

          A URI type record.

          +
          Constant: Rho.Record.NDEF_RTD_GENERAL (For Ruby use "::" for all "." when referencing constants)
          String: 3

          A generic type record.

          +

          Property Access:

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

          typeName : STRING

          When you create a new record then this field is needed for NFC_NDEF_RTD_GENERAL, for another types it will be set automatically. For values see NFC Forum.

          +

          Property Access:

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

          uriProtocol : INTEGER

          Use if record type is NFC_NDEF_RTD_URI. For values please see NFC Forum. This property will be ignored in read tag mode, you should find it in a payload.

          +

          Property Access:

          • Instance: This property can be accessed via an instance object of this class:
            • myObject.uriProtocol
          \ No newline at end of file diff --git a/docs/en/5.5/api/Record.xml b/docs/en/5.5/api/Record.xml new file mode 100644 index 00000000..49a16b49 --- /dev/null +++ b/docs/en/5.5/api/Record.xml @@ -0,0 +1,155 @@ + + + + + NFC Record + This class representative Record object +# Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["nfc"] + +NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + + +## Enabling the API +There are two methods of enabling the Record API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Record API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.record.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + List of properties supported by class. + + + Object ID. + WM + + + + Optional field for NFC_NDEF_RTD_GENERAL record type. + WM + + + + Record type. This property will be ignored in read tag mode. If you create a record you should set this property firstly. + + + A text type record. + + + A URI type record. + + + A generic type record. + + + WM + + + + When you create a new record then this field is needed for NFC_NDEF_RTD_GENERAL, for another types it will be set automatically. For values see NFC Forum. + WM + + + + When you create a new record then this field is needed for NFC_NDEF_RTD_GENERAL, for another types it will be set automatically. + + + + + + + + + + + + + + + + + + + + + + + + + + + WM + + + + Use if record type is NFC_NDEF_RTD_TEXT. This property will be ignored in read tag mode. This property will be ignored in read tag mode, you should find it in a payload. + WM + + + + Use if record type is NFC_NDEF_RTD_TEXT. Values see NFC Forum. For example UTF-8 is 2 and it will be set by default. This property will be ignored in read tag mode, you should find it in a payload. + WM + + + + Use if record type is NFC_NDEF_RTD_URI. For values please see NFC Forum. This property will be ignored in read tag mode, you should find it in a payload. + WM + + + + Record payload(data buffer). + WM + + + + + + Creates record. + + Record object. + + WM + + + + Release resources. + WM + + + + + + + 1.0.0 + + + + \ No newline at end of file diff --git a/docs/en/5.5/api/RhoConnectClient.md b/docs/en/5.5/api/RhoConnectClient.md new file mode 100644 index 00000000..e5f99b76 --- /dev/null +++ b/docs/en/5.5/api/RhoConnectClient.md @@ -0,0 +1,448 @@ +#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

          + +
          :::ruby
          +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.

            +
            :::javascript
            +
            +
            +Rho.RhoConnectClient.login('john','password',function(result){
            +   loginCallback(result);
            +});
            +                          
            :::ruby
            +
            +
            +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).
            +
            +
            :::javascript
            +
            +// 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
            +  }
            +}
            +                            
            :::ruby
            +
            +# 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:

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

            Which is the same as:

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

            You can also set a notification for all models:

            +
            :::javascript
            +
            +function syncNotify(params) {
            +  // handle notifications...
            +}
            +Rho.RhoConnectClient.setNotification('*', syncNotify);
            +
            +                            
            :::ruby
            +
            +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.

            +
            :::ruby
            +
            +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:

            +
            :::javascript
            +
            +function syncObjectNotified(params) {
            +  // handle notifications...
            +}
            +
            +var product = Product.find('first');
            +
            +Rho.RhoConnectClient.addObjectNotify('Product', product.id);
            +
            +                            
            :::ruby
            +
            +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:

            +
            :::javascript
            +
            +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);
            +
            +                            
            :::ruby
            +
            +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:

            +
            :::ruby
            +
            +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:

            +
            :::ruby
            +
            +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:

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

            JavaScript Example:

            + +
            :::javascript
            +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.

            +
            \ No newline at end of file diff --git a/docs/en/5.5/api/RhoConnectClient.xml b/docs/en/5.5/api/RhoConnectClient.xml new file mode 100644 index 00000000..bcd8670c --- /dev/null +++ b/docs/en/5.5/api/RhoConnectClient.xml @@ -0,0 +1,726 @@ + + + + + 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` + :::ruby + extensions: ["rhoconnect-client"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + + + + + + + These properties are used to configure RhoConnectClient global behavior or retrieving current configuration parameters. + + + Current username of the RhoConnectClient session if isLoggedIn is true, otherwise returns the last logged in username. + + + + Sync poll interval in seconds. Setting this to 0 will disable polling-based sync. Sync process will be triggered automatically according to this setting. + + + + Sync server URL. + + + + 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. + + + + Page size for RhoConnectClient. Default size is 2000. + + + + Sets if RhoConnectClient will work in a separate thread. If true then calls to login, doSync, doSyncSource and search will perform asynchronously without delaying calling thread. Results should be handled in provided callbacks. If false, all calls are blocking and resuls are returned directly from method calls. Default is true. + + + + Enable or disable show status popup. + + + + Enable or disable verification of RhoConnect ssl certificates, true by default. + + + + + + + Deprecated name of doSync method. + + + + Deprecated name of setObjectNotification method. + + + + Deprecated name of addObjectNotify method. + + + + Deprecated name of cleanObjectNotify method. + + + + Deprecated name of stopSync method. + + + + + Returns true if the RhoConnectClient currently has a user session, false if not. + + True if have logged in user session, false if not. + + + + + Returns true if sync is currently in progress. + + True if sync has started but not finished yet, false otherwise. + + + + + If you have a large dataset in your backend service, you don't have to synchronize everything with the RhoConnectClient. Instead you can filter the synchronized dataset using the RhoConnectClient's search function. Provide callback, which will be executed after search is completed. + Not currently supported in JavaScript. + + + Hash of arguments passed to search. + + + Array of source names to be included in search result. + + + + Default is 'search' + + + + + Hash of key-value pairs to be included in search result. + + + + + + + + + Maximum number of results to be returned. + + + + + + + + + If true and there are local changes, client sync will be triggered before search. + + + + + + + + Will return value only if threadedMode set to false. Otherwise search results returned in callback. + + + + + Resulting status of search. 'ok' of completed successfully, 'error' otherwise. + + + + Search_params originally provided for the search call. Typically you want to forward the original search_params to your view that displays the results so you can perform the same query locally. Please see examples section. + + + + + + + Start the RhoConnectClient sync process. + + + Set to true to show status popup. + + + + + Parameters to be passed to server. + + + + + Sync only sources that have local changes. + + + + + + + + Start RhoConnectClient sync process for a given source name. + + + Source name. + + + + + Set to true to show status popup. + + + + + Parameters to be passed to server. + + + + + + + Authenticates the user with RhoConnect. The callback will be executed when it is finished. + + + Login name. + + + + Password. + + + + + + + Logout the user from the RhoConnect server. This removes the local user session. + + + + Stops any sync operations currently in progress. + + + + 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. + + + Source name for which notification will be enabled. Use '*' to set notification for all models. + + + + + + Clears the sync notification for a given source. + + + Source name to clear notification. Use '*' to clear notification for all models. + + + + + + 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. + + + + Array of created objects. + + + + Array of updated objects. + + + + Array of deleted objects. + + + + + + + Add the object notification by passing in an object ID. + + + Source name for object notification. + + + Object ID to get notifications. + + + + + + Removes callback for object notifications. + + + + Returns number of synced objects for a given source. + + + Source name. + + + + + + + Sets property value for a given source. + + + Source name. + + + + Property name. + + + + Property value. + + + + + + Gets property value for a given source. + + + Source name. + + + + Property name. + + + + + + + 1.0.0 + WM, Win32, Android, iOS, WP8 + WM, Win32, Android + + + Call login method and then handle login result in provided callback. + +
            + In your controller call login. + + + :login_callback) +)]]> + + + + + +
            +
            + + When RhoConnectClient.login completes, the callback declared is executed and receives parameters including success or failure and error messages (if any). + + + :login, :query => {:msg => @msg}) + ) + end +end]]> + + + + +
            +
            +
            + + In this example, once the sync process for the Account model is complete, a callback will be invoked (we define as `sync_notify` here) with the status and errors (if any). + +
            + First, assign a sync notification for the Account model: + + :sync_notify), + "sync_complete=true" +)]]> + + + + +
            +
            + Which is the same as: + + :sync_notify), + "sync_complete=true" +)]]> + + + + +
            +
            + You can also set a notification for all models: + + :sync_notify), + "sync_complete=true" +)]]> + + + + +
            +
            +
            + + + +
            + To use object notifications, first set the notification callback in application.rb#initialize. + + "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: + + + + + + +
            +
            +
            + + Sync callbacks are invoked with a hash parameter containing the status and relevant errors (if any) applicable for the current sync process. Using callbacks you can process errors that occurred when the RhoConnectClient last synchronized. + +
            + Here we will set a notification and log an error code 1 or ERR_NETWORK: + + :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 consists of two steps: invoking the search function with the search criteria, process the search results in a callback and update the UI. + +
            + First, call search from your controller action: + + '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: + + :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 +]]> + + +
            +
            +
            +
            + + + "Error connecting to backend server: http://rhostore.herokuapp.com" + +JavaScript Example: + :::javascript + 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. +]]> + + + + + + + + +
            +
            \ No newline at end of file diff --git a/docs/en/5.5/api/SimulScan.md b/docs/en/5.5/api/SimulScan.md new file mode 100644 index 00000000..81c594fb --- /dev/null +++ b/docs/en/5.5/api/SimulScan.md @@ -0,0 +1,209 @@ +#SimulScan +
            +

            The SimulScan Document Capture is a software solution that enables customers to extract and process various types of information from documents. A single document may contain barcodes, text, image data and forms, using SimulScan Document Capture this data can be extracted programmatically using OCR, barcode decoding and image capture. For example, a driver’s license can be thought of as a template containing regions such as name and address, signature and photo, each of these regions are processed and returned to RhoElements separately by SimulScan Document Capture so Optical Character Recognition captures the owners name and address whilst their photo is captured separately. These regions are defined by a template which maps the various regions of the document to the data they contain and can be created on-line at The SimulScan Document Capture template builder. This API is available only on Symbol Android devices with firmware supporting SimulScan Document Capture.

            +

            Enabling the API

            + +

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

            + +
            :::ruby
            +extensions: ["simulscan"]
            +
            + +

            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

            + +

            captureDocument(CallBackHandler callback)

            Capture a document by either taking a photo of it and process that image for fields defined in the template. You must specify the template associated with the capture either through the template property or as part of the propertyMap when calling this method. If the document processing does not succeed the returned callback will contain failure description. If the captured document is processed successfully a callback will contain document data.

            +

            Parameters

            • callback : CallBackHandler Mandatory

            Async Callback Returning Parameters: HASH

              • callbackType : STRING

                Indicates whether the document was decoded successfully or not.

                +

                Possible Values :

                Constant: Rho.SimulScan.SUCCESS (For Ruby use "::" for all "." when referencing constants)
                String:success

                The document was decoded and processed successfully and this callback contains information about the processed form. Look at processedForm parameter.

                +
                Constant: Rho.SimulScan.FAILURE (For Ruby use "::" for all "." when referencing constants)
                String:failure

                An error has occurred whilst processing the document. Look at failureReason parameter.

                +
                Constant: Rho.SimulScan.STOP (For Ruby use "::" for all "." when referencing constants)
                String:stop

                The processing is over. No more notifications until next captureDocument.

                +
              • failureReason : STRING

                Describes reason for failure.

                +

                Possible Values :

                Constant: Rho.SimulScan.FAILURE_ERROR (For Ruby use "::" for all "." when referencing constants)
                String:error

                SimulScan Document Capture engine generic error.

                +
                Constant: Rho.SimulScan.FAILURE_IDENTIFICATION_TIMEOUT (For Ruby use "::" for all "." when referencing constants)
                String:identificationTimeout

                Identification timeout. Refer to identificationTimeout property.

                +
                Constant: Rho.SimulScan.FAILURE_PROCESSING_TIMEOUT (For Ruby use "::" for all "." when referencing constants)
                String:processingTimeout

                Processing timeout. Refer to processingTimeout property.

                +
              • processedForm : HASH

                • template : HASH

                  • name : STRING

                    The name of the template was used for recognition.

                    +

                  • number : INTEGER

                    The number of the template was used for recognition.

                    +

                • formCapture : HASH

                  • name : STRING

                    The name of the template was used for recognition.

                    +

                  • image : HASH

                    The image of whole scanned form.

                    +

                    • width : INTEGER

                      Width of scanned form in pixels.

                      +

                    • height : INTEGER

                      Height of scanned form in pixels.

                      +

                    • id : INTEGER

                      Id of scanned form image. Use getDataUri method to retrieve image data. The id is valid until close method is called.

                      +

                • regions : ARRAY

                  • group : STRING

                    The name of the group this region is found in, as defined in the template associated with the recognized region. It’s optional parameter.

                    +

                  • name : STRING

                    The name of the region, as defined in the template associated with the document.

                    +

                  • number : INTEGER

                    The number of the region, as defined in the template section associated with the recognized region.

                    +

                  • processingMode : STRING

                    The type of region which has been decoded.

                    +

                    Possible Values :

                    Constant: Rho.SimulScan.PM_OCR (For Ruby use "::" for all "." when referencing constants)
                    String: ocr

                    Optical Character Recognition. The region is a text field. The processedData parameter contains array of lines.

                    +
                    Constant: Rho.SimulScan.PM_OMR (For Ruby use "::" for all "." when referencing constants)
                    String: omr

                    Optical Mark Recognition. The region is a check box or radio box. The processedData parameter of this callback will contain a boolean value.

                    +
                    Constant: Rho.SimulScan.PM_PICTURE (For Ruby use "::" for all "." when referencing constants)
                    String: picture

                    The defined region was captured as a picture. No processedData parameter. Use the image callback property with the getDataUri() to get a DataURI of the image.

                    +
                    Constant: Rho.SimulScan.PM_BARCODE (For Ruby use "::" for all "." when referencing constants)
                    String: barcode

                    The region is a barcode and the decoded barcode data is given in the processedData parameter.

                    +
                  • processedData : STRING

                    The processed data contained in the specified region, this will depend on the type of region being captured. See the values of the processingMode parameter.

                    +

                  • image : STRING

                    The image of region.

                    +

                    • width : INTEGER

                      Width of region in pixels.

                      +

                    • height : INTEGER

                      Height of region in pixels.

                      +

                    • id : INTEGER

                      Id of region image. Use getDataUri method to retrieve image data. Id is valid until the close method is called.

                      +

                  • relativeOcrConfidence : INTEGER

                    Relative OCR confidence for processed data if applicable.

                    +

                  • absoluteOcrConfidence : INTEGER

                    Absolute OCR confidence for processed data if applicable.

                    +

            Synchronous Return:

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

            Method Access:

            • Instance Method: This method can be accessed via an instance object of this class:
              • myObject.captureDocument(CallBackHandler callback)
            • Default Instance: This method can be accessed via the default instance object of this class.
              • JavaScript: Rho.SimulScan.captureDocument(CallBackHandler callback)
              • Ruby: Rho::SimulScan.captureDocument(CallBackHandler callback)

            Destructor close()

            Close SimulScan Document Capture engine, and release allocated resources. When capturing images, this is especially important since they are made available temporarily.

            +

            Synchronous Return:

            • Void

            Method Access:

            • Class Method: This method is a destructor and can only be accessed via the object that was created by the `new` constructor.
              • JavaScript: myObj.close()
              • Ruby: @myObj.close()

            fetchTemplates(STRING userName, STRING password)

            Fetch templates from dedicated SimulScan Document Capture server and place into template directory. See templateDirectory property. The device must have access to the network and can access the SimulScan Document Capture Template Builder Website

            +

            Parameters

            • userName : STRING

              Username of the user.

              +

            • password : STRING

              Password of the user.

              +

            Synchronous Return:

            • Void

            Method Access:

            • Instance Method: This method can be accessed via an instance object of this class:
              • myObject.fetchTemplates(STRING userName, STRING password)
            • Default Instance: This method can be accessed via the default instance object of this class.
              • JavaScript: Rho.SimulScan.fetchTemplates(STRING userName, STRING password)
              • Ruby: Rho::SimulScan.fetchTemplates(STRING userName, STRING password)

            getAllProperties(CallBackHandler callback)

            This method will return all of object/value pairs for the propertyNames of the API class.

            +

            Parameters

            • callback : CallBackHandler Optional

            Async Callback Returning Parameters: HASH

              • : STRING

            Synchronous Return:

            • HASH :

              Map of all available properties

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

            Method Access:

            • Instance Method: This method can be accessed via an instance object of this class:
              • myObject.getAllProperties(CallBackHandler callback)
            • Default Instance: This method can be accessed via the default instance object of this class.
              • JavaScript: Rho.SimulScan.getAllProperties(CallBackHandler callback)
              • Ruby: Rho::SimulScan.getAllProperties(CallBackHandler callback)

            getDataUri(INTEGER imageId)

            Return data URI encoding of the raw image associated with the region or captured form, this allows the operator to easily verify that the captured data is accurate and if necessary perform any post processing changes by hand. To show the image on the HTML page insert the data URI string into the src attribute of the img tag:

            + +
                :::html
            +    <img src="dataURI string;">
            +
            +

            Parameters

            • imageId : INTEGER

              Id of image to retrieve. Ids are valid until close method call.

              +

            Synchronous Return:

            • Void

            Method Access:

            • Instance Method: This method can be accessed via an instance object of this class:
              • myObject.getDataUri(INTEGER imageId)
            • Default Instance: This method can be accessed via the default instance object of this class.
              • JavaScript: Rho.SimulScan.getDataUri(INTEGER imageId)
              • Ruby: Rho::SimulScan.getDataUri(INTEGER imageId)

            getDefault()

            This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

            +

            Synchronous Return:

            • SELF_INSTANCE :

              Default object of Module.

              +

            Method Access:

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

            getProperties(ARRAY arrayofNames, CallBackHandler callback)

            This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

            +

            Parameters

            • arrayofNames : ARRAY

              List of properties I want to know about

              +

              • Object : STRING

            • callback : CallBackHandler Optional

            Async Callback Returning Parameters: HASH

              • : STRING

            Synchronous Return:

            • HASH :

              Map of properties I want to know about

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

            Method Access:

            • Instance Method: This method can be accessed via an instance object of this class:
              • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
            • Default Instance: This method can be accessed via the default instance object of this class.
              • JavaScript: Rho.SimulScan.getProperties(ARRAY arrayofNames, CallBackHandler callback)
              • Ruby: Rho::SimulScan.getProperties(ARRAY arrayofNames, CallBackHandler callback)

            getProperty(STRING propertyName, CallBackHandler callback)

            This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

            +

            Parameters

            • propertyName : STRING

              The property to return info about.

              +

            • callback : CallBackHandler Optional

            Async Callback Returning Parameters: STRING

              Synchronous Return:

              • STRING :

                The property to return info about.

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

              Method Access:

              • Instance Method: This method can be accessed via an instance object of this class:
                • myObject.getProperty(STRING propertyName, CallBackHandler callback)
              • Default Instance: This method can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.getProperty(STRING propertyName, CallBackHandler callback)
                • Ruby: Rho::SimulScan.getProperty(STRING propertyName, CallBackHandler callback)

              setDefault(SELF_INSTANCE: Rho::SimulScan defaultInstance)

              This method allows you to set the attributes of the default object instance by passing in an object of the same class.

              +

              Parameters

              • defaultInstance : SELF_INSTANCE: Rho::SimulScan

                An instance object that is of the same class.

                +

              Synchronous Return:

              • Void

              Method Access:

              • Class Method: This method can only be accessed via the API class object.
                • JavaScript: Rho.SimulScan.setDefault(SELF_INSTANCE: Rho::SimulScan defaultInstance)
                • Ruby: Rho::SimulScan.setDefault(SELF_INSTANCE: Rho::SimulScan defaultInstance)

              setProperties(HASH propertyMap)

              This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

              +

              Parameters

              • propertyMap : HASH

                Map of properties I want to set

                +

                • Object : STRING

              Synchronous Return:

              • Void

              Method Access:

              • Instance Method: This method can be accessed via an instance object of this class:
                • myObject.setProperties(HASH propertyMap)
              • Default Instance: This method can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.setProperties(HASH propertyMap)
                • Ruby: Rho::SimulScan.setProperties(HASH propertyMap)

              setProperty(STRING propertyName, STRING propertyValue)

              This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

              +

              Parameters

              • propertyName : STRING

                The one property name that I want to set

                +

              • propertyValue : STRING

                The one property value that I want to set

                +

              Synchronous Return:

              • Void

              Method Access:

              • Instance Method: This method can be accessed via an instance object of this class:
                • myObject.setProperty(STRING propertyName, STRING propertyValue)
              • Default Instance: This method can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.setProperty(STRING propertyName, STRING propertyValue)
                • Ruby: Rho::SimulScan.setProperty(STRING propertyName, STRING propertyValue)
              + +

              Properties

              + +

              audioFeedback : BOOLEAN

              Whether or not to provide audio feedback to the user following document processing.

              +

              Default: true

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.audioFeedback
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.audioFeedback
                • Ruby: Rho::SimulScan.audioFeedback

              autoImageCapture : BOOLEAN

              If true, form will be captured automatically when detected. If false, user must manually tap screen or press trigger to capture the form.

              +

              Default: true

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.autoImageCapture
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.autoImageCapture
                • Ruby: Rho::SimulScan.autoImageCapture

              debug : BOOLEAN

              If enabled, allows a session to write form capture, region images, region values, and other data to storage.

              +

              Default: false

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.debug
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.debug
                • Ruby: Rho::SimulScan.debug

              decodeAudioFeedback : STRING

              Specifies the decode sound (beep) that is heard when a form is decoded.

              +

              Default: system/media/audio/notifications/decode.wav

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.decodeAudioFeedback
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.decodeAudioFeedback
                • Ruby: Rho::SimulScan.decodeAudioFeedback

              delayResultDisplay : BOOLEAN

              If true, the success event will be sent only after the SimulScan Document Capture dialog is dismissed. If false, the event will be sent immediately after the results are ready. A false value is recommended unless direct interaction with the underlying application is necessary (e.g. keystroke input).

              +

              Default: false

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.delayResultDisplay
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.delayResultDisplay
                • Ruby: Rho::SimulScan.delayResultDisplay

              flashMode : STRING

              Flash mode (off, on, disabled).

              +

              Default: off

              Possible Values (STRING):

              Constant: Rho.SimulScan.FLASH_OFF (For Ruby use "::" for all "." when referencing constants)
              String: off

              Turn flash off.

              +
              Constant: Rho.SimulScan.FLASH_ON (For Ruby use "::" for all "." when referencing constants)
              String: on

              Turn flash on.

              +
              Constant: Rho.SimulScan.FLASH_DISABLED (For Ruby use "::" for all "." when referencing constants)
              String: disabled

              Disable flash.

              +

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.flashMode
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.flashMode
                • Ruby: Rho::SimulScan.flashMode

              frameThreshold : INTEGER

              Only used if autoImageCapture is enabled. The number of correct frames that is needed to pass before SimulScan Document Capture will automatically start to process form. This should be between 5 and 30.

              +

              Default: 15

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.frameThreshold
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.frameThreshold
                • Ruby: Rho::SimulScan.frameThreshold

              hapticFeedback : BOOLEAN

              Whether or not to provide haptic feedback to the user following document processing.

              +

              Default: true

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.hapticFeedback
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.hapticFeedback
                • Ruby: Rho::SimulScan.hapticFeedback

              identificationTimeout : INTEGER

              The length of time, in milliseconds that the processing engine has to recognize the image from the provided template. From 0 to 20000 in increments of 100.

              +

              Default: 15000

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.identificationTimeout
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.identificationTimeout
                • Ruby: Rho::SimulScan.identificationTimeout

              inputSource : STRING

              Defines where the document should be captured from. The only supported source is camera.

              +

              Default: camera

              Possible Values (STRING):

              Constant: Rho.SimulScan.SOURCE_CAMERA (For Ruby use "::" for all "." when referencing constants)
              String: camera

              The document will be captured from the device camera. After calling the captureDocument method the camera preview will be presented, the user should place the document to be captured in the preview frame and press the soft button to capture & process the image.

              +

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.inputSource
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.inputSource
                • Ruby: Rho::SimulScan.inputSource

              ledFeedback : BOOLEAN

              Whether or not to provide LED feedback to the user following document processing.

              +

              Default: true

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.ledFeedback
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.ledFeedback
                • Ruby: Rho::SimulScan.ledFeedback

              logDirectory : STRING

              Specify which directory to search for logs in.

              +

              Default: /sdcard/SimulScanLog

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.logDirectory
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.logDirectory
                • Ruby: Rho::SimulScan.logDirectory

              negativeFrameThreshold : INTEGER

              Only used if autoImageCapture is enabled. Number of incorrect frames that is allowed to pass before the frame counter is reset for automatic image capture. This should be between 0 and 20.

              +

              Default: 2

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.negativeFrameThreshold
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.negativeFrameThreshold
                • Ruby: Rho::SimulScan.negativeFrameThreshold

              processingTimeout : INTEGER

              Amount of time in milliseconds to wait before timing out processing.

              +

              Default: 10000

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.processingTimeout
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.processingTimeout
                • Ruby: Rho::SimulScan.processingTimeout

              template : STRING

              The template XML which defines the document to be processed. This should be file URI to the template on the device. You must provide this property to define the form being captured and what is contained in each region on that form. Templates are specific to each document format you intend on capturing and can be created on-line at https://dpx-uat.motorolasolutions.com/.

              +

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.template
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.template
                • Ruby: Rho::SimulScan.template

              templateDirectory : STRING

              Specify where to store downloaded templates. See fetchTemplates()

              +

              Default: /sdcard/templates

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.templateDirectory
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.templateDirectory
                • Ruby: Rho::SimulScan.templateDirectory

              uiResultConfirmation : BOOLEAN

              If enabled, shows a UI confirmation with results in SimulScan Document Capture View before sending results back to application.

              +

              Default: true

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.uiResultConfirmation
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.uiResultConfirmation
                • Ruby: Rho::SimulScan.uiResultConfirmation

              version : STRING Read Only

              Version of SimulScan Document Capture engine.

              +

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.version
              • Default Instance: This property can be accessed via the default instance object of this class.
                • JavaScript: Rho.SimulScan.version
                • Ruby: Rho::SimulScan.version
              + +

              Examples

              + +
              Download Templates
              +

              Before you are able to process any documents with the SimulScan Document Capture engine, you must have template files loaded on the device. These template files must be located in an area that is open to both the SimulScan Document Capture Engine as well as your application. To retrieve the templates from the server, you would use the fetchTemplates method. This method will communicate with the SimulScan Document Capture back-end and download the templates to the folder that is specified by the templateDirectory property

              +
              :::javascript
              +
              +			 
              +function downloadSimulScanTemplates(user,password){
              +	// If you include your SimulScan Document Capture template files in the applications public folder
              +	// the SimulScan Document Capture engine will not be able to access them due to Android
              +	// security policies
              +
              +	Rho.SimulScan.templateDirectory = 'file:///sdcard/Templates';
              +	Rho.SimulScan.fetchTemplates(user,password);
              +	templates = Rho.RhoFile.listDir(Rho.SimulScan.templateDirectory);
              +	for (var i = 0; i < templates.length; ++i) {
              +		console.log(templates[i]);
              +	}
              +}
              +					 
              Capture Document
              +

              The only requirement for capturing a document is to have the SimulScan Document Capture template file location set using the SimulScan.template property. This must be an absolute URI to the locale file. The location must also be in a folder that is openly available to both your application and the SimulScan Document Capture engine (i.e. it cannot be in the applications public folder)

              +
              :::javascript
              +
              +			 
              +// POSTAL.XML was exported from the SimulScan Document Capture Template Builder
              +// In the Template Builder there were several fields defined
              +
              +Rho.SimulScan.template = 'file:///sdcard/Templates/POSTAL.XML';
              +
              +// Once the captureDocument method is launched,
              +// the SimulScan Document Capture Engine dialog appears instructing the
              +// user to hold the device steady over the printed label
              +// The callback function will be triggered possibly for
              +// many reasons
              +
              +Rho.SimulScan.captureDocument(function(params){
              +	if(params.callbackType == Rho.SimulScan.SUCCESS ){
              +		// process the returned object:
              +		var returnedField = params.processedForm;
              +		processSimulScanForm(returnedField);
              +	}
              +
              +	if(params.callbackType == Rho.SimulScan.FAILURE ){
              +		if(params.failureReason == Rho.SimulScan.FAILURE_IDENTIFICATION_TIMEOUT){
              +			// This means it could not identify the label based on the template used
              +			// Possible reasons
              +			//    -label is the wrong label
              +			//    -Template is poorly defined
              +			//      maybe scanned in image for defining was not high enough resolution
              +			//    -camera cannot focus
              +
              +			// This may trigger multiple times and may not warrant display information
              +			// in your app - the SimulScan Document Capture engine will prompt the user in most cases
              +		}
              +		if(params.failureReason == Rho.SimulScan.FAILURE_PROCESSING_TIMEOUT){
              +			// This means it identified the form but could not process it
              +			// Possible reasons
              +			//    -Template is poorly defined
              +			//      maybe scanned in image for defining was not high enough resolution
              +			//    -Camera cannot focus or poorly lit
              +
              +			// This will trigger once and return focus to your application
              +		}
              +	}
              +});
              +					
              +

              Now we can loop through the processedForm object returned by the captureDocument method. Depending on how the template was defined will determine the type of information in this object. Typically the template will contain several regions that may be OCR (Text), OMR (Check-boxes), Barcode, Picture. It will only return regions that it was able to be processed.

              +
              :::javascript
              +
              +			 
              +function processSimulScanForm(SimulScanForm){
              +	var regions = SimulScanForm.regions;
              +	for(i=0; i< regions.length; ++i){
              +		switch(regions[i].processingMode){
              +		case Rho.SimulScan.PM_OCR:
              +			// The text that OCR translated into an array of lines
              +			regionTextArray = regions[i].processedData;
              +
              +			//maybe do something with returned confidence
              +			// PDXform.absoluteOcrConfidence
              +			// PDXform.relativeOcrConfidence
              +			break;
              +		case Rho.SimulScan.PM_OMR:
              +			// Checkbox region either True or False
              +			regionBooleanCheckbox = regions[i].processedData;
              +			break;
              +		case Rho.SimulScan.PM_PICTURE:
              +			// nothing in processedData
              +			// Image held temporarily until Rho.SimulScan.close()
              +			// use the id and the Rho.SimulScan.getDataUri method
              +			regionImageURI = Rho.SimulScan.getDataUri(regions[i].image.id);
              +			break;
              +		case Rho.SimulScan.PM_BARCODE:
              +			// Barcode data will be in processedData field
              +			regionBarCode = regions[i].processedData;
              +			break;
              +		}
              +	}
              +}
              +					 
              \ No newline at end of file diff --git a/docs/en/5.5/api/SimulScan.xml b/docs/en/5.5/api/SimulScan.xml new file mode 100644 index 00000000..9cf6035e --- /dev/null +++ b/docs/en/5.5/api/SimulScan.xml @@ -0,0 +1,413 @@ + + + + The SimulScan Document Capture is a software solution that enables customers to extract and process various types of information from documents. A single document may contain barcodes, text, image data and forms, using SimulScan Document Capture this data can be extracted programmatically using OCR, barcode decoding and image capture. For example, a driver's license can be thought of as a template containing regions such as name and address, signature and photo, each of these regions are processed and returned to RhoElements separately by SimulScan Document Capture so Optical Character Recognition captures the owners name and address whilst their photo is captured separately. These regions are defined by a template which maps the various regions of the document to the data they contain and can be created on-line at [The SimulScan Document Capture template builder](https://dpx-uat.motorolasolutions.com/). This API is available only on Symbol Android devices with firmware supporting SimulScan Document Capture. + + The SimulScan Document Capture is a software solution that enables customers to extract and process various types of information from documents. A single document may contain barcodes, text, image data and forms, using SimulScan Document Capture this data can be extracted programmatically using OCR, barcode decoding and image capture. For example, a driver's license can be thought of as a template containing regions such as name and address, signature and photo, each of these regions are processed and returned to the app separately by SimulScan Document Capture so Optical Character Recognition captures the owners name and address whilst their photo is captured separately. These regions are defined by a template which maps the various regions of the document to the data they contain and can be created on-line at [The SimulScan Document Capture template builder](https://dpx-uat.motorolasolutions.com/). This API is available only on Symbol Android devices with firmware supporting SimulScan Document Capture. + + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + + :::ruby + extensions: ["simulscan"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + +## Enabling the API +There are two methods of enabling the SimulScan Document Capture API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the SimulScan Document Capture API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.simulscan.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + These properties are used to configure how the SimulScan Document Capture works, for example how feedback is provided to the user + + The template XML which defines the document to be processed. This should be file URI to the template on the device. You must provide this property to define the form being captured and what is contained in each region on that form. Templates are specific to each document format you intend on capturing and can be created on-line at https://dpx-uat.motorolasolutions.com/. + Android + + + Whether or not to provide audio feedback to the user following document processing. + Android + + + If enabled, allows a session to write form capture, region images, region values, and other data to storage. + Android + + + Whether or not to provide haptic feedback to the user following document processing. + Android + + + If true, form will be captured automatically when detected. If false, user must manually tap screen or press trigger to capture the form. + Android + + + Only used if autoImageCapture is enabled. The number of correct frames that is needed to pass before SimulScan Document Capture will automatically start to process form. This should be between 5 and 30. + Android + + + Only used if autoImageCapture is enabled. Number of incorrect frames that is allowed to pass before the frame counter is reset for automatic image capture. This should be between 0 and 20. + Android + + + If true, the success event will be sent only after the SimulScan Document Capture dialog is dismissed. If false, the event will be sent immediately after the results are ready. A false value is recommended unless direct interaction with the underlying application is necessary (e.g. keystroke input). + Android + + + Whether or not to provide LED feedback to the user following document processing. + Android + + + Flash mode (off, on, disabled). + + Turn flash off. + Turn flash on. + Disable flash. + + Android + + + The length of time, in milliseconds that the processing engine has to recognize the image from the provided template. From 0 to 20000 in increments of 100. + Android + + + Defines where the document should be captured from. The only supported source is camera. + + + The document will be captured from the device camera. After calling the captureDocument method the camera preview will be presented, the user should place the document to be captured in the preview frame and press the soft button to capture & process the image. + + + + Android + + + Specify where to store downloaded templates. See [fetchTemplates()](#mfetchTemplates) + Android + + + Specifies the decode sound (beep) that is heard when a form is decoded. + Android + + + Specify which directory to search for logs in. + Android + + + Amount of time in milliseconds to wait before timing out processing. + Android + + + Version of SimulScan Document Capture engine. + Android + + + If enabled, shows a UI confirmation with results in SimulScan Document Capture View before sending results back to application. + Android + + + + + + Capture a document by either taking a photo of it and process that image for fields defined in the template. You must specify the template associated with the capture either through the template property or as part of the propertyMap when calling this method. If the document processing does not succeed the returned callback will contain failure description. If the captured document is processed successfully a callback will contain document data. + + + SimulScan Document Capture engine calls the callback on any significant event. Look at callbackType parameter. + + + Indicates whether the document was decoded successfully or not. + + + The document was decoded and processed successfully and this callback contains information about the processed form. Look at processedForm parameter. + + + An error has occurred whilst processing the document. Look at failureReason parameter. + + + The processing is over. No more notifications until next captureDocument. + + + + + Describes reason for failure. + + + SimulScan Document Capture engine generic error. + + + Identification timeout. Refer to identificationTimeout property. + + + Processing timeout. Refer to processingTimeout property. + + + + + + + The name of the template was used for recognition. + + + The number of the template was used for recognition. + + + + + The name of the template was used for recognition. + + + The image of whole scanned form. + + Width of scanned form in pixels. + + + Height of scanned form in pixels. + + + Id of scanned form image. Use getDataUri method to retrieve image data. The id is valid until close method is called. + + + + + + The name of the group this region is found in, as defined in the template associated with the recognized region. It's optional parameter. + + + + The name of the region, as defined in the template associated with the document. + + + The number of the region, as defined in the template section associated with the recognized region. + + + The type of region which has been decoded. + + + Optical Character Recognition. The region is a text field. The processedData parameter contains array of lines. + + + + Optical Mark Recognition. The region is a check box or radio box. The processedData parameter of this callback will contain a boolean value. + + + + The defined region was captured as a picture. No processedData parameter. Use the `image` callback property with the [getDataUri()](#mgetDataUri) to get a DataURI of the image. + + + The region is a barcode and the decoded barcode data is given in the processedData parameter. + + + + + The processed data contained in the specified region, this will depend on the type of region being captured. See the values of the `processingMode` parameter. + + + + The image of region. + + Width of region in pixels. + + + Height of region in pixels. + + + Id of region image. Use [getDataUri method](#mgetDataUri) to retrieve image data. Id is valid until the close method is called. + + + + Relative OCR confidence for processed data if applicable. + + + Absolute OCR confidence for processed data if applicable. + + + + + + Android + + + Fetch templates from dedicated SimulScan Document Capture server and place into template directory. See [templateDirectory property](#ptemplateDirectory). The device must have access to the network and can access the [SimulScan Document Capture Template Builder Website](http://dpx-uat.motorolasolutions.com) + + Username of the user. + Password of the user. + + Android + + + Return data URI encoding of the raw image associated with the region or captured form, this allows the operator to easily verify that the captured data is accurate and if necessary perform any post processing changes by hand. To show the image on the HTML page insert the data URI string into the src attribute of the img tag: + + :::html + <img src="dataURI string;"> + + + + Id of image to retrieve. Ids are valid until close method call. + + + Android + + + Close SimulScan Document Capture engine, and release allocated resources. When capturing images, this is especially important since they are made available temporarily. + Android + + + + + + 4.1.0 + Android + + + + +
              + Before you are able to process any documents with the SimulScan Document Capture engine, you must have template files loaded on the device. These template files must be located in an area that is open to both the SimulScan Document Capture Engine as well as your application. To retrieve the templates from the server, you would use the `fetchTemplates` method. This method will communicate with the SimulScan Document Capture back-end and download the templates to the folder that is specified by the [templateDirectory property](#ptemplateDirectory) + + + + +
              +
              +
              + + + +
              + The only requirement for capturing a document is to have the SimulScan Document Capture template file location set using the `SimulScan.template` property. This must be an absolute URI to the locale file. The location must also be in a folder that is openly available to both your application and the SimulScan Document Capture engine (i.e. it cannot be in the applications `public` folder) + + + + +
              + +
              + Now we can loop through the `processedForm` object returned by the `captureDocument` method. Depending on how the template was defined will determine the type of information in this object. Typically the template will contain several regions that may be OCR (Text), OMR (Check-boxes), Barcode, Picture. It will only return regions that it was able to be processed. + + + + +
              +
              +
              +
              +
              +
              \ No newline at end of file diff --git a/docs/en/5.5/api/Sip.md b/docs/en/5.5/api/Sip.md new file mode 100644 index 00000000..2c143fd9 --- /dev/null +++ b/docs/en/5.5/api/Sip.md @@ -0,0 +1,24 @@ +#Sip +
              +

              The SIP API controls whether the default software input panel (SIP) is displayed on the Android Device.

              +

              Enabling the API

              + +

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

              + +
              :::ruby
              +extensions: ["sip"]
              +
              + + + +

              Methods

              + +

              hide()

              Hides the default software keyboard.

              +

              Synchronous Return:

              • Void

              Method Access:

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

              show()

              Displays the default software keyboard on the device.

              +

              Synchronous Return:

              • Void

              Method Access:

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

              Remarks

              + +
              Focus on calling show method

              Focus on input field will not be reflected automatically when show method of SIP module is called.

              +
              Software keyboard behavior after hide method

              The hide method does not permanently disable the SIP, but simply hides it until the focus returns to a text input field, which causes it to reappear.

              +
              \ No newline at end of file diff --git a/docs/en/5.5/api/Sip.xml b/docs/en/5.5/api/Sip.xml new file mode 100644 index 00000000..eaf3b13c --- /dev/null +++ b/docs/en/5.5/api/Sip.xml @@ -0,0 +1,79 @@ + + + + + The SIP API controls whether the default software input panel (SIP) is displayed on the Android Device. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["sip"] + + +## Enabling the API +There are two ways to enable Enterprise Browser APIs: + +* Include all 'ebapi' modules +* Include only the API modules you need + +Both methods are explained below. + +Either way, the included files will be from: +`/Enterprise Browser/JavaScript Files/Enterprise Browser`, +a directory on the computer that contains the Enterprise Browser installation. + +### Include all JS API modules +To include all JavaScript APIs, copy the `ebapi-modules.js` file to a location accessible by your app's files and include the JavaScript modules file in your app. For instance, to include the modules file in your `index.html`, copy the file to the same directory as your index.html and add the following line to the HEAD section of your index.html file: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> This will define the EB class within the page. **Note that the path for this file is relative to the current page** (index.html). Any page on which the modules are required will need to have the required .js file(s) included in this fashion. + +### Include only the modules you need + +To include individual APIs, you must first include the `ebapi.js` in your HTML, and then the additional required API file(s). For instance, to use the SIP API, add the following code to the HTML file(s). Again, this assumes that relevant API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.sip.js"></script> + +> In the code lines above, notice that `ebapi.js` is included first, followed by `eb.sip.js`, which is the SIP API for Enterprise Browser. **This coding is required on each HTML page whenever an individual API will be called from that page**. + + + Android + + + + + Android + Displays the default software keyboard on the device. + + + Android + Hides the default software keyboard. + + + + + + + + + + + + + + + + + 1.3.0 + + + + diff --git a/docs/en/5.5/api/Tag.md b/docs/en/5.5/api/Tag.md new file mode 100644 index 00000000..b9afe719 --- /dev/null +++ b/docs/en/5.5/api/Tag.md @@ -0,0 +1,40 @@ +#Tag +
              +

              NFC Tag

              +

              This class representative NFC Tag object

              + +

              Enabling the API

              + +

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

              + +
              :::ruby
              +extensions: ["nfc"]
              +
              + +

              NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

              + + + +

              Methods

              + +

              close()

              release resources, close connection

              +

              Synchronous Return:

              • Void

              Method Access:

              • Instance Method: This method can be accessed via an instance object of this class:
                • myObject.close()

              exchangeData(STRING sendData)

              This function exchanges raw data with Tag. Tag shouldn’t be NDEF formated. Only Milfare and Ti tags are supported. When sendData is empty then method reads data from Tag and write into receiveData parameter.

              +

              Parameters

              • sendData : STRING

              Synchronous Return:

              • HASH
                • receiveData : STRING

                  NFC_SUCCESS if OK

                  +

              Method Access:

              • Instance Method: This method can be accessed via an instance object of this class:
                • myObject.exchangeData(STRING sendData)

              formatNDEF()

              format Tag to NDEF type

              +

              Synchronous Return:

              • Void

              Method Access:

              • Instance Method: This method can be accessed via an instance object of this class:
                • myObject.formatNDEF()

              getTagById(STRING id)

              This function returns Tag object

              +

              Parameters

              • id : STRING

              Synchronous Return:

              • SELF_INSTANCE

              Method Access:

              • Class Method: This method can only be accessed via the API class object.
                • JavaScript: Rho.Tag.getTagById(STRING id)
                • Ruby: Rho::Tag.getTagById(STRING id)

              makeReadOnly()

              make Tag read only

              +

              Synchronous Return:

              • Void

              Method Access:

              • Instance Method: This method can be accessed via an instance object of this class:
                • myObject.makeReadOnly()

              writeMessage(ARRAY messages)

              write messages on Tag. On the current moment only 1 message is supported.

              +

              Parameters

              • messages : ARRAY

                • Object : STRING

                  id of Rho.NFC.Message object

                  +

              Synchronous Return:

              • Void

              Method Access:

              • Instance Method: This method can be accessed via an instance object of this class:
                • myObject.writeMessage(ARRAY messages)
              + +

              Properties

              + +

              ID : STRING Read Only

              object ID

              +

              Property Access:

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

              freeSize : INTEGER Read Only

              free size in bytes

              +

              Property Access:

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

              isConnected : BOOLEAN Read Only

              connected or not(if connections between tag and nfc device exists)

              +

              Property Access:

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

              isNdef : BOOLEAN Read Only

              ndef or not

              +

              Property Access:

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

              isReadOnly : BOOLEAN Read Only

              Indicating if the tag is locked for write operation.

              +

              Property Access:

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

              serialNumber : STRING Read Only

              The serial number of a tag.

              +

              Property Access:

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

              size : INTEGER Read Only

              size in bytes

              +

              Property Access:

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

              type : STRING Read Only

              Tag type

              +

              Possible Values (false):

              Constant: Rho.Tag.TAG_TYPE_TOPAZ (For Ruby use "::" for all "." when referencing constants)
              String: 1
              Constant: Rho.Tag.TAG_TYPE_FELICA (For Ruby use "::" for all "." when referencing constants)
              String: 2
              Constant: Rho.Tag.TAG_TYPE_MIFARE_CLASSIC (For Ruby use "::" for all "." when referencing constants)
              String: 3
              Constant: Rho.Tag.TAG_TYPE_MIFARE_UL (For Ruby use "::" for all "." when referencing constants)
              String: 4
              Constant: Rho.Tag.TAG_TYPE_MIFARE_DESFIRE (For Ruby use "::" for all "." when referencing constants)
              String: 6
              Constant: Rho.Tag.TAG_TYPE_ISO15693 (For Ruby use "::" for all "." when referencing constants)
              String: 7
              Constant: Rho.Tag.TAG_TYPE_B (For Ruby use "::" for all "." when referencing constants)
              String: 8
              Constant: Rho.Tag.TAG_TYPE_MIFARE (For Ruby use "::" for all "." when referencing constants)
              String: 9
              Constant: Rho.Tag.TAG_TYPE_NXP_I_CODE (For Ruby use "::" for all "." when referencing constants)
              String: 10
              Constant: Rho.Tag.TAG_TYPE_MIFARE_PLUS (For Ruby use "::" for all "." when referencing constants)
              String: 11
              Constant: Rho.Tag.TAG_TYPE_MIFARE_ULC (For Ruby use "::" for all "." when referencing constants)
              String: 12
              Constant: Rho.Tag.TAG_TYPE_MIFARE_PLUS_S2K (For Ruby use "::" for all "." when referencing constants)
              String: 13
              Constant: Rho.Tag.TAG_TYPE_MIFARE_PLUS_X2K (For Ruby use "::" for all "." when referencing constants)
              String: 14
              Constant: Rho.Tag.TAG_TYPE_UNKNOWN (For Ruby use "::" for all "." when referencing constants)
              String: 255

              Property Access:

              • Instance: This property can be accessed via an instance object of this class:
                • myObject.type
              \ No newline at end of file diff --git a/docs/en/5.5/api/Tag.xml b/docs/en/5.5/api/Tag.xml new file mode 100644 index 00000000..00813fe8 --- /dev/null +++ b/docs/en/5.5/api/Tag.xml @@ -0,0 +1,201 @@ + + + + + NFC Tag + This class representative NFC Tag object +# Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["nfc"] + +NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + + +## Enabling the API +There are two methods of enabling the Tag API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Tag API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.tag.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + list of properties supported by class + + + object ID + WM + + + Tag type + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WM + + + The serial number of a tag. + WM + + + size in bytes + WM + + + free size in bytes + WM + + + Indicating if the tag is locked for write operation. + WM + + + ndef or not + WM + + + connected or not(if connections between tag and nfc device exists) + WM + + + + + + + + This function returns Tag object + + + + + + + + + WM + + + + make Tag read only + WM + + + + format Tag to NDEF type + WM + + + + write messages on Tag. On the current moment only 1 message is supported. + + + + + id of Rho.NFC.Message object + id of Message object + + + + WM + + + + This function exchanges raw data with Tag. Tag shouldn't be NDEF formated. Only Milfare and Ti tags are supported. When sendData is empty then method reads data from Tag and write into receiveData parameter. + + + + + + + + + + NFC_SUCCESS if OK + + + + WM + + + + release resources, close connection + WM + + + + + + + + 1.0.0 + + + + diff --git a/docs/en/5.5/api/Timer.md b/docs/en/5.5/api/Timer.md new file mode 100644 index 00000000..2890ced2 --- /dev/null +++ b/docs/en/5.5/api/Timer.md @@ -0,0 +1,48 @@ +#Timer +
              +

              The Timer API is used to create, start, stop and check the existence of timers.

              +

              Enabling the API

              + +

              This API is part of the coreapi extension that is included automatically.

              + +
              :::ruby
              +extensions: ["coreapi"]
              +
              + + + +

              Methods

              + +

              create()

              Create timer object(s).

              +

              Synchronous Return:

              • SELF_INSTANCE

              Method Access:

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

              isAlive()

              Synchronous Return:

              • BOOLEAN :

                Return alive state of a timer. If callback doesn’t return true, returns false.

                +

              Method Access:

              • Instance Method: This method can be accessed via an instance object of this class:
                • myObject.isAlive()

              start(INTEGER interval, CallBackHandler callback)

              Start timer with preset interval. Callback fired one time only.

              +

              Parameters

              • interval : INTEGER

                timer interval in ms

                +

              • callback : CallBackHandler Mandatory

              Async Callback Returning Parameters: STRING

                Synchronous Return:

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

                Method Access:

                • Instance Method: This method can be accessed via an instance object of this class:
                  • myObject.start(INTEGER interval, CallBackHandler callback)

                stop()

                Stop the timer.

                +

                Synchronous Return:

                • Void

                Method Access:

                • Instance Method: This method can be accessed via an instance object of this class:
                  • myObject.stop()
                + +

                Examples

                + +
                Examples
                +

                Implementation of the timer API.

                +
                :::javascript
                + 
                +           // Create a timer and catch callback after the specified interval:
                +           
                +            var timerCallback = function() {
                +                alert("callback called");
                +            }                                              
                +
                +            var timer = Rho.Timer.create();
                +            timer.start(5000, timerCallback);
                +            
                +            Create a timer, start and stop:
                +            var timerCallback = function() {
                +                alert("callback called");
                +            }                                              
                +
                +            var timer = Rho.Timer.create();
                +            timer.start(5000, timerCallback);
                +            setTimeout(function() {
                +                    timer.stop();
                +                },3000);
                +              
                \ No newline at end of file diff --git a/docs/en/5.5/api/Timer.xml b/docs/en/5.5/api/Timer.xml new file mode 100644 index 00000000..3feaec5e --- /dev/null +++ b/docs/en/5.5/api/Timer.xml @@ -0,0 +1,116 @@ + + + + + The Timer API is used to create, start, stop and check the existence of timers. + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + + +## Enabling the API + +There are two methods of enabling the Timer API: + +* Include all 'ebapi' modules +* Include only the API modules you need + +Both methods are explained below. + +Either way, the included files will be found in: +`/Enterprise Browser/JavaScript Files/Enterprise Browser`, +a directory on the computer that contains the Enterprise Browser installation. + +### Include all JS API modules +To include all JavaScript APIs, copy the `ebapi-modules.js` file to a location accessible by your app's files and include the JavaScript modules file in your app. For instance, to include the modules file in your `index.html`, copy the file to the same directory as your index.html and add the following line to the HEAD section of your index.html file: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> This will define the EB class within the page. **Note that the path for this file is relative to the current page** (index.html). Any page on which the modules are required will need to have the required .js file(s) included in this fashion. + +### Include only the modules you need +To include individual APIs, you must first include the `ebapi.js` in your HTML, and then the additional required API file(s). For instance, to use the Timer API, add the following code to the HTML file(s). Again, this assumes that relevant API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.timer.js"></script> + +> In the code lines above, notice that `ebapi.js` is included first, followed by `eb.timer.js`, which is the Timer API for Enterprise Browser. **This coding is required on each HTML page whenever an individual API will be called from that page**. + + + WM, CE, Android, WP8, iOS, Win32 + WM, CE, Android + + + + + Create timer object(s). + + + + + + timer interval in ms + + + + + Start timer with preset interval. Callback fired one time only. + + + + Stop the timer. + + + + + + Return alive state of a timer. If callback doesn't return true, returns false. + + + + + + + + + 5.1.0 + + + + + +
                + Implementation of the timer API. + + + // Create a timer and catch callback after the specified interval: + + var timerCallback = function() { + alert("callback called"); + } + + var timer = Rho.Timer.create(); + timer.start(5000, timerCallback); + + Create a timer, start and stop: + var timerCallback = function() { + alert("callback called"); + } + + var timer = Rho.Timer.create(); + timer.start(5000, timerCallback); + setTimeout(function() { + timer.stop(); + },3000); + + +
                +
                +
                +
                +
                +
                diff --git a/docs/en/5.5/api/addressbar.md b/docs/en/5.5/api/addressbar.md new file mode 100644 index 00000000..28ed0522 --- /dev/null +++ b/docs/en/5.5/api/addressbar.md @@ -0,0 +1,404 @@ +# AddressBar Module + + + + + + + + + + + + +
                + +

                The AddressBar Module is used to set the parameters of the address bar. The address bar should only be used for debugging Hybrid applications and is not designed to be used as a replacement for a web browser address bar. Press the 'Go' button or enter key to navigate to the typed URI.

                + +

                Enabling the API

                + In order to use this API you must include reference to the following JavaScript file that is included with the Enterprise Browser installation: + + * elements.js + + > Note - this file either needs to be on the device in a relative folder from where your HTML page is, or it must be copied to your web server appropriately. + +

                API Usage

                + This API does not use the `EB` namespace. It is simply referenced using the API name: + +
                +	:::javascript
                +addressBar.left = 0;
                +	
                +
                + +

                NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

                + +

                JavaScript Usage

                + +

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

                + + + +

                Properties

                + + +
                +

                visibility : STRING

                + +
                +
                +

                Sets the visibility to either show or hide the address bar.

                +

                +

                + + + +

                +
                +

                +
                +
                +

                Default: "hidden"

                +
                +
                +
                +

                + Visibility Access: +

                +
                  +
                • + Default Instance: This property can be accessed via the default instance object of this class: +
                    +
                  • addressBar.visibility = "visible";
                  • +
                  +
                • +
                +
                +
                +
                +
                + + +
                +

                Left : INTEGER

                + +
                +
                +

                Sets the X position of the address bar.

                +

                +

                + + + + +

                +
                +

                +
                +
                +

                Default: 0

                +
                +
                +
                +

                + Left Access: +

                +
                  +
                • + Default Instance: This property can be accessed via the default instance object of this class: +
                    +
                  • addressBar.left = 100;
                  • +
                  +
                • +
                +
                +
                +
                +
                + + +
                +

                top : INTEGER

                + +
                +
                +

                Sets the Y position of the address bar.

                +

                +

                + + + + +

                +
                +

                +
                +
                +

                Default: 0

                +
                +
                +
                +

                + Top Access: +

                +
                  +
                • + Default Instance: This property can be accessed via the default instance object of this class: +
                    +
                  • addressBar.top = 100;
                  • +
                  +
                • +
                +
                +
                +
                +
                + + +
                +

                width : INTEGER

                + +
                +
                +

                Sets the width of the address bar.

                +

                +

                + + + + +

                +
                +

                +
                +
                +

                Default: Most of the screen width

                +
                +
                +
                +

                + Width Access: +

                +
                  +
                • + Default Instance: This property can be accessed via the default instance object of this class: +
                    +
                  • addressBar.width = Rho.System.screenWidth;
                  • +
                  +
                • +
                +
                +
                +
                +
                + + + + +

                Examples

                + +
                +
                +
                + + Manipulating the Address Bar +
                +
                +
                +

                In this example, you'll see how to manipulate the addressBar using JavaScript. This example assumes that your rhoapi-modules.js file is in the same folder as the html invoking it.

                + +
                +
                +
                +								:::javascript
                +function onLoad(){
                +	visible = 0;
                +	screenWidth = EB.System.screenWidth;
                +}
                +
                +function toggleAddressBar(){
                +	if(visible){
                +		addressBar.visibility = "hidden";
                +		visible = 0;
                +	}
                +	else{
                +		addressBar.visibility = "visible";
                +		// Reset addressBar to (0, 0)
                +		addressBar.left = 0;
                +		addressBar.top = 0;
                +		visible = 1;
                +	}
                +}
                +
                +function moveAddressBar(direction, distance){
                +	switch(direction){
                +		case "left":
                +			addressBar.left = distance;
                +			break;
                +		case "top":
                +			addressBar.top = distance;
                +			break;
                +		default:
                +			alert("Invalid direction!!");
                +	}
                +}
                +
                +function addressBarWidth(percent){
                +	width = screenWidth*(percent/100);
                +	addressBar.width = width;
                +}
                +								
                +							
                +
                +
                +
                +
                +
                +
                + + + + + +

                Remarks

                + +
                +
                +
                + + Default Positions +
                +
                +
                +

                By default this control will be placed a the top of the screen. On Windows Mobile if the ‘FullScreen’ configuration setting is disabled the control will need to be moved, otherwise it will appear beneath the task bar.

                +
                +
                +
                +
                + + + +
                +
                +
                + + Switching to Other Applications +
                +
                +
                +

                All controls are designed to be shown on top of Enteprise Browser. If you require to switch to an application other than Enterprise Browser, you should minimize Enterprise Browser to ensure the buttons do not remain shown. (Not applicable to Android)

                +
                +
                +
                +
                + + + +
                +
                +
                + + Screen Orientation +
                +
                +
                +

                When the screen orientation changes, either using the ScreenOrientation API or by rotating a device with hardware support, the command areas will automatically move and resize to fit the new layout. However the buttons themselves are not moved and in some cases this may result in them being off the screen or not in the expected position. If so they must be moved manually by detecting the ScreenOrientationEvent.

                +
                +
                +
                +
                + + + +
                +
                +
                + + Named Anchors +
                +
                +
                +

                The address bar is not compatible with named anchors (page bookmarks) eg. <a name="bookmark"/></p> +

                +
                +
                +
                + + + +
                +
                +
                + + Use in Production +
                +
                +
                +

                This API is designed for debugging your application only and should not be used in production

                +
                +
                +
                +
                + + + +

                Licensing

                +
                + You can fully use all features of this API during evaluation, development or testing without obtaining a license. A message will be displayed on application startup and will also display a nag screen periodically. Before deploying an application to a production environment, you must obtain a license key. Read more about licensing. +
                +
                \ No newline at end of file diff --git a/docs/en/5.5/api/audiocapture.md b/docs/en/5.5/api/audiocapture.md new file mode 100644 index 00000000..c0b9b214 --- /dev/null +++ b/docs/en/5.5/api/audiocapture.md @@ -0,0 +1,201 @@ +#AudioCapture +
                +

                Audio capture API allows you to capture audio from the device’s built in microphone or input source.

                +

                Enabling the API

                + +

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

                + +
                :::ruby
                +extensions: ["audiocapture"]
                +
                + +

                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

                + +

                cancel()

                Cancel audio recording. During recording if ‘cancel’ method is called, the status of recording will be ‘cancel’ in the callback returning parameter of ‘start’ method. No file is saved. In android, it will delete the file if it exists.

                +

                Synchronous Return:

                • Void

                Method Access:

                • Instance Method: This method can be accessed via an instance object of this class:
                  • myObject.cancel()
                • Default Instance: This method can be accessed via the default instance object of this class.
                  • JavaScript: Rho.AudioCapture.cancel()
                  • Ruby: Rho::AudioCapture.cancel()

                getAllProperties(CallBackHandler callback)

                This method will return all of object/value pairs for the propertyNames of the API class.

                +

                Parameters

                • callback : CallBackHandler Optional

                Async Callback Returning Parameters: HASH

                  • : STRING

                Synchronous Return:

                • HASH :

                  Map of all available properties

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

                Method Access:

                • Instance Method: This method can be accessed via an instance object of this class:
                  • myObject.getAllProperties(CallBackHandler callback)
                • Default Instance: This method can be accessed via the default instance object of this class.
                  • JavaScript: Rho.AudioCapture.getAllProperties(CallBackHandler callback)
                  • Ruby: Rho::AudioCapture.getAllProperties(CallBackHandler callback)

                getDefault()

                This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

                +

                Synchronous Return:

                • SELF_INSTANCE :

                  Default object of Module.

                  +

                Method Access:

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

                getProperties(ARRAY arrayofNames, CallBackHandler callback)

                This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                +

                Parameters

                • arrayofNames : ARRAY

                  List of properties I want to know about

                  +

                  • Object : STRING

                • callback : CallBackHandler Optional

                Async Callback Returning Parameters: HASH

                  • : STRING

                Synchronous Return:

                • HASH :

                  Map of properties I want to know about

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

                Method Access:

                • Instance Method: This method can be accessed via an instance object of this class:
                  • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                • Default Instance: This method can be accessed via the default instance object of this class.
                  • JavaScript: Rho.AudioCapture.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                  • Ruby: Rho::AudioCapture.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                getProperty(STRING propertyName, CallBackHandler callback)

                This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                +

                Parameters

                • propertyName : STRING

                  The property to return info about.

                  +

                • callback : CallBackHandler Optional

                Async Callback Returning Parameters: STRING

                  Synchronous Return:

                  • STRING :

                    The property to return info about.

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

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.getProperty(STRING propertyName, CallBackHandler callback)
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.AudioCapture.getProperty(STRING propertyName, CallBackHandler callback)
                    • Ruby: Rho::AudioCapture.getProperty(STRING propertyName, CallBackHandler callback)

                  setDefault(SELF_INSTANCE: Rho::AudioCapture defaultInstance)

                  This method allows you to set the attributes of the default object instance by passing in an object of the same class.

                  +

                  Parameters

                  • defaultInstance : SELF_INSTANCE: Rho::AudioCapture

                    An instance object that is of the same class.

                    +

                  Synchronous Return:

                  • Void

                  Method Access:

                  • Class Method: This method can only be accessed via the API class object.
                    • JavaScript: Rho.AudioCapture.setDefault(SELF_INSTANCE: Rho::AudioCapture defaultInstance)
                    • Ruby: Rho::AudioCapture.setDefault(SELF_INSTANCE: Rho::AudioCapture defaultInstance)

                  setProperties(HASH propertyMap)

                  This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                  +

                  Parameters

                  • propertyMap : HASH

                    Map of properties I want to set

                    +

                    • Object : STRING

                  Synchronous Return:

                  • Void

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.setProperties(HASH propertyMap)
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.AudioCapture.setProperties(HASH propertyMap)
                    • Ruby: Rho::AudioCapture.setProperties(HASH propertyMap)

                  setProperty(STRING propertyName, STRING propertyValue)

                  This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                  +

                  Parameters

                  • propertyName : STRING

                    The one property name that I want to set

                    +

                  • propertyValue : STRING

                    The one property value that I want to set

                    +

                  Synchronous Return:

                  • Void

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.setProperty(STRING propertyName, STRING propertyValue)
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.AudioCapture.setProperty(STRING propertyName, STRING propertyValue)
                    • Ruby: Rho::AudioCapture.setProperty(STRING propertyName, STRING propertyValue)

                  start(HASH props, CallBackHandler callback)

                  Starts capturing audio until either ‘stop’ is received, or ‘maxDuration’ is reached. The successful recording will set ‘ok’ as the status. An unsuccessful recording will set ‘cancel’ or ‘error’ as the status in the callback returning parameters. If ‘cancel’ method is called during recording, ‘cancel’ status will be set in the callback returning parameters. In order to restart the audio capture, if the audio capturing is already in process, it is mandatory to call ‘stop’ or ‘cancel’ method before calling ‘start’ method again.

                  +

                  Parameters

                  • props : HASH

                    Map of Audio Capture properties to be set. For iOS 22kHz 16bit Mono WAV file will be created. In Android, ruby callbacks are taking 20secs to fire.

                    + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

                  • callback : CallBackHandler Mandatory

                  Async Callback Returning Parameters: HASH

                    • status : STRING

                      Whether or not the audio recording was successfully captured, status will be ‘ok’ or ‘cancel’ or ‘error’.

                      +

                    • message : STRING

                      If ‘status’ == ‘error’, then message contains error message. In all other cases, it will remain empty.

                      +

                    • fileName : STRING

                      If ‘status’ == ‘ok’, then contain full file path with the file name of recorded audiofile. In all other cases, it will remain empty.

                      +

                  Synchronous Return:

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

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.start(HASH props, CallBackHandler callback)
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.AudioCapture.start(HASH props, CallBackHandler callback)
                    • Ruby: Rho::AudioCapture.start(HASH props, CallBackHandler callback)

                  stop()

                  Stop audio recording. During recording if ‘stop’ method is called, the status of recording will be ‘ok’ in the callback returning parameter of ‘start’ method. The file is saved in user provided location.

                  +

                  Synchronous Return:

                  • Void

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.stop()
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.AudioCapture.stop()
                    • Ruby: Rho::AudioCapture.stop()
                  + +

                  Properties

                  + +

                  encoder : STRING

                  Encoder to compress recorded audio. In Android devices, the supported encoder type is dependent upon device hardware and vendor.

                  +

                  Possible Values (STRING):

                  Constant: Rho.AudioCapture.ENCODER_AAC (For Ruby use "::" for all "." when referencing constants)
                  String: AAC

                  AAC low complexity. This is the default value. If wrong or no value is specified this value will be accounted.

                  +
                  Constant: Rho.AudioCapture.ENCODER_AMR_NB (For Ruby use "::" for all "." when referencing constants)
                  String: AMR_NB

                  AMR narrow-band.

                  +
                  Constant: Rho.AudioCapture.ENCODER_AMR_WB (For Ruby use "::" for all "." when referencing constants)
                  String: AMR_WB

                  AMR wide-band.

                  +

                  Property Access:

                  • Instance: This property can be accessed via an instance object of this class:
                    • myObject.encoder
                  • Default Instance: This property can be accessed via the default instance object of this class.
                    • JavaScript: Rho.AudioCapture.encoder
                    • Ruby: Rho::AudioCapture.encoder

                  fileName : STRING

                  (Required) This parameter is used to specify the file name. The file name should be set at least once before calling ‘start’ method, otherwise the ‘start’ method will update the callback ‘status’ as ‘error’.

                  +

                  Property Access:

                  • Instance: This property can be accessed via an instance object of this class:
                    • myObject.fileName
                  • Default Instance: This property can be accessed via the default instance object of this class.
                    • JavaScript: Rho.AudioCapture.fileName
                    • Ruby: Rho::AudioCapture.fileName

                  maxDuration : INTEGER

                  Specifies the number of milliseconds of audio to capture, defining the size of the capture buffer. This is also the maximum number of milliseconds of audio to capture when the ‘start’ method is called if not interrupted with the ‘stop’ method. The duration cannot be set to less than 1000 milliseconds, if a value of less than 1000 milliseconds is specified, the interval will be defaulted to 20000 milliseconds. The default value is 20,000 milliseconds.

                  +

                  Default: 20000

                  Property Access:

                  • Instance: This property can be accessed via an instance object of this class:
                    • myObject.maxDuration
                  • Default Instance: This property can be accessed via the default instance object of this class.
                    • JavaScript: Rho.AudioCapture.maxDuration
                    • Ruby: Rho::AudioCapture.maxDuration
                  + +

                  Examples

                  + +
                  Starting, Stopping And Canceling Audio Capture
                  +

                  Starting, Stopping and Canceling audio capture is same across all platforms.

                  +
                  :::javascript
                  +
                  +// Starting Audio Capture without settings. Callback is mandatory. Setting the file name at least once is also mandatory before invoking 'start' method.
                  +Rho.AudioCapture.start({},mycallback);
                  +
                  +// Starting Audio Capture with settings. Callback is mandatory.
                  +// On successful recording the hash property  for fileName' in callback will return the complete file path with the filename.
                  +// In Windows, for the below settings, it will return "file://\AudioCapture.wav".
                  +Rho.AudioCapture.start({'fileName':"AudioCapture",'maxDuration':'15000'},mycallback);
                  +
                  +// Stopping Audio Capture
                  +Rho.AudioCapture.stop();
                  +
                  +// Cancelling Audio Capture
                  +Rho.AudioCapture.cancel();
                  +
                  +                                
                  :::ruby
                  +
                  +#Starting Audio Capture without settings. Callback is mandatory. Setting the file name at least once is also mandatory before invoking 'start' method.
                  +Rho::AudioCapture.start({},mycallback);
                  +
                  +#Starting Audio Capture with settings. Callback is mandatory.
                  +#On successful recording the hash property  for fileName' in callback will return the complete file path with the filename.
                  +#In Windows, for the below settings, it will return "file://\AudioCapture.wav".
                  +Rho::AudioCapture.start({'fileName'=>"AudioCapture",'maxDuration'=>'15000'},mycallback);
                  +
                  +#Stopping Audio Capture
                  +Rho::AudioCapture.stop();
                  +
                  +#Cancelling Audio Capture
                  +Rho::AudioCapture.cancel();
                  +
                  +                                
                  Setting And Getting File Name
                  +

                  In WM/WinCE, one can set the fileName with or without extensions. On retrieving, the fileName property will return the complete path with the extension name.

                  +
                  :::javascript
                  +
                  +// Setting fileName without extension
                  +Rho.AudioCapture.fileName = "\\Application\\Audio1";
                  +
                  +// The returned value is "\Application\Audio1.wav"
                  +alert(Rho.AudioCapture.fileName);
                  +
                  +// Setting fileName with extension
                  +Rho.AudioCapture.fileName = "Audio2.wav";
                  +
                  +// The returned value is "\Audio2.wav"
                  +alert(Rho.AudioCapture.fileName);
                  +
                  +                                
                  :::ruby
                  +
                  +#Setting fileName without extension
                  +Rho::AudioCapture.fileName = "\\Application\\Audio1";
                  +
                  +#The returned value is "\Application\Audio1.wav"
                  +Alert.show_popup(Rho::AudioCapture.fileName);
                  +
                  +#Setting fileName with extension
                  +Rho::AudioCapture.fileName = "Audio2.wav";
                  +
                  +#The returned value is "\Audio2.wav"
                  +Alert.show_popup(Rho::AudioCapture.fileName);
                  +
                  +                                
                  +

                  In Android, one can set the fileName with or without extensions. The extension depends on encoder. The directory should be present.

                  +
                  :::javascript
                  +
                  +// Setting fileName without extension
                  +Rho.AudioCapture.fileName = "/sdcard/Audio/sample";
                  +
                  +// The returned value is "/sdcard/Audio/sample";
                  +alert(Rho.AudioCapture.fileName);
                  +
                  +// Setting fileName with extension
                  +Rho.AudioCapture.fileName = "/sdcard/Audio/sample.mp4";
                  +
                  +// The returned value is "/sdcard/Audio/sample.mp4";
                  +alert(Rho.AudioCapture.fileName);
                  +
                  +                                
                  :::ruby
                  +
                  +#Setting fileName without extension
                  +Rho::AudioCapture.fileName = "/sdcard/Audio/sample";
                  +
                  +#The returned value is "/sdcard/Audio/sample"
                  +Alert.show_popup(Rho::AudioCapture.fileName);
                  +
                  +#Setting fileName with extension
                  +Rho::AudioCapture.fileName = "/sdcard/Audio/sample.mp4";
                  +
                  +#The returned value is "/sdcard/Audio/sample.mp4"
                  +Alert.show_popup(Rho::AudioCapture.fileName);
                  +
                  +                                
                  +

                  In iOS, one can set the fileName without extensions. The extension depends on encoder and will be automatically added. Currently supported WAV (16kHz, 16 bit, mono) IF you do not specify fullpath filename, then file will be placed to default folder. You can receive result fullpath filename in callback.

                  +
                  :::javascript
                  +
                  +#Setting fileName without extension
                  +Rho.AudioCapture.fileName = "sample";
                  +
                  +// The returned value is "sample";
                  +alert(Rho.AudioCapture.fileName);
                  +
                  +#Setting fileName with fullpath
                  +Rho.AudioCapture.fileName = Rho.Application.userFolder + 'mysound';
                  +
                  +// The returned value is (this is example for simulator) "/Users/MOHUS/Library/Application Support/iPhone Simulator/7.1/Applications/376D660D-B6C7-4E6E-8B69-38E7C681DAC5/Documents/apps/mysound";
                  +alert(Rho.AudioCapture.fileName);
                  +
                  +
                  +                                
                  :::ruby
                  +
                  +#Setting fileName without extension
                  +Rho::AudioCapture.fileName = 'sample'
                  +
                  +// The returned value is "sample"
                  +Alert.show_popup(Rho.AudioCapture.fileName)
                  +
                  +#Setting fileName with fullpath
                  +Rho::AudioCapture.fileName = File.join(Rho::Application.userFolder,'mysound')
                  +
                  +// The returned value is (this is example for simulator) "/Users/MOHUS/Library/Application Support/iPhone Simulator/7.1/Applications/376D660D-B6C7-4E6E-8B69-38E7C681DAC5/Documents/apps/mysound";
                  +Alert.show_popup(Rho.AudioCapture.fileName)
                  +
                  +
                  +                                
                  + +

                  Remarks

                  + +
                  File Name

                  In Windows, to store the file in a particular location, specify the path with the file name. Mentioning the extension name with the file name is optional. Only *.wav files are supported. If the path is not specified with the file name, the captured file is stored in the root directory of the device. In Windows and Android, if the folder is not present, it should be created manually for storing the file in that location. In Android, the file extension depends on encoder value. If it is AAC, the extension should be ‘.mp4’. In all other cases, it is of ‘.3gpp’. If only filename is specified, it will be saved in the root directory of external storage.

                  +
                  Audio Capture

                  In Windows & Android, Audio capture will not be started, if the file name is set to null. File will not be saved for invaild file name. It will return error in the callback returning parameters with the valid reason.

                  +
                  Restarting of Audio Capture

                  Audio recording will not be restarted, if the audio recording is already in process. In order to restart the audio capture, stop or cancel method need to be invoked before invoking start method.

                  +
                  Page Refresh

                  If the page is to be refreshed, the audio recording should be canceled. In Android and iOS, the state will be persisted.

                  +
                  Page Navigation

                  Upon page navigation, the audio recording should be canceled.In iOS, the state will be persisted.

                  +
                  Duration And File Name Settings

                  The default values will be applied for duration if no values are provided by the user. If values are provided then it will apply the user provided values. Later if values are not provided then it will apply the last provided values for the same. The settings for duration and file name will not be applied if the audio capture is already started and in progress. In android, there might be slight omit of recording data initially.

                  +
                  Get Property Or Get Properties

                  In Windows, ‘getProperty’ or ‘getProperties’ for fileName will return the complete path along with the extension name. For example: If file name was set to ‘\Application\AudioCapture’, then ‘getProperty’ or ‘getProperties’ will return ‘\Application\AudioCapture.wav’. If file name was set to ‘AudioCapture’, then ‘getProperty’ or ‘getProperties’ will return ‘\AudioCapture.wav’. In Android, the fileName will return whatever is set with or without extension.

                  +
                  General

                  On Quitting of the Application, Android will save the data in the file and gracefully exit. In Android, during suspend/resume or screen timeout the audio will keep on recording.

                  +
                  SDCard Access

                  Extensions which came from RhoElements (i.e. AudioCapture) that could possibly write files to external storage will require “write SD card” permissions as part of the extension’s AndroidManifest. You cannot remove the ability to write to the SD card as it would cause the extension to malfunction. Therefore, the capability has already been granted on build, and any capability added by you will be ignored. This being the case, the following extensions will always be able to write to the SD card by default.

                  +
                  \ No newline at end of file diff --git a/docs/en/5.5/api/audiocapture.xml b/docs/en/5.5/api/audiocapture.xml new file mode 100644 index 00000000..4eb16e9f --- /dev/null +++ b/docs/en/5.5/api/audiocapture.xml @@ -0,0 +1,419 @@ + + + + + Audio capture API allows you to capture audio from the device's built in microphone or input source. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["audiocapture"] + +### JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +### Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the AudioCapture API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the AudioCapture API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.audiocapture.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + 4.2.0 + WM, CE, Android, iOS + WM, CE, Android + + + + + + + + + + Audio source. + Android + + + Embedded microphone. This is the default value. + + + + + + Encoder to compress recorded audio. In Android devices, the supported encoder type is dependent upon device hardware and vendor. + Android + + + + AAC low complexity. This is the default value. If wrong or no value is specified this value will be accounted. + + + + AMR narrow-band. + + + AMR wide-band. + + + + + + Specifies the number of milliseconds of audio to capture, defining the size of the capture buffer. This is also the maximum number of milliseconds of audio to capture when the 'start' method is called if not interrupted with the 'stop' method. The duration cannot be set to less than 1000 milliseconds, if a value of less than 1000 milliseconds is specified, the interval will be defaulted to 20000 milliseconds. The default value is 20,000 milliseconds. + WM, CE, Android, iOS + WM, CE, Android + + + (Required) This parameter is used to specify the file name. The file name should be set at least once before calling 'start' method, otherwise the 'start' method will update the callback 'status' as 'error'. + WM, CE, Android, iOS + WM, CE, Android + + + + + + + + Map of Audio Capture properties to be set. For iOS 22kHz 16bit Mono WAV file will be created. In Android, ruby callbacks are taking 20secs to fire. + Map of Audio Capture properties to be set. + + + + + + Whether or not the audio recording was successfully captured, status will be 'ok' or 'cancel' or 'error'. + + + If 'status' == 'error', then message contains error message. In all other cases, it will remain empty. + + + If 'status' == 'ok', then contain full file path with the file name of recorded audiofile. In all other cases, it will remain empty. + + + + Starts capturing audio until either 'stop' is received, or 'maxDuration' is reached. The successful recording will set 'ok' as the status. An unsuccessful recording will set 'cancel' or 'error' as the status in the callback returning parameters. If 'cancel' method is called during recording, 'cancel' status will be set in the callback returning parameters. In order to restart the audio capture, if the audio capturing is already in process, it is mandatory to call 'stop' or 'cancel' method before calling 'start' method again. + WM, CE, Android, iOS + WM, CE, Android + + + Stop audio recording. During recording if 'stop' method is called, the status of recording will be 'ok' in the callback returning parameter of 'start' method. The file is saved in user provided location. + WM, CE, Android, iOS + WM, CE, Android + + + Cancel audio recording. During recording if 'cancel' method is called, the status of recording will be 'cancel' in the callback returning parameter of 'start' method. No file is saved. In android, it will delete the file if it exists. + WM, CE, Android, iOS + WM, CE, Android + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Extensions which came from RhoElements (i.e. AudioCapture) that could possibly write files to external storage will require "write SD card" permissions as part of the extension's AndroidManifest. You cannot remove the ability to write to the SD card as it would cause the extension to malfunction. Therefore, the capability has already been granted on build, and any capability added by you will be ignored. This being the case, the following extensions will always be able to write to the SD card by default. + + + + + Extensions that could possibly write files to external storage (i.e. AudioCapture) will require "write SD card" permissions as part of the extension's AndroidManifest. You cannot remove the ability to write to the SD card as it would cause the extension to malfunction. Therefore, the capability has already been granted on build, and any capability added by you will be ignored. This being the case, the following extensions will always be able to write to the SD card by default. + + + + + + +
                  + Starting, Stopping and Canceling audio capture is same across all platforms. + + "AudioCapture",'maxDuration'=>'15000'},mycallback); + +#Stopping Audio Capture +Rho::AudioCapture.stop(); + +#Cancelling Audio Capture +Rho::AudioCapture.cancel(); +]]> + + + + +
                  +
                  +
                  + + +
                  + In WM/WinCE, one can set the fileName with or without extensions. On retrieving, the fileName property will return the complete path with the extension name. + + + + + + +
                  +
                  + In Android, one can set the fileName with or without extensions. The extension depends on encoder. The directory should be present. + + + + + + +
                  +
                  + In iOS, one can set the fileName without extensions. The extension depends on encoder and will be automatically added. Currently supported WAV (16kHz, 16 bit, mono) IF you do not specify fullpath filename, then file will be placed to default folder. You can receive result fullpath filename in callback. + + + + + + +
                  +
                  +
                  +
                  + + + +
                  + This example will show how to capture audio from your device to a file and then play that audio file. Note that this example assumes that your ebapi-modules.js file is located in the same folder as the HTML that is evoking it. + + + + + + Audio Capture API Example + + + + +

                  AudioCapture API Example

                  +
                  +
                  +
                  + + + + ]]> +
                  +
                  +
                  +
                  +
                  +
                  +
                  +
                  diff --git a/docs/en/5.5/api/barcode.md b/docs/en/5.5/api/barcode.md new file mode 100644 index 00000000..a2c3ff27 --- /dev/null +++ b/docs/en/5.5/api/barcode.md @@ -0,0 +1,681 @@ +#Barcode +
                  Properties 216
                  +

                  The Barcode Module provides access to control the functionality of the device’s scanner. Because RhoMobile Suite is designed to run on both Consumer devices and Symbol Technologies' enterprise devices support for the Barcode API will vary for each method and properties depending on which platform you are running on. Please note that a lot these APIs are optimized for the extended functionality that Symbol Technologies devices provide. Check the platform indicators in each property or method section. In general if you are developing for a consumer device the number of symbologies available to you will be limited to just the most common ones, eg EAN13, UPCA etc and your scanning will be via the device camera. If your application is running on Symbol Technologies' hardware you will have much finer control over a more fully featured Scanner, often with a choice of scanner hardware on the device. In general if you wish to capture a single barcode in a ‘one shot’ use case, eg your App just wants to capture a single barcode to be submitted to a price comparison website then use Barcode.take(callback); if your application is expecting a number of barcodes to be received, common in enterprise scenarios for example a user in a warehouse then use Barcode.enable(callback). The Barcode API will not run on non-Symbol Technologies Windows Mobile / CE devices.Only the foreground application is given access to the scanning hardware, when an application is sent to the background its state will be saved and it will automatically relinquish control of the scanner. When brought back to the foreground, an application previously using the barcode API will have its previous configuration reapplied automatically.In VC70 scanner will work only if connected in SSI Mode. In Symbol android devices, it is recommended to use EMDK for KitKat devices and not to use EMDK in JellyBean devices.

                  +

                  Enabling the API

                  + +

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

                  + +
                  :::ruby
                  +extensions: ["barcode"]
                  +
                  + +

                  The barcode extension is also included automatically if you specify the following in your build.yml

                  + +
                  :::ruby
                  +app_type: "rhoelements"
                  +
                  + +

                  NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

                  + +

                  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

                  + +

                  barcode_recognize(STRING imageFilePath)

                  Deprecated

                  Recognizes a barcode on an image. Returns a string with recognized code, or empty string if the barcode is not recognized.

                  +

                  Parameters

                  • imageFilePath : STRING

                    Path to the image that contains the barcode to be recognized.

                    +

                  Synchronous Return:

                  • STRING :

                    String with recognized code, or empty string if the barcode is not recognized.

                    +

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.barcode_recognize(STRING imageFilePath)
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.Barcode.barcode_recognize(STRING imageFilePath)
                    • Ruby: Rho::Barcode.barcode_recognize(STRING imageFilePath)

                  commandRemoteScanner(STRING command)

                  Instruct the connected RS507 scanner to perform some action.

                  +

                  (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                  Parameters

                  • command : STRING

                    The action the RS507 scanner should perform, can be ‘Disconnect’ which disconnects the bluetooth RS507; ‘unpair’ which unpairs the RS507 from the device for association with another device; ‘StartPaging’ or ‘StopPaging’ which will cause the RS507 scanner to start or stop emitting a beep, to allow it to be located.

                    +

                  Synchronous Return:

                  • Void

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.commandRemoteScanner(STRING command)
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.Barcode.commandRemoteScanner(STRING command)
                    • Ruby: Rho::Barcode.commandRemoteScanner(STRING command)

                  disable()

                  Disables the barcode scanner. This reverts the scanner to its default state and flushes any current decoder settings.

                  +

                  (Symbol Technologies' scanners)

                  Synchronous Return:

                  • Void

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.disable()
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.Barcode.disable()
                    • Ruby: Rho::Barcode.disable()

                  enable(HASH propertyMap, CallBackHandler callback)

                  Enabling the scanner puts it in a state where it will respond to the trigger (on devices with a hardware trigger) or will accept a command to initiate a soft scan (start method). Scanned barcodes will be available to the application through the callback provided to this method. Only one scanner on the device can be enabled at any one time, to switch between the imager and camera scanners (for example) then first disable the currently enabled scanner. If you do not specify a callback to this method you will received the scanned data as keystrokes. Note that it is necessary to enable the scanner on WM/CE devices prior to being able to retrieve the state of properties.

                  + + +NOTE:

                  This method replaces Barcode.enable from RhoElements 2.2 and takes a different prototype, no longer taking a ‘deviceName’ parameter this method can now be called on the individual scanner instances returned by Barcode.enumerate to control which hardware scanner on the device is enabled. Please consider using Barcode.take if you only require a ‘single shot’ scan and Barcode.enable if your user will be using the trigger to return scan events.

                  + + +

                  (Symbol Technologies' Scanners which support a hardware or software trigger to invoke the scan.)

                  Parameters

                  • propertyMap : HASH Optional

                    Provide a set of properties to configure the scanner, for example enable specific symbologies or check digits.

                    + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

                    Not providing properties to this function will use the scanner’s default properties, or those previously set on the Scanner instance.

                    +

                  • callback : CallBackHandler Optional

                  Async Callback Returning Parameters: HASH

                    • data : STRING

                      The data decoded by the scanner or imaging device.

                      +

                    • source : STRING

                      The source device and human readable decoder type of the decoded barcode or symbol.

                      +

                    • type : STRING

                      Hex value representing the decoder type.

                      +

                    • time : STRING

                      The time at which the decode occurred (hh:mm:ss)

                      +

                    • length : STRING

                      The length of the decoded barcode or symbol.

                      +

                    • direction : STRING

                      The direction the barcode was scanned, either forward, reverse or unavailable.

                      +

                  Synchronous Return:

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

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.enable(HASH propertyMap, CallBackHandler callback)
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.Barcode.enable(HASH propertyMap, CallBackHandler callback)
                    • Ruby: Rho::Barcode.enable(HASH propertyMap, CallBackHandler callback)

                  getAllProperties(CallBackHandler callback)

                  This method will return all of object/value pairs for the propertyNames of the API class.

                  +

                  Parameters

                  • callback : CallBackHandler Optional

                  Async Callback Returning Parameters: HASH

                    • : STRING

                  Synchronous Return:

                  • HASH :

                    Map of all available properties

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

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.getAllProperties(CallBackHandler callback)
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.Barcode.getAllProperties(CallBackHandler callback)
                    • Ruby: Rho::Barcode.getAllProperties(CallBackHandler callback)

                  getDefault()

                  This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

                  +

                  Synchronous Return:

                  • SELF_INSTANCE :

                    Default object of Module.

                    +

                  Method Access:

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

                  getProperties(ARRAY arrayofNames, CallBackHandler callback)

                  This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                  +

                  Parameters

                  • arrayofNames : ARRAY

                    List of properties I want to know about

                    +

                    • Object : STRING

                  • callback : CallBackHandler Optional

                  Async Callback Returning Parameters: HASH

                    • : STRING

                  Synchronous Return:

                  • HASH :

                    Map of properties I want to know about

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

                  Method Access:

                  • Instance Method: This method can be accessed via an instance object of this class:
                    • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                  • Default Instance: This method can be accessed via the default instance object of this class.
                    • JavaScript: Rho.Barcode.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                    • Ruby: Rho::Barcode.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                  getProperty(STRING propertyName, CallBackHandler callback)

                  This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                  +

                  Parameters

                  • propertyName : STRING

                    The property to return info about.

                    +

                  • callback : CallBackHandler Optional

                  Async Callback Returning Parameters: STRING

                    Synchronous Return:

                    • STRING :

                      The property to return info about.

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

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.getProperty(STRING propertyName, CallBackHandler callback)
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.getProperty(STRING propertyName, CallBackHandler callback)
                      • Ruby: Rho::Barcode.getProperty(STRING propertyName, CallBackHandler callback)

                    getSupportedProperties(CallBackHandler callback)

                    Return array of properties supported by this scanner.

                    +

                    (Symbol Technologies' scanners)

                    Parameters

                    • callback : CallBackHandler Optional

                    Async Callback Returning Parameters: ARRAY

                      • Object : STRING

                    Synchronous Return:

                    • ARRAY :

                      Array of property names supported by this scanner.

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

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.getSupportedProperties(CallBackHandler callback)
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.getSupportedProperties(CallBackHandler callback)
                      • Ruby: Rho::Barcode.getSupportedProperties(CallBackHandler callback)

                    registerBluetoothStatus(CallBackHandler callback)

                    If you are using an RS507 barcode scanner you can register to receive connected or disconnected events through this method.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Parameters

                    • callback : CallBackHandler Mandatory

                    Async Callback Returning Parameters: HASH

                      • status : STRING

                        The message describing the bluetooth connection: BluetoothConnected, BluetoothDisconnected or BTScanAssociationBarcode. See below for further descriptions.

                        +

                    Synchronous Return:

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

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.registerBluetoothStatus(CallBackHandler callback)
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.registerBluetoothStatus(CallBackHandler callback)
                      • Ruby: Rho::Barcode.registerBluetoothStatus(CallBackHandler callback)

                    setDefault(SELF_INSTANCE: Rho::Barcode defaultInstance)

                    This method allows you to set the attributes of the default object instance by passing in an object of the same class.

                    +

                    Parameters

                    • defaultInstance : SELF_INSTANCE: Rho::Barcode

                      An instance object that is of the same class.

                      +

                    Synchronous Return:

                    • Void

                    Method Access:

                    • Class Method: This method can only be accessed via the API class object.
                      • JavaScript: Rho.Barcode.setDefault(SELF_INSTANCE: Rho::Barcode defaultInstance)
                      • Ruby: Rho::Barcode.setDefault(SELF_INSTANCE: Rho::Barcode defaultInstance)

                    setProperties(HASH propertyMap)

                    This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                    +

                    Parameters

                    • propertyMap : HASH

                      Map of properties I want to set

                      +

                      • Object : STRING

                    Synchronous Return:

                    • Void

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.setProperties(HASH propertyMap)
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.setProperties(HASH propertyMap)
                      • Ruby: Rho::Barcode.setProperties(HASH propertyMap)

                    setProperty(STRING propertyName, STRING propertyValue)

                    This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                    +

                    Parameters

                    • propertyName : STRING

                      The one property name that I want to set

                      +

                    • propertyValue : STRING

                      The one property value that I want to set

                      +

                    Synchronous Return:

                    • Void

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.setProperty(STRING propertyName, STRING propertyValue)
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.setProperty(STRING propertyName, STRING propertyValue)
                      • Ruby: Rho::Barcode.setProperty(STRING propertyName, STRING propertyValue)

                    start()

                    Performs a soft trigger start, initiating a scan without pressing the hardware trigger. If the scan does not result in a decode it is necessary to perform a soft stop before another soft start.

                    +

                    (Symbol Technologies' scanners)

                    Synchronous Return:

                    • Void

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.start()
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.start()
                      • Ruby: Rho::Barcode.start()

                    stop()

                    Performs a soft trigger stop.

                    +

                    (Symbol Technologies' scanners)

                    Synchronous Return:

                    • Void

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.stop()
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.stop()
                      • Ruby: Rho::Barcode.stop()

                    take(HASH propertyMap, CallBackHandler callback)

                    Enable the scanner and start capturing the barcode automatically. On Symbol Technologies' devices the amount of time to scan the barcode is defined by the scanTimeout property. On iPhone and Android if a barcode is found, the user can confirm barcode recognition, or continue to try to recognize the barcode. When the user confirms or cancels, the callback is called. Once the callback has been called the barcode hardware is disabled.This method will work only on scanners which support soft scan.

                    +

                    Parameters

                    • propertyMap : HASH Optional

                      Provide a set of properties to configure the scanner, for example enable specific symbologies or check digits.

                      + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

                      Not providing properties to this function will use the scanner’s default properties, or those previously set on the Scanner instance.

                      +

                    • callback : CallBackHandler Mandatory

                    Async Callback Returning Parameters: HASH

                      • barcode : STRING

                        The data decoded by the scanner or imaging device.

                        +

                      • status : STRING

                        Whether or not the barcode was successfully scanned, status will be ‘ok’ or ‘cancel’

                        +

                    Synchronous Return:

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

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.take(HASH propertyMap, CallBackHandler callback)
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.take(HASH propertyMap, CallBackHandler callback)
                      • Ruby: Rho::Barcode.take(HASH propertyMap, CallBackHandler callback)

                    take_barcode(STRING rubyCallbackURL, HASH propertyMap)

                    Deprecated

                    Deprecated old method for Barcode.take().

                    +

                    Parameters

                    • rubyCallbackURL : STRING

                      Ruby callback URL.

                      +

                    • propertyMap : HASH Optional

                      Provide a set of properties to configure the scanner, for example enable specific symbologies or check digits.

                      + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

                      Not providing properties to this function will use the scanner’s default properties, or those previously set on the Scanner instance.

                      +

                    Synchronous Return:

                    • Void

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.take_barcode(STRING rubyCallbackURL, HASH propertyMap)
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.take_barcode(STRING rubyCallbackURL, HASH propertyMap)
                      • Ruby: Rho::Barcode.take_barcode(STRING rubyCallbackURL, HASH propertyMap)
                    + +

                    Properties

                    + +

                    adaptiveScanning : BOOLEAN 1.0.0

                    Enables or disables adaptive scanning. When set to true, the scan engine will automatically toggle between 2 scan angles, wide and narrow, allowing the scan engine to decode barcodes both in close proximity and far away (~100 inches). Adaptive scanning is only supported in high performance, long working range scan engines such as SE960.

                    +

                    (Laser Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.adaptiveScanning
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.adaptiveScanning
                      • Ruby: Rho::Barcode.adaptiveScanning

                    aimMode : STRING 1.0.0

                    Defines the aiming mode to use.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.AIMMODE_NONE (For Ruby use "::" for all "." when referencing constants)
                    String: none

                    No Aiming (Can be overridden by picklistMode).

                    +
                    Constant: Rho.Barcode.AIMMODE_DOT (For Ruby use "::" for all "." when referencing constants)
                    String: dot

                    Laser barcode readers will show a dot for aiming.

                    +
                    Constant: Rho.Barcode.AIMMODE_SLAB (For Ruby use "::" for all "." when referencing constants)
                    String: slab

                    Laser barcode readers will show a slab for aiming.

                    +
                    Constant: Rho.Barcode.AIMMODE_RETICLE (For Ruby use "::" for all "." when referencing constants)
                    String: reticle

                    Imager barcode readers will show a reticle for aiming.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.aimMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.aimMode
                      • Ruby: Rho::Barcode.aimMode

                    aimType : STRING 1.0.0

                    Describes the type of aiming to use.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.AIMTYPE_TRIGGER (For Ruby use "::" for all "." when referencing constants)
                    String: trigger

                    Standard trigger mode. Holding the trigger will start a decoding session.

                    +
                    Constant: Rho.Barcode.AIMTYPE_TIMED_HOLD (For Ruby use "::" for all "." when referencing constants)
                    String: timedHold

                    Aiming lasts for the time specified by ‘timedAimDuration’ before decoding. The opportunity to scan will last until the barcode is decoded or scanTimeout occurs.

                    +
                    Constant: Rho.Barcode.AIMTYPE_TIMED_RELEASE (For Ruby use "::" for all "." when referencing constants)
                    String: timedRelease

                    Aiming lasts until trigger is released. If the timedAimDuration has expired when the trigger is released then a decode session is started until a barcode is decoded or for the remaining time equal to the scanTimeout value.

                    +
                    Constant: Rho.Barcode.AIMTYPE_PRESENTATION (For Ruby use "::" for all "." when referencing constants)
                    String: presentation

                    Provided to support Kiosk devices. The scanner illuminates when movement is detected in the range of the scanner window. In order to use this mode the scanner must be initiated with a softscan using the Rho.Barcode.start() method and again after each decode. The device must be equipped with a sensor to detect movement to use presentation mode. MK31XX devices come with presentation mode pre-enabled in the scanner driver and the aimType cannot be modified for these devices.

                    +
                    Constant: Rho.Barcode.AIMTYPE_PRESS_AND_RELEASE (For Ruby use "::" for all "." when referencing constants)
                    String: pressAndRelease

                    Scan will continue after the trigger is released until scanTimeout occurs.

                    +
                    Constant: Rho.Barcode.AIMTYPE_CONTINUOUS_READ (For Ruby use "::" for all "." when referencing constants)
                    String: continuousRead

                    Once the trigger is pulled barcodes will continue to be scanned as long as the trigger is held, enabling rapid scanning, to be used in conjunction with sameSymbolTimeout and differentSymbolTimeout. This value is ignored if viewfinderMode is set to ‘dynamicReticle’

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.aimType
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.aimType
                      • Ruby: Rho::Barcode.aimType

                    allDecoders : BOOLEAN 1.0.0

                    When set to true, the barcode scanner will read all barcode types that the scanner is capable of reading. When set to false, the barcode scanner will not be able to decode any symbologies, this is most useful if you want to set the scanner to a default state before only enabling your required symbologies. The fewer symbologies that are enabled the faster the decoding performance of the scanning engine will be. This property will return true only if all supported symbologies by the scanner are enabled, if only a subset of supported symbologies are enabled then false will be returned. Note that some decoders will not be enabled as some symbologies use the same systems to encode data, making it impossible to differentiate between them. For example: “canpostal” and “auspostal” both use a 4-state system, so devices will only enable either “canpostal” OR “auspostal” when “alldecoders” is enabled. Note that other symbologies also share the 4-state system.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.allDecoders
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.allDecoders
                      • Ruby: Rho::Barcode.allDecoders

                    ausPostal : BOOLEAN 1.0.0

                    Enables or disables the symbology for Australian Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.ausPostal
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.ausPostal
                      • Ruby: Rho::Barcode.ausPostal

                    autoEnter : BOOLEAN 1.0.0

                    When true, automatically appends the character code for ‘enter’ to the end of any barcodes scanned. This is useful if you want to submit forms following a scan without further interaction. This property will only take effect if you have not specified a callback to the enable method. AutoEnter and AutoTab are mutually exclusive properties.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.autoEnter
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.autoEnter
                      • Ruby: Rho::Barcode.autoEnter

                    autoTab : BOOLEAN 1.0.0

                    When true, automatically appends the tab character to the end of any barcodes scanned. This is useful if you are populating a form and want to jump to the next field in the form without further interaction. This property will only take effect if you have not specified a callback to the enable method. AutoTab and AutoEnter are mutually exclusive properties.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.autoTab
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.autoTab
                      • Ruby: Rho::Barcode.autoTab

                    aztec : BOOLEAN 1.0.0

                    Enables or disables the symbology for Aztec barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.aztec
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.aztec
                      • Ruby: Rho::Barcode.aztec

                    barcodeDataFormat : STRING 2.1.0

                    Specifies the format in which the barcode data is returned, binary data is returned in Data URI format with the appropriate mime type. This parameter is designed to be used primarily with image based symbologies (eg. Signature). Binary data will not be output as keystrokes, you must set a decode callback in order to receive scanned data.

                    +

                    (Camera / Imager Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.FORMAT_BINARY (For Ruby use "::" for all "." when referencing constants)
                    String: binary

                    Scanned data will be returned in Data URI format.

                    +
                    Constant: Rho.Barcode.FORMAT_TEXT (For Ruby use "::" for all "." when referencing constants)
                    String: text

                    Scanned data will be returned in Text format.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.barcodeDataFormat
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.barcodeDataFormat
                      • Ruby: Rho::Barcode.barcodeDataFormat

                    beamWidth : STRING 2.1.0

                    Specifies the width of the laser beam. All devices will support normal beam widths but other widths may not be supported on your device.

                    +

                    (Laser Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.BEAM_NORMAL (For Ruby use "::" for all "." when referencing constants)
                    String: normal

                    Laser beam width is normal.

                    +
                    Constant: Rho.Barcode.BEAM_WIDE (For Ruby use "::" for all "." when referencing constants)
                    String: wide

                    Laser beam width is wide.

                    +
                    Constant: Rho.Barcode.BEAM_NARROW (For Ruby use "::" for all "." when referencing constants)
                    String: narrow

                    Laser beam width is narrow.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.beamWidth
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.beamWidth
                      • Ruby: Rho::Barcode.beamWidth

                    bidirectionalRedundancy : BOOLEAN 1.0.0

                    Enables or disables bidirectional redundancy.

                    +

                    (Laser Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.bidirectionalRedundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.bidirectionalRedundancy
                      • Ruby: Rho::Barcode.bidirectionalRedundancy

                    canPostal : BOOLEAN 1.0.0

                    Enables or disables the symbology for Canadian Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.canPostal
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.canPostal
                      • Ruby: Rho::Barcode.canPostal

                    chinese2of5 : BOOLEAN 1.0.0

                    Enables or disables the symbology for Chinese 2of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.chinese2of5
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.chinese2of5
                      • Ruby: Rho::Barcode.chinese2of5

                    codabar : BOOLEAN 1.0.0

                    Enables or disables the symbology for Codabar barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.codabar
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.codabar
                      • Ruby: Rho::Barcode.codabar

                    codabarClsiEditing : BOOLEAN 1.0.0

                    Enables Codabar CLSi formatting when set to true.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.codabarClsiEditing
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.codabarClsiEditing
                      • Ruby: Rho::Barcode.codabarClsiEditing

                    codabarMaxLength : INTEGER 1.0.0

                    Specifies the maximum number of allowable characters in a Codabar barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.codabarMaxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.codabarMaxLength
                      • Ruby: Rho::Barcode.codabarMaxLength

                    codabarMinLength : INTEGER 1.0.0

                    Specifies the minimum number of allowable characters in a Codabar barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.codabarMinLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.codabarMinLength
                      • Ruby: Rho::Barcode.codabarMinLength

                    codabarNotisEditing : BOOLEAN 1.0.0

                    Enables Codabar NotisEditing formatting when set to true.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.codabarNotisEditing
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.codabarNotisEditing
                      • Ruby: Rho::Barcode.codabarNotisEditing

                    codabarRedundancy : BOOLEAN 1.0.0

                    Sets the Codabar Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.codabarRedundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.codabarRedundancy
                      • Ruby: Rho::Barcode.codabarRedundancy

                    code11 : BOOLEAN 1.0.0

                    Enables or disables the symbology for Code11 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code11
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code11
                      • Ruby: Rho::Barcode.code11

                    code11checkDigitCount : STRING 1.0.0

                    Specifies whether to verify 0, 1 or 2 check digits.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.CODE11_CHECKDIGIT_NONE (For Ruby use "::" for all "." when referencing constants)
                    String: none

                    Scanning engine will verify no Code 11 check digits.

                    +
                    Constant: Rho.Barcode.CODE11_CHECKDIGIT_ONE (For Ruby use "::" for all "." when referencing constants)
                    String: one

                    Scanning engine will verify one Code 11 check digit.

                    +
                    Constant: Rho.Barcode.CODE11_CHECKDIGIT_TWO (For Ruby use "::" for all "." when referencing constants)
                    String: two

                    Scanning engine will verify two Code 11 check digits.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code11checkDigitCount
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code11checkDigitCount
                      • Ruby: Rho::Barcode.code11checkDigitCount

                    code11maxLength : INTEGER 1.0.0

                    Specifies the maximum number of allowable characters in a Code 11 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code11maxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code11maxLength
                      • Ruby: Rho::Barcode.code11maxLength

                    code11minLength : INTEGER 1.0.0

                    Specifies the minimum number of allowable characters in a Code 11 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code11minLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code11minLength
                      • Ruby: Rho::Barcode.code11minLength

                    code11redundancy : BOOLEAN 1.0.0

                    Sets the Code 11 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code11redundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code11redundancy
                      • Ruby: Rho::Barcode.code11redundancy

                    code11reportCheckDigit : BOOLEAN 1.0.0

                    When true, the barcode check digit(s) will be reported for scanned Code 11 barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code11reportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code11reportCheckDigit
                      • Ruby: Rho::Barcode.code11reportCheckDigit

                    code128 : BOOLEAN 1.0.0

                    Enables or disables the symbology for Code128 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128
                      • Ruby: Rho::Barcode.code128

                    code128checkIsBtTable : BOOLEAN 2.0.0

                    When true, decodes concatenated Code128 output only if the pair belongs to one of the commonly concatenated pairs as defined by the standard.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128checkIsBtTable
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128checkIsBtTable
                      • Ruby: Rho::Barcode.code128checkIsBtTable

                    code128ean128 : BOOLEAN 1.0.0

                    When true, barcodes with the EAN128 subtype property set will be read.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128ean128
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128ean128
                      • Ruby: Rho::Barcode.code128ean128

                    code128isbt128 : BOOLEAN 2.0.0

                    When true, barcodes with the isbt128 subtype property set will be read.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128isbt128
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128isbt128
                      • Ruby: Rho::Barcode.code128isbt128

                    code128isbt128ConcatMode : STRING 1.0.0

                    Sets the Code128 ISBT concatenation mode property. This feature allows a pair of barcodes which meet certain criteria defined in the ISBT128 spec to be reported as a single barcode. This parameter describes the different concatenation modes available for ISBT128.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.CODE128ISBT_NEVER (For Ruby use "::" for all "." when referencing constants)
                    String: never

                    Will ignore the barcode pair and only output decode data for one of the barcodes.

                    +
                    Constant: Rho.Barcode.CODE128ISBT_ALWAYS (For Ruby use "::" for all "." when referencing constants)
                    String: always

                    Will not decode if both barcodes are not present or if one of them can not be decoded.

                    +
                    Constant: Rho.Barcode.CODE128ISBT_AUTO (For Ruby use "::" for all "." when referencing constants)
                    String: auto

                    Auto-Discriminate.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128isbt128ConcatMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128isbt128ConcatMode
                      • Ruby: Rho::Barcode.code128isbt128ConcatMode

                    code128maxLength : INTEGER 1.0.0

                    Specifies the maximum number of allowable characters in a Code 128 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128maxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128maxLength
                      • Ruby: Rho::Barcode.code128maxLength

                    code128minLength : INTEGER 1.0.0

                    Specifies the minimum number of allowable characters in a Code 128 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128minLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128minLength
                      • Ruby: Rho::Barcode.code128minLength

                    code128other128 : BOOLEAN 1.0.0

                    Sets the other 128 property which enables the non EAN and non ISBT 128 subtype.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128other128
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128other128
                      • Ruby: Rho::Barcode.code128other128

                    code128redundancy : BOOLEAN 1.0.0

                    Sets the Code 128 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128redundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128redundancy
                      • Ruby: Rho::Barcode.code128redundancy

                    code128securityLevel : INTEGER 1.0.0

                    Sets the Code 128 security level and accepts a value between 0 and 3 inclusive. 0: Allows the scanner to operate in its most aggressive state, while providing sufficient security in decoding most ‘in-spec’ barcodes. 1: Eliminates most mis-decodes. 2: Select this option if security level 1 fails to eliminate mis-decodes. 3: Select this option if security level 1 and 2 fail to eliminate mis-decodes. Be advised that selecting level 3 is an extreme measure against mis-decoding and will significantly impair the decoding ability of the scanner.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code128securityLevel
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code128securityLevel
                      • Ruby: Rho::Barcode.code128securityLevel

                    code39 : BOOLEAN 1.0.0

                    Enables or disables the symbology for Code 39 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39
                      • Ruby: Rho::Barcode.code39

                    code39code32Prefix : BOOLEAN 1.0.0

                    Enables reporting of the Code32 prefix when a Code39 barcode is converted.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39code32Prefix
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39code32Prefix
                      • Ruby: Rho::Barcode.code39code32Prefix

                    code39convertToCode32 : BOOLEAN 1.0.0

                    Enables conversion from Code39 to Code 32 barcodes, when set the decoded barcode is converted to Code 32.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39convertToCode32
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39convertToCode32
                      • Ruby: Rho::Barcode.code39convertToCode32

                    code39fullAscii : BOOLEAN 1.0.0

                    Enables full ASCII conversion of Code 39 barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39fullAscii
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39fullAscii
                      • Ruby: Rho::Barcode.code39fullAscii

                    code39maxLength : INTEGER 1.0.0

                    Specifies the maximum number of allowable characters in a Code 39 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39maxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39maxLength
                      • Ruby: Rho::Barcode.code39maxLength

                    code39minLength : INTEGER 1.0.0

                    Specifies the minimum number of allowable characters in a Code 39 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39minLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39minLength
                      • Ruby: Rho::Barcode.code39minLength

                    code39redundancy : BOOLEAN 1.0.0

                    Sets the Code 39 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39redundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39redundancy
                      • Ruby: Rho::Barcode.code39redundancy

                    code39reportCheckDigit : BOOLEAN 1.0.0

                    Enables reporting of the Code 39 check digit when a Code 39 barcode is scanned.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39reportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39reportCheckDigit
                      • Ruby: Rho::Barcode.code39reportCheckDigit

                    code39securityLevel : INTEGER 1.0.0

                    Sets the Code 128 security level and accepts a value between 0 and 3 inclusive. 0: This setting allows the scanner to operate in its most aggressive state, while providing sufficient security in decoding most ‘in-spec’ barcodes. 1: This setting eliminates most mis-decodes. 2: Select this option if security level 1 fails to eliminate mis-decodes. 3: Select this option if security level 1 and 2 fail to eliminate mis-decodes. Be advised that selecting level 3 is an extreme measure against mis-decoding and will significantly impair the decoding ability of the scanner.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39securityLevel
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39securityLevel
                      • Ruby: Rho::Barcode.code39securityLevel

                    code39verifyCheckDigit : BOOLEAN 1.0.0

                    Turns on verification of the Code 39 check digit.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code39verifyCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code39verifyCheckDigit
                      • Ruby: Rho::Barcode.code39verifyCheckDigit

                    code93 : BOOLEAN 1.0.0

                    Enables or disables the symbology for Code 93 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code93
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code93
                      • Ruby: Rho::Barcode.code93

                    code93maxLength : INTEGER 1.0.0

                    Specifies the maximum number of allowable characters in a Code 93 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code93maxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code93maxLength
                      • Ruby: Rho::Barcode.code93maxLength

                    code93minLength : INTEGER 1.0.0

                    Specifies the minimum number of allowable characters in a Code 93 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code93minLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code93minLength
                      • Ruby: Rho::Barcode.code93minLength

                    code93redundancy : BOOLEAN 1.0.0

                    Sets the Code 93 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.code93redundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.code93redundancy
                      • Ruby: Rho::Barcode.code93redundancy

                    compositeAb : BOOLEAN 1.0.0

                    Enables or disables the symbology for Composite AB barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.compositeAb
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.compositeAb
                      • Ruby: Rho::Barcode.compositeAb

                    compositeAbUccLinkMode : STRING 2.0.0

                    Describes whether UCC link mode is enabled.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.UCC_NEVER (For Ruby use "::" for all "." when referencing constants)
                    String: never

                    Link flag is ignored.

                    +
                    Constant: Rho.Barcode.UCC_ALWAYS (For Ruby use "::" for all "." when referencing constants)
                    String: always

                    Composite AB barcodes are always linked.

                    +
                    Constant: Rho.Barcode.UCC_AUTO (For Ruby use "::" for all "." when referencing constants)
                    String: auto

                    Auto-discriminate whether Composite AB barcodes are linked.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.compositeAbUccLinkMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.compositeAbUccLinkMode
                      • Ruby: Rho::Barcode.compositeAbUccLinkMode

                    compositeAbUseUpcPreambleCheckDigitRules : BOOLEAN 2.0.0

                    This setting causes the UPC rules specified in the UPC EAN parameters to be used when reporting composite decode data.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.compositeAbUseUpcPreambleCheckDigitRules
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.compositeAbUseUpcPreambleCheckDigitRules
                      • Ruby: Rho::Barcode.compositeAbUseUpcPreambleCheckDigitRules

                    compositeC : BOOLEAN 1.0.0

                    Enables or disables the symbology for Composite C barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.compositeC
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.compositeC
                      • Ruby: Rho::Barcode.compositeC

                    connectionIdleTimeout : INTEGER 1.0.0

                    Specifies the time, in seconds, that an external scanner will be allowed to remain idle before the connection is terminated to conserve power.

                    +

                    (Bluetooth Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.connectionIdleTimeout
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.connectionIdleTimeout
                      • Ruby: Rho::Barcode.connectionIdleTimeout

                    d2of5 : BOOLEAN 1.0.0

                    Enables or disables the symbology for D2of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.d2of5
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.d2of5
                      • Ruby: Rho::Barcode.d2of5

                    d2of5maxLength : INTEGER 1.0.0

                    Specifies the maximum number of allowable characters in a D2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.d2of5maxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.d2of5maxLength
                      • Ruby: Rho::Barcode.d2of5maxLength

                    d2of5minLength : INTEGER 1.0.0

                    Specifies the minimum number of allowable characters in a D2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.d2of5minLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.d2of5minLength
                      • Ruby: Rho::Barcode.d2of5minLength

                    d2of5redundancy : BOOLEAN 1.0.0

                    Sets the D2of5 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.d2of5redundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.d2of5redundancy
                      • Ruby: Rho::Barcode.d2of5redundancy

                    dataBufferSize : INTEGER 2.1.0

                    Specifies the number of bytes allocated to receive the scanned barcode. This parameter is designed to be used primarily with image based symbologies and should not be modified unless absolutely necessary (eg. Signature).

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.dataBufferSize
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.dataBufferSize
                      • Ruby: Rho::Barcode.dataBufferSize

                    datamatrix : BOOLEAN 1.0.0

                    Enables or disables the symbology for Datamatrix barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.datamatrix
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.datamatrix
                      • Ruby: Rho::Barcode.datamatrix

                    dbpMode : STRING 1.0.0

                    Describes the type of Digital Bar Pulse (DBP) being produced by the scan engine.

                    +

                    (Laser Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.DBP_NORMAL (For Ruby use "::" for all "." when referencing constants)
                    String: normal

                    Tells the scan engine to produce normal DBP.

                    +
                    Constant: Rho.Barcode.DBP_COMPOSITE (For Ruby use "::" for all "." when referencing constants)
                    String: composite

                    Tells the scan engine to produce composite DBP, which is 2 different sets of DBP data multiplexed together for better decode performance. In order to enable this mode it must be supported by the scanner.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.dbpMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.dbpMode
                      • Ruby: Rho::Barcode.dbpMode

                    decodeDuration : INTEGER 4.0.0

                    The duration of the device beeper when a barcode is scanned, in milliseconds.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Default: 250

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.decodeDuration
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.decodeDuration
                      • Ruby: Rho::Barcode.decodeDuration

                    decodeFrequency : INTEGER 4.0.0

                    The frequency of the device beeper when a barcode is successfully decoded. This should be within the range of the beeper but the API will accept values in the range 0 to 65535.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Default: 3000

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.decodeFrequency
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.decodeFrequency
                      • Ruby: Rho::Barcode.decodeFrequency

                    decodeSound : STRING 4.0.0

                    Path to a local wave file to be played when the scanner successfully decodes a barcode. This setting overrides the scanner beeper. In Android, this settings will not override beeper and hence not supported.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.decodeSound
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.decodeSound
                      • Ruby: Rho::Barcode.decodeSound

                    decodeVolume : INTEGER 4.0.0

                    The volume of the device beeper when a barcode is scanned. Volume specified using 0 to 5, with 5 being the loudest. The value of 0 is device dependent, some Windows Mobile / CE devices interpret this as the quietest volume; if you wish to completely disable the beeper on scan please set decodeSound to an empty or invalid sound file.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Default: 5

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.decodeVolume
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.decodeVolume
                      • Ruby: Rho::Barcode.decodeVolume

                    differentSymbolTimeout : INTEGER 1.0.0

                    When the aimType:continuousRead property is applied this value defines the interval between which different barcodes can be scanned. The value is specified in milliseconds, use 0 to indicate no interval between successive reads. Use this setting to allow time for the operator to re-aim the device between successive scans.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.differentSymbolTimeout
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.differentSymbolTimeout
                      • Ruby: Rho::Barcode.differentSymbolTimeout

                    disableScannerDuringNavigate : BOOLEAN 4.0.0

                    By default if you have enabled the Scanner on a page, through either JavaScript or Ruby and navigate to a new page the Scanner will automatically disable. To override this behavior you can set this option to false and once enabled the Scanner will remain so in the foreground application until you disable it.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Default: true

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.disableScannerDuringNavigate
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.disableScannerDuringNavigate
                      • Ruby: Rho::Barcode.disableScannerDuringNavigate

                    disconnectBtOnDisable : BOOLEAN 1.0.0

                    Forces the scanner to disconnect from the terminal when it is ‘disabled’. Since the scanner is disabled when you navigate to a new page, set this value to false if you want to maintain the bluetooth connection to your remote scanner.

                    +

                    (Bluetooth Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.disconnectBtOnDisable
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.disconnectBtOnDisable
                      • Ruby: Rho::Barcode.disconnectBtOnDisable

                    displayBtAddressBarcodeOnEnable : BOOLEAN 2.1.0

                    If set to true the bluetooth address will be displayed as a barcode on the screen during the pairing process, initiated by calling ‘enable’ on a bluetooth scanner. Not all devices support this functionality. Note you must specify this parameter before or within the call to ‘enable’.

                    +

                    (Bluetooth Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.displayBtAddressBarcodeOnEnable
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.displayBtAddressBarcodeOnEnable
                      • Ruby: Rho::Barcode.displayBtAddressBarcodeOnEnable

                    dpmMode : BOOLEAN 1.0.0

                    Allows Direct Part Marking (DPM) barcodes to be read When true, but may adversely affect overall decoding performance. DPM is a way of stamping barcodes directly on physical objects and is only available on DPM terminals.

                    +

                    (Imager / Camera Scanners on Symbol Technologies' devices. The scanning engine must support DPM barcodes.)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.dpmMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.dpmMode
                      • Ruby: Rho::Barcode.dpmMode

                    dutchPostal : BOOLEAN 1.0.0

                    Enables or disables the symbology for Dutch Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.dutchPostal
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.dutchPostal
                      • Ruby: Rho::Barcode.dutchPostal

                    ean13 : BOOLEAN 1.0.0

                    Enables or disables the symbology for EAN 13 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.ean13
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.ean13
                      • Ruby: Rho::Barcode.ean13

                    ean8 : BOOLEAN 1.0.0

                    Enables or disables the symbology for EAN 8 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.ean8
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.ean8
                      • Ruby: Rho::Barcode.ean8

                    ean8convertToEan13 : BOOLEAN 1.0.0

                    When true, EAN 8 barcodes will be converted to EAN 13 and EAN 13 parameters used.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.ean8convertToEan13
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.ean8convertToEan13
                      • Ruby: Rho::Barcode.ean8convertToEan13

                    enableTimeout : INTEGER 2.1.0

                    Configures the time (in seconds) allowed to pair with the external bluetooth scanner after calling the ‘enable()’ method. You must specify this parameter before calling ‘enable’ to change the default.

                    +

                    (Bluetooth Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.enableTimeout
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.enableTimeout
                      • Ruby: Rho::Barcode.enableTimeout

                    focusMode : STRING 1.0.0

                    Sets the focus mode in use.

                    +

                    (Imager / Camera Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.FOCUS_FIXED (For Ruby use "::" for all "." when referencing constants)
                    String: fixed

                    Use fixed focus.

                    +
                    Constant: Rho.Barcode.FOCUS_AUTO (For Ruby use "::" for all "." when referencing constants)
                    String: auto

                    Use auto focus.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.focusMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.focusMode
                      • Ruby: Rho::Barcode.focusMode

                    friendlyName : STRING Read Only 4.0.0

                    Returns the friendly name associated with the scanner.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.friendlyName
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.friendlyName
                      • Ruby: Rho::Barcode.friendlyName

                    gs1dataBar : BOOLEAN 2.1.0

                    Enables or disables the symbology for GS1 DataBar barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. This symbology was previously known as rss.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.gs1dataBar
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.gs1dataBar
                      • Ruby: Rho::Barcode.gs1dataBar

                    gs1dataBarExpanded : BOOLEAN 2.1.0

                    Enables or disables the symbology for GS1 Databar Expanded barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. This symbology was previously known as rssExp.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.gs1dataBarExpanded
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.gs1dataBarExpanded
                      • Ruby: Rho::Barcode.gs1dataBarExpanded

                    gs1dataBarLimited : BOOLEAN 2.1.0

                    Enables or disables the symbology for GS1 Databar Limited barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. This symbology was previously known as rssLim.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.gs1dataBarLimited
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.gs1dataBarLimited
                      • Ruby: Rho::Barcode.gs1dataBarLimited

                    hapticFeedback : BOOLEAN 4.0.0

                    Controls the haptic feedback on decode. This means that if this is set to true, then the device will vibrate when a decode occurs.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Default: true

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.hapticFeedback
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.hapticFeedback
                      • Ruby: Rho::Barcode.hapticFeedback

                    i2of5 : BOOLEAN 1.0.0

                    Enables or disables the symbology for I2of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.i2of5
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.i2of5
                      • Ruby: Rho::Barcode.i2of5

                    i2of5convertToEan13 : BOOLEAN 1.0.0

                    When true, EAN 8 barcodes will be converted to EAN 13 and EAN 13 parameters used.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.i2of5convertToEan13
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.i2of5convertToEan13
                      • Ruby: Rho::Barcode.i2of5convertToEan13

                    i2of5maxLength : INTEGER 1.0.0

                    Specifies the maximum number of allowable characters in a I2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.i2of5maxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.i2of5maxLength
                      • Ruby: Rho::Barcode.i2of5maxLength

                    i2of5minLength : INTEGER 1.0.0

                    Specifies the minimum number of allowable characters in a I2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.i2of5minLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.i2of5minLength
                      • Ruby: Rho::Barcode.i2of5minLength

                    i2of5redundancy : BOOLEAN 1.0.0

                    Sets the I2of5 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.i2of5redundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.i2of5redundancy
                      • Ruby: Rho::Barcode.i2of5redundancy

                    i2of5reportCheckDigit : BOOLEAN 1.0.0

                    When true, the barcode check digit(s) will be reported for scanned I2of5 barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.i2of5reportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.i2of5reportCheckDigit
                      • Ruby: Rho::Barcode.i2of5reportCheckDigit

                    i2of5verifyCheckDigit : STRING 1.0.0

                    Enables the verification of the I2of5 check digit.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.I2OF5_VERIFY_NONE (For Ruby use "::" for all "." when referencing constants)
                    String: none

                    Disables verification of the check digit.

                    +
                    Constant: Rho.Barcode.I2OF5_VERIFY_USS (For Ruby use "::" for all "." when referencing constants)
                    String: uss

                    Enables the USS format for the check digit.

                    +
                    Constant: Rho.Barcode.I2OF5_VERIFY_OPCC (For Ruby use "::" for all "." when referencing constants)
                    String: opcc

                    Enables the OPCC format for the check digit.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.i2of5verifyCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.i2of5verifyCheckDigit
                      • Ruby: Rho::Barcode.i2of5verifyCheckDigit

                    illuminationMode : STRING 1.0.0

                    Selects the illumination mode to use. Not currently supported on Android (illumination is always on).

                    +

                    (Imager / Camera Scanners on Symbol Technologies devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.ILLUMINATION_AUTO (For Ruby use "::" for all "." when referencing constants)
                    String: auto

                    Auto-exposure algorithms will decide whether illumination is required. Not currently supported on Android.

                    +
                    Constant: Rho.Barcode.ILLUMINATION_ALWAYS_ON (For Ruby use "::" for all "." when referencing constants)
                    String: alwaysOn

                    External illumination is always on.

                    +
                    Constant: Rho.Barcode.ILLUMINATION_ALWAYS_OFF (For Ruby use "::" for all "." when referencing constants)
                    String: alwaysOff

                    External illumination is always off.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.illuminationMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.illuminationMode
                      • Ruby: Rho::Barcode.illuminationMode

                    invalidDecodeFrequency : INTEGER 4.0.0

                    The frequency of the device beeper when a barcode is scanned but not successfully decoded. This should be within the range of the beeper but the API will accept values in the range 0 to 65535.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Default: 2500

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.invalidDecodeFrequency
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.invalidDecodeFrequency
                      • Ruby: Rho::Barcode.invalidDecodeFrequency

                    invalidDecodeSound : STRING 4.0.0

                    Path to a local wave file to be played when a barcode is scanned but not successfully decoded. This setting overrides the scanner beeper.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.invalidDecodeSound
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.invalidDecodeSound
                      • Ruby: Rho::Barcode.invalidDecodeSound

                    inverse1dMode : STRING 1.0.0

                    Allows the user to select inverse 1D barcodes for decoding.

                    +

                    (Scanners on Symbol Technologies' devices. The scanning engine must support inverse barcodes)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.INVERSE_ENABLED (For Ruby use "::" for all "." when referencing constants)
                    String: enabled

                    Inverse 1D symbology decoding is enabled.

                    +
                    Constant: Rho.Barcode.INVERSE_DISABLED (For Ruby use "::" for all "." when referencing constants)
                    String: disabled

                    Inverse 1D symbology decoding is disabled.

                    +
                    Constant: Rho.Barcode.INVERSE_AUTO (For Ruby use "::" for all "." when referencing constants)
                    String: auto

                    Allows decoding of both positive and inverse 1D symbologies.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.inverse1dMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.inverse1dMode
                      • Ruby: Rho::Barcode.inverse1dMode

                    japPostal : BOOLEAN 1.0.0

                    Enables or disables the symbology for Japanese Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.japPostal
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.japPostal
                      • Ruby: Rho::Barcode.japPostal

                    klasseEins : BOOLEAN 1.0.0

                    Enables or disables the Klasse Eins laser on time function.

                    +

                    (Laser Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.klasseEins
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.klasseEins
                      • Ruby: Rho::Barcode.klasseEins

                    korean3of5 : BOOLEAN 2.0.0

                    Enables or disables the symbology for Korean 3of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.korean3of5
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.korean3of5
                      • Ruby: Rho::Barcode.korean3of5

                    korean3of5maxLength : INTEGER 1.0.0

                    Specifies the maximum number of allowable characters in a Korean 3of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.korean3of5maxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.korean3of5maxLength
                      • Ruby: Rho::Barcode.korean3of5maxLength

                    korean3of5minLength : INTEGER 1.0.0

                    Specifies the minimum number of allowable characters in a Korean 3of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.korean3of5minLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.korean3of5minLength
                      • Ruby: Rho::Barcode.korean3of5minLength

                    korean3of5redundancy : BOOLEAN 1.0.0

                    Sets Korean 3of5 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.korean3of5redundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.korean3of5redundancy
                      • Ruby: Rho::Barcode.korean3of5redundancy

                    lcdMode : BOOLEAN 4.0.0

                    Controls whether LCD Mode is enabled on the scanner. LCD Mode makes it easier to scan barcodes off of LCD screens (like mobile device screens)

                    +

                    (Scanners on Symbol Technologies' devices)

                    Default: false

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.lcdMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.lcdMode
                      • Ruby: Rho::Barcode.lcdMode

                    linearSecurityLevel : STRING 1.0.0

                    Describes the linear security level used during decoding. This determines the number of times a barcode must be read before it is decoded. If the successive reads of the barcode do not match, it will not be decoded.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.REDUNDANCY_AND_LENGTH (For Ruby use "::" for all "." when referencing constants)
                    String: redundancyAndLength

                    Double redundancy based on redundancy flags and code length. Only applicable to laser scanners, not BlockBuster imager scanners. Not supported on Android with EMDK version 3.1 and above.

                    +
                    Constant: Rho.Barcode.SHORT_OR_CODABAR (For Ruby use "::" for all "." when referencing constants)
                    String: shortOrCodabar

                    Double redundancy if short barcode or Codabar.

                    +
                    Constant: Rho.Barcode.LONG_AND_SHORT (For Ruby use "::" for all "." when referencing constants)
                    String: longAndShort

                    Double redundancy for long barcodes, triple for short barcodes.

                    +
                    Constant: Rho.Barcode.ALL_TWICE (For Ruby use "::" for all "." when referencing constants)
                    String: allTwice

                    Double redundancy for all barcodes.

                    +
                    Constant: Rho.Barcode.ALL_THRICE (For Ruby use "::" for all "." when referencing constants)
                    String: allThrice

                    Triple redundancy for all barcodes.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.linearSecurityLevel
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.linearSecurityLevel
                      • Ruby: Rho::Barcode.linearSecurityLevel

                    lowBatteryScan : BOOLEAN 1.0.0

                    Set to false to disable scanning when the battery is low / critical or set to true to enable it.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Default: false

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.lowBatteryScan
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.lowBatteryScan
                      • Ruby: Rho::Barcode.lowBatteryScan

                    macroMicroPdf : BOOLEAN 1.0.0

                    Enables or disables the symbology for MacroMicroPDF barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.macroMicroPdf
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.macroMicroPdf
                      • Ruby: Rho::Barcode.macroMicroPdf

                    macroMicroPdfBufferLabels : BOOLEAN 2.0.0

                    If true, the scanner driver will return the barcode data only after the complete macroMicroPdf sequence has been read. If false, the scanner driver will return each barcode in the macroMicroPdf sequence as it is read.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.macroMicroPdfBufferLabels
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.macroMicroPdfBufferLabels
                      • Ruby: Rho::Barcode.macroMicroPdfBufferLabels

                    macroMicroPdfConvertToMicroPdf : BOOLEAN 2.0.0

                    If true, MacroMicroPDF barcodes will be converted to MicroPDF codes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.macroMicroPdfConvertToMicroPdf
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.macroMicroPdfConvertToMicroPdf
                      • Ruby: Rho::Barcode.macroMicroPdfConvertToMicroPdf

                    macroMicroPdfExclusive : BOOLEAN 2.0.0

                    If true, the scanner driver will not complete read requests while in the middle of a macroMicroPdf sequence. Once a macroMicroPdf sequence has been started it must be completed or canceled before the scan driver will complete other read requests.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.macroMicroPdfExclusive
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.macroMicroPdfExclusive
                      • Ruby: Rho::Barcode.macroMicroPdfExclusive

                    macroMicroPdfReportAppendInfo : BOOLEAN 2.0.0

                    If true, the appended info is concatenated to the decoded data before being returned.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.macroMicroPdfReportAppendInfo
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.macroMicroPdfReportAppendInfo
                      • Ruby: Rho::Barcode.macroMicroPdfReportAppendInfo

                    macroPdf : BOOLEAN 1.0.0

                    Enables or disables the symbology for Macro PDF barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.macroPdf
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.macroPdf
                      • Ruby: Rho::Barcode.macroPdf

                    macroPdfBufferLabels : BOOLEAN 2.0.0

                    When true, the scanner driver will return he barcode data only after the complete macroPdf sequence has been read. If false, the scan driver will return each barcode in the macroPdf sequence as it is read.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.macroPdfBufferLabels
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.macroPdfBufferLabels
                      • Ruby: Rho::Barcode.macroPdfBufferLabels

                    macroPdfConvertToPdf417 : BOOLEAN 2.0.0

                    If true, MacroPDF barcodes will be converted to PDF417 codes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.macroPdfConvertToPdf417
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.macroPdfConvertToPdf417
                      • Ruby: Rho::Barcode.macroPdfConvertToPdf417

                    macroPdfExclusive : BOOLEAN 2.0.0

                    If true, the scanner driver will not complete read requests while in the middle of a macroPdf sequence. Once a macroPdf sequence has been started it must be completed or canceled before the scan driver will complete other read requests.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.macroPdfExclusive
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.macroPdfExclusive
                      • Ruby: Rho::Barcode.macroPdfExclusive

                    matrix2of5 : BOOLEAN 2.0.0

                    Enables or disables the symbology for Matrix 2of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.matrix2of5
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.matrix2of5
                      • Ruby: Rho::Barcode.matrix2of5

                    matrix2of5maxLength : INTEGER 2.0.0

                    Specifies the maximum number of allowable characters in a Matrix 2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.matrix2of5maxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.matrix2of5maxLength
                      • Ruby: Rho::Barcode.matrix2of5maxLength

                    matrix2of5minLength : INTEGER 2.0.0

                    Specifies the minimum number of allowable characters in a Matrix 2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.matrix2of5minLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.matrix2of5minLength
                      • Ruby: Rho::Barcode.matrix2of5minLength

                    matrix2of5reportCheckDigit : BOOLEAN 2.0.0

                    When true, the barcode check digit(s) will be reported for scanned Matrix 2of5 barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.matrix2of5reportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.matrix2of5reportCheckDigit
                      • Ruby: Rho::Barcode.matrix2of5reportCheckDigit

                    matrix2of5verifyCheckDigit : BOOLEAN 2.0.0

                    Enables verification of the Matrix 2of5 symbology check digit.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.matrix2of5verifyCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.matrix2of5verifyCheckDigit
                      • Ruby: Rho::Barcode.matrix2of5verifyCheckDigit

                    maxiCode : BOOLEAN 1.0.0

                    Enables or disables the symbology for Maxicode barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.maxiCode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.maxiCode
                      • Ruby: Rho::Barcode.maxiCode

                    microPdf : BOOLEAN 1.0.0

                    Enables or disables the symbology for Micro PDF barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.microPdf
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.microPdf
                      • Ruby: Rho::Barcode.microPdf

                    microQr : BOOLEAN 1.0.0

                    Enables or disables the symbology for Micro QR barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.microQr
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.microQr
                      • Ruby: Rho::Barcode.microQr

                    msi : BOOLEAN 1.0.0

                    Enables or disables the symbology for MSI barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.msi
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.msi
                      • Ruby: Rho::Barcode.msi

                    msiCheckDigitScheme : STRING 1.0.0

                    Specifies the check digit scheme used to verify MSI barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.MSI_CHECKDIGITS_MOD11 (For Ruby use "::" for all "." when referencing constants)
                    String: mod11

                    The first check digit is MOD 11, the second is MOD 10.

                    +
                    Constant: Rho.Barcode.MSI_CHECKDIGITS_MOD10 (For Ruby use "::" for all "." when referencing constants)
                    String: mod10

                    Both check digits are MOD 10.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.msiCheckDigitScheme
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.msiCheckDigitScheme
                      • Ruby: Rho::Barcode.msiCheckDigitScheme

                    msiCheckDigits : STRING 1.0.0

                    Sets the number of MSI check digits to use.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.MSI_CHECKDIGITS_ONE (For Ruby use "::" for all "." when referencing constants)
                    String: one

                    Use one check digit for MSI barcodes.

                    +
                    Constant: Rho.Barcode.MSI_CHECKDIGITS_TWO (For Ruby use "::" for all "." when referencing constants)
                    String: two

                    Use two check digits for MSI barcodes.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.msiCheckDigits
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.msiCheckDigits
                      • Ruby: Rho::Barcode.msiCheckDigits

                    msiMaxLength : INTEGER 1.0.0

                    Specifies the maximum number of allowable characters in a MSI barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.msiMaxLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.msiMaxLength
                      • Ruby: Rho::Barcode.msiMaxLength

                    msiMinLength : INTEGER 1.0.0

                    Specifies the minimum number of allowable characters in a MSI barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.msiMinLength
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.msiMinLength
                      • Ruby: Rho::Barcode.msiMinLength

                    msiRedundancy : BOOLEAN 1.0.0

                    Sets the MSI Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.msiRedundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.msiRedundancy
                      • Ruby: Rho::Barcode.msiRedundancy

                    msiReportCheckDigit : BOOLEAN 1.0.0

                    When true, the barcode check digit(s) will be reported for scanned MSI barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.msiReportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.msiReportCheckDigit
                      • Ruby: Rho::Barcode.msiReportCheckDigit

                    pdf417 : BOOLEAN 1.0.0

                    Enables or disables the symbology for PDF 417 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.pdf417
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.pdf417
                      • Ruby: Rho::Barcode.pdf417

                    picklistMode : STRING 1.0.0

                    Allows the imager to decode only the barcode that is directly under the cross-hair / center of the reticle. This feature is most useful in applications where multiple barcodes may appear in the field of view during a decode session and only one of them is targeted for decode. When enabled picklistMode will override aimMode or, if no aiming is chosen, and use aimMode:reticle. This mode will also interact with viewfinderMode, see the EMDK for C help file for more information. Enabling picklist mode may adversely affect overall decoding performance.

                    +

                    (Imager / Camera Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.PICKLIST_DISABLED (For Ruby use "::" for all "." when referencing constants)
                    String: disabled

                    Disables picklist mode so any barcode within the field of view can be decoded.

                    +
                    Constant: Rho.Barcode.PICKLIST_HARDWARE_RETICLE (For Ruby use "::" for all "." when referencing constants)
                    String: hardwareReticle

                    Enables picklist mode so that only the barcode under the projected reticle can be decoded. On Windows, if the imager does not support a projected reticle then the behavior is the same as softwareReticle. On Android, this is only supported for Imager (non-viewfinder) based scanners.

                    +
                    Constant: Rho.Barcode.PICKLIST_SOFTWARE_RETICLE (For Ruby use "::" for all "." when referencing constants)
                    String: softwareReticle

                    Enables picklist mode so that only the barcode in the center of the image is decoded. This is most useful when used in conjunction with static and dynamic reticle viewfinder modes. This value is not supported on Android Platform.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.picklistMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.picklistMode
                      • Ruby: Rho::Barcode.picklistMode

                    poorQuality1dMode : BOOLEAN 1.0.0

                    Allows poor quality 1D barcodes to be read When true, but this will adversely affect the overall decoding performance.

                    +

                    (Imager / Camera Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.poorQuality1dMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.poorQuality1dMode
                      • Ruby: Rho::Barcode.poorQuality1dMode

                    qrCode : BOOLEAN 1.0.0

                    Enables or disables the symbology for QR Code barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.qrCode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.qrCode
                      • Ruby: Rho::Barcode.qrCode

                    rasterHeight : INTEGER 1.0.0

                    Vertical rastering height to use, as a percentage, when rasterMode:openAlways is applied. This value must be between 0 and 100.

                    +

                    (Laser Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rasterHeight
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rasterHeight
                      • Ruby: Rho::Barcode.rasterHeight

                    rasterMode : STRING 1.0.0

                    Describes the type of vertical rastering to use.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.RASTER_NONE (For Ruby use "::" for all "." when referencing constants)
                    String: none

                    No vertical rastering.

                    +
                    Constant: Rho.Barcode.RASTER_OPEN_ALWAYS (For Ruby use "::" for all "." when referencing constants)
                    String: openAlways

                    Vertical rastering is always full open. To adjust the rastering height use the rasterHeight property.

                    +
                    Constant: Rho.Barcode.RASTER_SMART (For Ruby use "::" for all "." when referencing constants)
                    String: smart

                    Vertical rastering mode is ‘Smart’.

                    +
                    Constant: Rho.Barcode.RASTER_CYCLONE (For Ruby use "::" for all "." when referencing constants)
                    String: cyclone

                    Vertical rastering mode is ‘Cyclone’.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rasterMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rasterMode
                      • Ruby: Rho::Barcode.rasterMode

                    rsmBatteryCapacity : STRING Read Only 4.0.0

                    The remaining capacity of the battery, in the range 0 to 100. ‘unknown’ will be returned if the capacity could not be determined, for example if the scanner had no battery.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBatteryCapacity
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBatteryCapacity
                      • Ruby: Rho::Barcode.rsmBatteryCapacity

                    rsmBatteryId : STRING Read Only 4.0.0

                    One of ‘simple’, ‘double’, ‘disabled’ or ‘unknown’

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBatteryId
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBatteryId
                      • Ruby: Rho::Barcode.rsmBatteryId

                    rsmBatteryStatus : STRING Read Only 4.0.0

                    Indicates the status of the remote scanner’s battery, will be one of ‘unknown’, ‘full’, ‘medium’, ‘empty’, ‘chargingFullRate’, ‘chargingHalfRate’, ‘chargingTrickle’ or ‘discharging’

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBatteryStatus
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBatteryStatus
                      • Ruby: Rho::Barcode.rsmBatteryStatus

                    rsmBluetoothAddress : STRING Read Only 4.0.0

                    Bluetooth address as FF:FF:FF:FF:FF:FF where FF is a hex number.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothAddress
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothAddress
                      • Ruby: Rho::Barcode.rsmBluetoothAddress

                    rsmBluetoothAuthentication : BOOLEAN 4.0.0

                    True if authentication is required.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothAuthentication
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothAuthentication
                      • Ruby: Rho::Barcode.rsmBluetoothAuthentication

                    rsmBluetoothAutoReconnect : STRING 4.0.0

                    Bluetooth reconnection scheme.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.RSM_AUTORECONNECT_NONE (For Ruby use "::" for all "." when referencing constants)
                    String: none

                    No scheme.

                    +
                    Constant: Rho.Barcode.RSM_AUTORECONNECT_ON_POWER (For Ruby use "::" for all "." when referencing constants)
                    String: onPower

                    When powered on.

                    +
                    Constant: Rho.Barcode.RSM_AUTORECONNECT_ON_OUT_OF_RANGE (For Ruby use "::" for all "." when referencing constants)
                    String: onOutOfRange

                    When device goes out of range.

                    +
                    Constant: Rho.Barcode.RSM_AUTORECONNECT_ON_POWER_OUT_OF_RANGE (For Ruby use "::" for all "." when referencing constants)
                    String: onPowerOutOfRange

                    When powered on or when the device goes out of range.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothAutoReconnect
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothAutoReconnect
                      • Ruby: Rho::Barcode.rsmBluetoothAutoReconnect

                    rsmBluetoothBeepOnReconnectAttempt : BOOLEAN 4.0.0

                    When true, scanner will emit 5 beeps every 5 seconds whilst re-connection in progress.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothBeepOnReconnectAttempt
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothBeepOnReconnectAttempt
                      • Ruby: Rho::Barcode.rsmBluetoothBeepOnReconnectAttempt

                    rsmBluetoothEncryption : BOOLEAN 4.0.0

                    True if encryption is required.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothEncryption
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothEncryption
                      • Ruby: Rho::Barcode.rsmBluetoothEncryption

                    rsmBluetoothFriendlyName : STRING 4.0.0

                    Friendly Bluetooth name, e.g. ‘MyBTScanner’

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothFriendlyName
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothFriendlyName
                      • Ruby: Rho::Barcode.rsmBluetoothFriendlyName

                    rsmBluetoothHidAutoReconnect : STRING 4.0.0

                    ‘neverReconnect’, ‘reconnectOnData’ or ‘reconnectImmediately’

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothHidAutoReconnect
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothHidAutoReconnect
                      • Ruby: Rho::Barcode.rsmBluetoothHidAutoReconnect

                    rsmBluetoothInquiryMode : STRING 4.0.0

                    To use a general inquiry mode, ‘general’ else, ‘limited’

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothInquiryMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothInquiryMode
                      • Ruby: Rho::Barcode.rsmBluetoothInquiryMode

                    rsmBluetoothPinCode : STRING 4.0.0

                    Up to 5 character PIN code used for Bluetooth authentication.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothPinCode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothPinCode
                      • Ruby: Rho::Barcode.rsmBluetoothPinCode

                    rsmBluetoothPinCodeType : STRING 4.0.0

                    ‘UseStored’ will use the PIN code stored in the memory of the ring scanner, by default ‘12345’. ‘PromptUser’ indicates that the ring scanner should be used to scan 5 alpha numeric barcodes to define the PIN, eg. “1”, “2”, “3”, “4”, “5” (for PIN 12345). This parameter is not saved permanently on the ring scanner.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothPinCodeType
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothPinCodeType
                      • Ruby: Rho::Barcode.rsmBluetoothPinCodeType

                    rsmBluetoothReconnectionAttempts : INTEGER 4.0.0

                    How long the scanner tries to re-establish connection if it goes out of range, in seconds. This value must be a multiple of 5 and in the range 30 to 60 seconds.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmBluetoothReconnectionAttempts
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmBluetoothReconnectionAttempts
                      • Ruby: Rho::Barcode.rsmBluetoothReconnectionAttempts

                    rsmDateOfManufacture : STRING Read Only 4.0.0

                    Ring scanner date of manufacture as DDMMYY.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmDateOfManufacture
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmDateOfManufacture
                      • Ruby: Rho::Barcode.rsmDateOfManufacture

                    rsmDateOfService : STRING Read Only 4.0.0

                    Ring scanner date of service as DDMMYY.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmDateOfService
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmDateOfService
                      • Ruby: Rho::Barcode.rsmDateOfService

                    rsmDecodeFeedback : BOOLEAN 4.0.0

                    If true, the remote scanner beeps and illuminates its green LED on a successful decode.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmDecodeFeedback
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmDecodeFeedback
                      • Ruby: Rho::Barcode.rsmDecodeFeedback

                    rsmDeviceClass : STRING Read Only 4.0.0

                    The device class of the ring scanner.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmDeviceClass
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmDeviceClass
                      • Ruby: Rho::Barcode.rsmDeviceClass

                    rsmFirmwareVersion : STRING Read Only 4.0.0

                    Scanner’s operating system version.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmFirmwareVersion
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmFirmwareVersion
                      • Ruby: Rho::Barcode.rsmFirmwareVersion

                    rsmForceSavePairingBarcode : BOOLEAN 4.0.0

                    Force saving the barcode assigned to the device to which the scanner has been paired.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmForceSavePairingBarcode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmForceSavePairingBarcode
                      • Ruby: Rho::Barcode.rsmForceSavePairingBarcode

                    rsmGoodScansDelay : INTEGER 4.0.0

                    Delay between good scans in proximity continuous mode, measured in milliseconds. Range 0 to 15000. This value must be a multiple of 100.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmGoodScansDelay
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmGoodScansDelay
                      • Ruby: Rho::Barcode.rsmGoodScansDelay

                    rsmIgnoreCode128Usps : BOOLEAN 4.0.0

                    Feature for ignoring Code 128 barcodes beginning with 420 and 421.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmIgnoreCode128Usps
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmIgnoreCode128Usps
                      • Ruby: Rho::Barcode.rsmIgnoreCode128Usps

                    rsmLowBatteryIndication : BOOLEAN 4.0.0

                    Whether or not the ring scanner should give a low battery indication.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmLowBatteryIndication
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmLowBatteryIndication
                      • Ruby: Rho::Barcode.rsmLowBatteryIndication

                    rsmLowBatteryIndicationCycle : INTEGER 4.0.0

                    Low battery indication cycle time, in seconds. Must be one of 15, 30, 60, 90 or 120.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmLowBatteryIndicationCycle
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmLowBatteryIndicationCycle
                      • Ruby: Rho::Barcode.rsmLowBatteryIndicationCycle

                    rsmMems : BOOLEAN 4.0.0

                    If you press the trigger on an RSM scanner, proximity enabled will be turned off, even though it still reports its self as being turned on if you query the property. In order to use ProximityEnable you need to also have Mems enabled, this is the motion sensor and if you disable Mems the scanner will not function.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmMems
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmMems
                      • Ruby: Rho::Barcode.rsmMems

                    rsmModelNumber : STRING Read Only 4.0.0

                    Ring scanner model number.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmModelNumber
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmModelNumber
                      • Ruby: Rho::Barcode.rsmModelNumber

                    rsmPagingBeepSequence : INTEGER 4.0.0

                    Range 0 to 15 to specify the pattern for the paging beep sequence.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmPagingBeepSequence
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmPagingBeepSequence
                      • Ruby: Rho::Barcode.rsmPagingBeepSequence

                    rsmPagingEnable : BOOLEAN 4.0.0

                    Specify whether paging the device is enabled.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmPagingEnable
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmPagingEnable
                      • Ruby: Rho::Barcode.rsmPagingEnable

                    rsmProximityContinuous : BOOLEAN 4.0.0

                    Proximity continuous mode.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmProximityContinuous
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmProximityContinuous
                      • Ruby: Rho::Barcode.rsmProximityContinuous

                    rsmProximityDistance : STRING 4.0.0

                    Specify the distance for the proximity feature as ‘short’, ‘medium’ or ‘long’

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmProximityDistance
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmProximityDistance
                      • Ruby: Rho::Barcode.rsmProximityDistance

                    rsmProximityEnable : BOOLEAN 4.0.0

                    If you press the trigger on an RSM scanner, proximity enabled will be turned off, even though it still reports its self as being turned on if you query the property. In order to use ProximityEnable you need to also have Mems enabled, this is the motion sensor and if you disable Mems the scanner will not function.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmProximityEnable
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmProximityEnable
                      • Ruby: Rho::Barcode.rsmProximityEnable

                    rsmScanLineWidth : STRING 4.0.0

                    The laser scan line width, ‘wide’ or ‘narrow’.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmScanLineWidth
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmScanLineWidth
                      • Ruby: Rho::Barcode.rsmScanLineWidth

                    rsmScanTriggerWakeup : BOOLEAN 4.0.0

                    Scanner trigger will wakeup the device from a low power state.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmScanTriggerWakeup
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmScanTriggerWakeup
                      • Ruby: Rho::Barcode.rsmScanTriggerWakeup

                    rsmSerialNumber : STRING Read Only 4.0.0

                    Ring scanner serial number.

                    +

                    (Symbol Technologies' Bluetooth barcode scanners, model RS507)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.rsmSerialNumber
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.rsmSerialNumber
                      • Ruby: Rho::Barcode.rsmSerialNumber

                    sameSymbolTimeout : INTEGER 1.0.0

                    When the aimType:continuousRead property is applied this value defines the interval between which the same barcode can be decoded twice. The value is specified in milliseconds, use 0 to indicate no interval between successive reads. Use this value to prevent accidental duplicate scans.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.sameSymbolTimeout
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.sameSymbolTimeout
                      • Ruby: Rho::Barcode.sameSymbolTimeout

                    scanTimeout : INTEGER 1.0.0

                    Maximum time in milliseconds that laser scanners will emit a beam or imager scanners will enable the imager. A value of 0 indicates an infinite timeout. This parameter is compatible with aimType:trigger, aimType:timedHold, aimType:timedRelease and aimType:pressAndRelease. Note that for regulatory reasons scanTimeout is not configurable on all laser / imager scanners. Scan timeout is extent to hardware capabilities and limitations.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.scanTimeout
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.scanTimeout
                      • Ruby: Rho::Barcode.scanTimeout

                    scannerType : STRING Read Only 4.0.0

                    The type of scanner in use, will be one of ‘Camera’, ‘Imager’ or ‘Laser’. Camera scanners capture and process an image taken via the devices camera. Imager scanners rely on capturing and processing an image of the barcode via dedicated scanning hardware. Both camera and imager scanners are capable of decoding 1D and 2D barcodes. Laser scanners are only capable of decoding 1D barcodes and rely on a sweeping laser.

                    +

                    (All Scanners)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.scannerType
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.scannerType
                      • Ruby: Rho::Barcode.scannerType

                    signature : BOOLEAN 2.1.0

                    Enables or disables the symbology for Signature barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. Signature barcodes return their data in Data URI format, it is recommended you adjust the dataBufferSize and barcodeDataFormat properties when scanning Signature barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.signature
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.signature
                      • Ruby: Rho::Barcode.signature

                    signatureImageHeight : INTEGER 2.1.0

                    Specifies the output height of the captured signature barcode. Signature barcodes return their data in Data URI format, it is recommended you adjust the dataBufferSize and barcodeDataFormat properties when scanning Signature barcodes. Provide a number greater than or equal to 20.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.signatureImageHeight
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.signatureImageHeight
                      • Ruby: Rho::Barcode.signatureImageHeight

                    signatureImageQuality : INTEGER 2.1.0

                    Specifies the output quality of the captured signature barcode. Signature barcodes return their data in Data URI format, it is recommended you adjust the dataBufferSize and barcodeDataFormat properties when scanning Signature barcodes. Provide a value between 10 and 100 inclusive.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.signatureImageQuality
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.signatureImageQuality
                      • Ruby: Rho::Barcode.signatureImageQuality

                    signatureImageWidth : INTEGER 2.1.0

                    Specifies the output width of the captured signature barcode. Signature barcodes return their data in Data URI format, it is recommended you adjust the dataBufferSize and barcodeDataFormat properties when scanning Signature barcodes. Provide a number greater than or equal to 20.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.signatureImageWidth
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.signatureImageWidth
                      • Ruby: Rho::Barcode.signatureImageWidth

                    timedAimDuration : INTEGER 1.0.0

                    Aim duration in milliseconds for aimType:timedHold and aimType:timedRelease.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.timedAimDuration
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.timedAimDuration
                      • Ruby: Rho::Barcode.timedAimDuration

                    tlc39 : BOOLEAN 1.0.0

                    Enables or disables the symbology for TLC 39 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.tlc39
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.tlc39
                      • Ruby: Rho::Barcode.tlc39

                    triggerConnected : BOOLEAN 4.1.0

                    Only applies to an enabled laser or imaging scanner. Disconnecting the trigger will prevent the scan beam from being emitted, this can temporarily prevent a user from scanning without having to disable the scanner, which can take longer. By default the trigger will be connected when the scanner is first enabled, you do not have to connect it separately. Please note that disconnecting the trigger will also prevent the start method from emitting a laser. This property will only affect the scanner and will have no effect on the ‘captureTrigger’ API.

                    +

                    (Scanners on Symbol Technologies' devices)

                    Default: true

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.triggerConnected
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.triggerConnected
                      • Ruby: Rho::Barcode.triggerConnected

                    trioptic39 : BOOLEAN 1.0.0

                    Enables or disables the symbology for Trioptic 39 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.trioptic39
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.trioptic39
                      • Ruby: Rho::Barcode.trioptic39

                    trioptic39Redundancy : BOOLEAN 1.0.0

                    Sets the Trioptic 39 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.trioptic39Redundancy
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.trioptic39Redundancy
                      • Ruby: Rho::Barcode.trioptic39Redundancy

                    ukPostal : BOOLEAN 1.0.0

                    Enables or disables the symbology for UK Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.ukPostal
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.ukPostal
                      • Ruby: Rho::Barcode.ukPostal

                    ukPostalReportCheckDigit : BOOLEAN 1.0.0

                    When true, the barcode check digit(s) will be reported for scanned UK Postal barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.ukPostalReportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.ukPostalReportCheckDigit
                      • Ruby: Rho::Barcode.ukPostalReportCheckDigit

                    upcEanBookland : BOOLEAN 2.0.0

                    Enables or disables decoding of UPC EAN Bookland barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanBookland
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanBookland
                      • Ruby: Rho::Barcode.upcEanBookland

                    upcEanBooklandFormat : STRING 1.0.0

                    Specifies the bookland format to use when decoding UPC EAN Bookland barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.BOOKLAND_ISBN10 (For Ruby use "::" for all "." when referencing constants)
                    String: isbn10

                    Causes 978 bookland barcodes to be reported in 10 digit mode.

                    +
                    Constant: Rho.Barcode.BOOKLAND_ISBN13 (For Ruby use "::" for all "." when referencing constants)
                    String: isbn13

                    Causes 978/979 bookland barcodes to be transmitted as EAN13 as per 2007 ISBN-13 protocol.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanBooklandFormat
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanBooklandFormat
                      • Ruby: Rho::Barcode.upcEanBooklandFormat

                    upcEanConvertGs1dataBarToUpcEan : BOOLEAN 2.1.0

                    If true, RSS barcodes will be converted to UPC/EAN format. For this setting to work UPC/EAN symbologies must be enabled.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanConvertGs1dataBarToUpcEan
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanConvertGs1dataBarToUpcEan
                      • Ruby: Rho::Barcode.upcEanConvertGs1dataBarToUpcEan

                    upcEanCoupon : BOOLEAN 1.0.0

                    Enables or disables decoding of UPC EAN Coupon barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanCoupon
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanCoupon
                      • Ruby: Rho::Barcode.upcEanCoupon

                    upcEanLinearDecode : BOOLEAN 1.0.0

                    Sets the linear decode property.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanLinearDecode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanLinearDecode
                      • Ruby: Rho::Barcode.upcEanLinearDecode

                    upcEanRandomWeightCheckDigit : BOOLEAN 1.0.0

                    When true, enables random weight check digit verification.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanRandomWeightCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanRandomWeightCheckDigit
                      • Ruby: Rho::Barcode.upcEanRandomWeightCheckDigit

                    upcEanRetryCount : INTEGER 1.0.0

                    Sets the retry count for auto-discriminating for supplementals. The value must be between 2 – 20 inclusive.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanRetryCount
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanRetryCount
                      • Ruby: Rho::Barcode.upcEanRetryCount

                    upcEanSecurityLevel : INTEGER 2.0.0

                    Sets the Security level for decoding UPC EAN barcodes and accepts a value between 0 and 3 inclusive. 0: This setting allows the scanner to operate in its most aggressive state, while providing sufficient security in decoding most ‘in-spec’ barcodes. 1: This setting eliminates most mis-decodes. 2: Select this option if security level 1 fails to eliminate mis-decodes. 3: Select this option if security level 1 and 2 fail to eliminate mis-decodes. Be advised that selecting level 3 is an extreme measure against mis-decoding and will significantly impair the decoding ability of the scanner.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanSecurityLevel
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanSecurityLevel
                      • Ruby: Rho::Barcode.upcEanSecurityLevel

                    upcEanSupplemental2 : BOOLEAN 1.0.0

                    When true, enables the supplemental barcode decoding. Note you must have upcEanSupplementalMode:always set for this parameter to take effect.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanSupplemental2
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanSupplemental2
                      • Ruby: Rho::Barcode.upcEanSupplemental2

                    upcEanSupplemental5 : BOOLEAN 1.0.0

                    When true, enables the supplemental barcode decoding. Note you must have upcEanSupplementalMode:always set for this parameter to take effect.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanSupplemental5
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanSupplemental5
                      • Ruby: Rho::Barcode.upcEanSupplemental5

                    upcEanSupplementalMode : STRING 1.0.0

                    Describes the UPC EAN Supplemental mode.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.UPCEAN_NONE (For Ruby use "::" for all "." when referencing constants)
                    String: none

                    Supplementals are ignored.

                    +
                    Constant: Rho.Barcode.UPCEAN_AUTO (For Ruby use "::" for all "." when referencing constants)
                    String: auto

                    Auto-discriminates supplementals.

                    +
                    Constant: Rho.Barcode.UPCEAN_ALWAYS (For Ruby use "::" for all "." when referencing constants)
                    String: always

                    Will not decode upc/ean without supplementals.

                    +
                    Constant: Rho.Barcode.UPCEAN_SMART (For Ruby use "::" for all "." when referencing constants)
                    String: smart

                    The decoder will return the decoded value of the main block right away if it does not belong to any of the supplemental types. If the barcode starts with one of the prefixes it will search the image more aggressively for a supplemental. The scanner will try to scan the supplemental if it is present but if that fails, the main barcode will be returned.

                    +
                    Constant: Rho.Barcode.UPCEAN_379 (For Ruby use "::" for all "." when referencing constants)
                    String: 378or379

                    Auto-discriminates supplemental for upc/ean codes starting with 378 or 379. Will disable reading of supplementals for any other upc/ean barcodes not starting with these values. The supplemental will be scanned if present but if scanning fails then the main barcode will be returned.

                    +
                    Constant: Rho.Barcode.UPCEAN_979 (For Ruby use "::" for all "." when referencing constants)
                    String: 978or979

                    Auto-discriminates supplemental for upc/ean codes starting with 978 or 979. Will disable reading of supplementals for any other upc/ean barcodes not starting with these values. The supplemental will be scanned if present but if scanning fails then the main barcode will be returned.

                    +
                    Constant: Rho.Barcode.UPCEAN_439 (For Ruby use "::" for all "." when referencing constants)
                    String: 414or419or434or439

                    Auto-discriminates supplemental for upc/ean codes starting with 414 or 419 or 434 or 439. Will disable reading of supplementals for any other upc/ean barcodes not starting with these values. The supplemental will be scanned if present but if scanning fails then the main barcode will be returned.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcEanSupplementalMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcEanSupplementalMode
                      • Ruby: Rho::Barcode.upcEanSupplementalMode

                    upca : BOOLEAN 1.0.0

                    Enables or disables the symbology for UPCA barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upca
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upca
                      • Ruby: Rho::Barcode.upca

                    upcaPreamble : STRING 1.0.0

                    Controls the preamble applied to the UPCA barcode.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.UPCA_PREAMBLE_NONE (For Ruby use "::" for all "." when referencing constants)
                    String: none

                    Applies no preamble to the bar code.

                    +
                    Constant: Rho.Barcode.UPCA_PREAMBLE_SYSTEMCHAR (For Ruby use "::" for all "." when referencing constants)
                    String: systemChar

                    Applies system character preamble to the bar code.

                    +
                    Constant: Rho.Barcode.UPCA_PREAMBLE_COUNTRY (For Ruby use "::" for all "." when referencing constants)
                    String: countryAndSystemChars

                    Applies both system and country code preamble to the bar code.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcaPreamble
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcaPreamble
                      • Ruby: Rho::Barcode.upcaPreamble

                    upcaReportCheckDigit : BOOLEAN 1.0.0

                    When true, the barcode check digit(s) will be reported for scanned UPCA barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upcaReportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upcaReportCheckDigit
                      • Ruby: Rho::Barcode.upcaReportCheckDigit

                    upce0 : BOOLEAN 1.0.0

                    Enables or disables the symbology for UPCE0 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upce0
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upce0
                      • Ruby: Rho::Barcode.upce0

                    upce0convertToUpca : BOOLEAN 1.0.0

                    When true, scanned UPCE0 barcodes will be converted to UPCA and UPCA parameters used.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upce0convertToUpca
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upce0convertToUpca
                      • Ruby: Rho::Barcode.upce0convertToUpca

                    upce0preamble : STRING 1.0.0

                    Controls the preamble applied to the UPCE0 barcode.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.UPCE0_PREAMBLE_NONE (For Ruby use "::" for all "." when referencing constants)
                    String: none

                    Applies no preamble to the bar code.

                    +
                    Constant: Rho.Barcode.UPCE0_PREAMBLE_SYSTEMCHAR (For Ruby use "::" for all "." when referencing constants)
                    String: systemChar

                    Applies system character preamble to the bar code.

                    +
                    Constant: Rho.Barcode.UPCE0_PREAMBLE_COUNTRY (For Ruby use "::" for all "." when referencing constants)
                    String: countryAndSystemChars

                    Applies both system and country code preamble to the bar code.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upce0preamble
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upce0preamble
                      • Ruby: Rho::Barcode.upce0preamble

                    upce0reportCheckDigit : BOOLEAN 1.0.0

                    When true, the barcode check digit(s) will be reported for scanned UPCE0 barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upce0reportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upce0reportCheckDigit
                      • Ruby: Rho::Barcode.upce0reportCheckDigit

                    upce1 : BOOLEAN 1.0.0

                    Enables or disables the symbology for UPCE1 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upce1
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upce1
                      • Ruby: Rho::Barcode.upce1

                    upce1convertToUpca : BOOLEAN 1.0.0

                    When true, scanned UPCE1 barcodes will be converted to UPCA and UPCA parameters used.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upce1convertToUpca
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upce1convertToUpca
                      • Ruby: Rho::Barcode.upce1convertToUpca

                    upce1preamble : STRING 1.0.0

                    Controls the preamble applied to the UPCE1 barcode.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.UPCE1_PREAMBLE_NONE (For Ruby use "::" for all "." when referencing constants)
                    String: none

                    Applies no preamble to the bar code.

                    +
                    Constant: Rho.Barcode.UPCE1_PREAMBLE_SYSTEMCHAR (For Ruby use "::" for all "." when referencing constants)
                    String: systemChar

                    Applies system character preamble to the bar code.

                    +
                    Constant: Rho.Barcode.UPCE1_PREAMBLE_COUNTRY (For Ruby use "::" for all "." when referencing constants)
                    String: countryAndSystemChars

                    Applies both system and country code preamble to the bar code.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upce1preamble
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upce1preamble
                      • Ruby: Rho::Barcode.upce1preamble

                    upce1reportCheckDigit : BOOLEAN 1.0.0

                    When true, the barcode check digit(s) will be reported for scanned UPCE1 barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.upce1reportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.upce1reportCheckDigit
                      • Ruby: Rho::Barcode.upce1reportCheckDigit

                    us4state : BOOLEAN 1.0.0

                    Enables or disables the symbology for US 4-State barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.us4state
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.us4state
                      • Ruby: Rho::Barcode.us4state

                    us4stateFics : BOOLEAN 2.0.0

                    Enables or disables the symbology for US 4-State FICS barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.us4stateFics
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.us4stateFics
                      • Ruby: Rho::Barcode.us4stateFics

                    usPlanet : BOOLEAN 1.0.0

                    Enables or disables the symbology for US Planet barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.usPlanet
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.usPlanet
                      • Ruby: Rho::Barcode.usPlanet

                    usPlanetReportCheckDigit : BOOLEAN 1.0.0

                    When true, the barcode check digit(s) will be reported for scanned US Planet barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.usPlanetReportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.usPlanetReportCheckDigit
                      • Ruby: Rho::Barcode.usPlanetReportCheckDigit

                    usPostNet : BOOLEAN 1.0.0

                    Enables or disables the symbology for US Post Net barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.usPostNet
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.usPostNet
                      • Ruby: Rho::Barcode.usPostNet

                    usPostNetReportCheckDigit : BOOLEAN 1.0.0

                    When true, the barcode check digit(s) will be reported for scanned US Post Net barcodes.

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.usPostNetReportCheckDigit
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.usPostNetReportCheckDigit
                      • Ruby: Rho::Barcode.usPostNetReportCheckDigit

                    viewfinderFeedback : STRING 1.0.0

                    Configures the feedback given after a successful scan. This value is ignored if aimType is set to continuousRead and no feedback will be given. Not supported on Android with EMDK version 3.1 and above.

                    +

                    (Camera Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.VF_FEEDBACK_ENABLED (For Ruby use "::" for all "." when referencing constants)
                    String: enabled

                    The last image that was successfully decoded is displayed. The time for which the image is displayed can be configured by the viewfinderFeedbackTime parameter.

                    +
                    Constant: Rho.Barcode.VF_FEEDBACK_DISABLED (For Ruby use "::" for all "." when referencing constants)
                    String: disabled

                    No feedback is given in the viewfinder after a successful decode.

                    +
                    Constant: Rho.Barcode.VF_FEEDBACK_RETICLE (For Ruby use "::" for all "." when referencing constants)
                    String: reticle

                    The last image that was successfully decoded is displayed along with a red reticle in the center of the image. The time for which the image is displayed can be configured by the viewfinderFeedbackTime parameter.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.viewfinderFeedback
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.viewfinderFeedback
                      • Ruby: Rho::Barcode.viewfinderFeedback

                    viewfinderFeedbackTime : INTEGER 1.0.0

                    If the viewfinderFeedback:enabled or viewfinderFeedback:reticle are applied then the decoded barcode will remain on the screen for this duration, specified in milliseconds. Not supported on Android with EMDK version 3.1 and above.

                    +

                    (Camera Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.viewfinderFeedbackTime
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.viewfinderFeedbackTime
                      • Ruby: Rho::Barcode.viewfinderFeedbackTime

                    viewfinderHeight : INTEGER 1.0.0

                    When scanning a barcode using a Camera scanner the viewfinder preview window will be this number of pixels in height. The images displayed in the viewfinder will be scaled as appropriate.

                    +

                    (Camera Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.viewfinderHeight
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.viewfinderHeight
                      • Ruby: Rho::Barcode.viewfinderHeight

                    viewfinderMode : STRING 1.0.0

                    Configures the mode of the scanner viewfinder window. This attribute is not supported on all Scanners and will interact with the picklistMode parameter, see the EMDK for C help file for more information.

                    +

                    (Camera Scanners on Symbol Technologies' devices)

                    Possible Values (STRING):

                    Constant: Rho.Barcode.VIEWFINDER_ENABLED (For Ruby use "::" for all "." when referencing constants)
                    String: enabled

                    Only the viewfinder is enabled (not the reticle). Displays a viewfinder on the screen showing the image being captured by the camera.

                    +
                    Constant: Rho.Barcode.VIEWFINDER_DISABLED (For Ruby use "::" for all "." when referencing constants)
                    String: disabled

                    The viewfinder will not be displayed during aiming or scanning.

                    +
                    Constant: Rho.Barcode.VIEWFINDER_STATIC_RETICLE (For Ruby use "::" for all "." when referencing constants)
                    String: staticReticle

                    Displays the viewfinder as well as draws a red reticle in the center of the image which helps with tracking the barcode.

                    +
                    Constant: Rho.Barcode.VIEWFINDER_DYNAMIC_RETICLE (For Ruby use "::" for all "." when referencing constants)
                    String: dynamicReticle

                    Displays the viewfinder as well as draws a red reticle in the center of the image. If the barcode in the image is ‘decodable’ the reticle turns green to indicate this. This mode requires a second trigger press to decode the barcode after the reticle turns green. Not supported on Android.

                    +

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.viewfinderMode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.viewfinderMode
                      • Ruby: Rho::Barcode.viewfinderMode

                    viewfinderWidth : INTEGER 1.0.0

                    When scanning a barcode using a Camera scanner the viewfinder preview window will be this number of pixels wide. The images displayed in the viewfinder will be scaled as appropriate.

                    +

                    (Camera Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.viewfinderWidth
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.viewfinderWidth
                      • Ruby: Rho::Barcode.viewfinderWidth

                    viewfinderX : INTEGER 1.0.0

                    When scanning a barcode using a Camera scanner the viewfinder preview window will appear this number of pixels from the left hand side of the screen. The images displayed in the viewfinder will be scaled as appropriate.

                    +

                    (Camera Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.viewfinderX
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.viewfinderX
                      • Ruby: Rho::Barcode.viewfinderX

                    viewfinderY : INTEGER 1.0.0

                    When scanning a barcode using a Camera scanner the viewfinder preview window will appear this number of pixels from the top of the screen. The images displayed in the viewfinder will be scaled as appropriate.

                    +

                    (Camera Scanners on Symbol Technologies' devices)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.viewfinderY
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.viewfinderY
                      • Ruby: Rho::Barcode.viewfinderY

                    webcode : BOOLEAN 1.0.0

                    Enables or disables the symbology for Webcode barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. Deprecated in Android 4.1 (Jelly Bean).

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.webcode
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.webcode
                      • Ruby: Rho::Barcode.webcode

                    webcodeDecodeGtSubtype : BOOLEAN 2.0.0

                    If true, the GT Webcode subtype will be decoded. Deprecated in Android 4.1 (Jelly Bean).

                    +

                    (Not all scanning engines support all symbologies or all symbology properties)

                    Property Access:

                    • Instance: This property can be accessed via an instance object of this class:
                      • myObject.webcodeDecodeGtSubtype
                    • Default Instance: This property can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Barcode.webcodeDecodeGtSubtype
                      • Ruby: Rho::Barcode.webcodeDecodeGtSubtype
                    + +

                    Examples

                    + +
                    Scan barcodes with the default scanner
                    +

                    Getting started with barcode scanning is very straightforward. If you do not need to customize the defaults, you need very little code.

                    +
                    :::javascript
                    +
                    +           
                    +function scan_using_default_scanner(){
                    +  // Scan with default options
                    +  Rho.Barcode.take({}, scan_received);
                    +}
                    +
                    +function scan_received(params){
                    +  // Did we actually find a barcode ?
                    +  // If status is not 'ok', the scan was canceled
                    +
                    +    if (params["status"]=="ok") {
                    +        alert('Barcode scanning complete. Scanned barcode: '+params["barcode"]);
                    +    } else {
                    +        alert('Barcode scanning aborted');
                    +    }
                    +    Rho.Barcode.stop();
                    +}
                    +                   
                    +                 
                    :::ruby
                    +
                    +           
                    +def scan_using_default_scanner
                    +  # Scan with default options
                    +  Rho::Barcode.take({}, url_for(:action => :scan_received))
                    +end
                    +
                    +def scan_received
                    +  # Did we actually find a barcode ?
                    +  # If status is not 'ok', the scan was canceled
                    +  if @params["status"] == "ok"
                    +    Rho::Log.info(@params["barcode"],"Barcode result")
                    +  else
                    +    Rho::Log.info("canceled", "Barcode result")
                    +  end
                    +end
                    +                   
                    +                 
                    Select which scanner to use
                    +

                    By default, Rho::Barcode will select a hardware scanner if present on the device. If you want to let the user choose which scanner to use at any particular time, you must enumerate the available scanners and select one from the set.

                    +
                    :::javascript
                    +
                    +           
                    +var scanners;
                    +
                    +function choose_scanner(){
                    +
                    +  // Enumerate returns an array of scanner objects
                    +  // Devices without a hardware scanner will return a software-based recognizer
                    +  scanners = Rho.Barcode.enumerate();
                    +}
                    +
                    +function scan_using_chosen_scanner(scanner_index) {
                    +    var scanner = scanners[scanner_index];
                    +    scanner.take({}, scan_received_callback);
                    +}
                    +
                    +function scan_received_callback(params){
                    +  // Did we actually find a barcode?
                    +  // If status is not 'ok' the scan is canceled
                    +  if (params["status"]=="ok") {
                    +            alert('Barcode scanning complete. Scanned barcode: '+params["barcode"]);
                    +        } else {
                    +            alert('Barcode scanning aborted');
                    +        }
                    +        Rho.Barcode.stop();
                    +}
                    +                   
                    +                 
                    :::ruby
                    +
                    +           
                    +# ---------------
                    +# controller.rb
                    +# ---------------
                    +
                    +def choose_scanner
                    +  # Obtain list of available scanners on the system. Devices without a hardware scanner will return a software-based recognizer
                    +  $scanners = Rho::Barcode.enumerate
                    +  render
                    +end
                    +
                    +def scan_using_chosen_scanner
                    +  # receive an integer as parameter, which represent the number of the scanner we wish to use
                    +  scanner = $scanners[@params["scannerIndex"].to_i]
                    +  scanner.take({}, url_for(:action => :scan_received_callback))
                    +end
                    +
                    +def scan_received_callback
                    +  # Did we actually find a barcode ?
                    +  # If status is not 'ok', the scan was canceled
                    +  if @params["status"] == "ok"
                    +    Rho::Log.info(@params["barcode"],"Barcode result")
                    +  else
                    +    Rho::Log.info("canceled", "Barcode result")
                    +  end
                    +end
                    +
                    +
                    +# ---------------
                    +# choose_scanner.erb
                    +# ---------------
                    +<ul data-role="listview">
                    +  <% $scanners.each_with_index do |scanner, index| %>
                    +    <li><a href="<%= url_for(:action => :scan_using_chosen_scanner, :query => {:scanner_index => index}) %>"><%= scanner.friendlyName %></li>
                    +  <% end %>
                    +</ul>
                    +                   
                    +                 
                    Set recognized symbologies
                    +

                    Specify which symbologies the barcode scanner must recognize.

                    +
                    :::javascript
                    +
                    +           
                    +// For the purpose of this example, let's say our application only needs to recognize one type of barcode.
                    +// In that case, we will disable all decoders...
                    +Rho.Barcode.allDecoders = false;
                    +// ... and enable only the one we are interested in:
                    +Rho.Barcode.upca = true;
                    +// All other barcode symbologies will be ignored
                    +Rho.Barcode.take({}, scan_received_callback);
                    +                   
                    +                 
                    :::ruby
                    +
                    +           
                    +# For the purpose of this example, let's say our application only needs to recognize one type of barcode.
                    +# In that case, we will disable all decoders...
                    +Rho::Barcode.allDecoders = false
                    +# ... and enable only the one we are interested in:
                    +Rho::Barcode.upca = true
                    +# All other barcode symbologies will be ignored
                    +Rho::Barcode.take({}, url_for(:action => :scan_received_callback))
                    +
                    +                   
                    +                 
                    Control scanner properties
                    +

                    Examples of setting barcode scanner properties.

                    +
                    :::javascript
                    +
                    +           
                    +// There are over 200 properties to fine-tune the barcode scanner functionality and adapt it to suit your application.
                    +// Almost all properties depend on the scanner hardware for support, please check the documentation to see if your device
                    +// supports a particular setting
                    +
                    +// Here are examples of setting some of the properties. The documentation lists the acceptable values for each of them
                    +
                    +// Aiming mode (visual cue):
                    +Rho.Barcode.aimMode = "none";
                    +Rho.Barcode.aimMode = "dot";
                    +Rho.Barcode.aimMode = "slab";
                    +Rho.Barcode.aimMode = "reticle";
                    +
                    +// Aiming type (processing mode):
                    +Rho.Barcode.aimType = "trigger";
                    +Rho.Barcode.aimType = "timedHold";
                    +Rho.Barcode.aimType = "timedRelease";
                    +Rho.Barcode.aimType = "presentation";
                    +Rho.Barcode.aimType = "pressAndRelease";
                    +Rho.Barcode.aimType = "continuousRead";
                    +
                    +// Generate an "Enter" keypress after a barcode is recognized. Useful for sending forms automatically after a scan
                    +Rho.Barcode.autoEnter = true;
                    +
                    +// Select the beam width of the scanner (only supported on some devices)
                    +Rho.Barcode.beamWidth = "normal";
                    +Rho.Barcode.beamWidth = "narrow";
                    +Rho.Barcode.beamWidth = "wide";
                    +                   
                    +                 
                    :::ruby
                    +
                    +           
                    +# There are over 200 properties to fine-tune the barcode scanner functionality and adapt it to suit your application.
                    +# Almost all properties depend on the scanner hardware for support, please check the documentation to see if your device
                    +# supports a particular setting
                    +
                    +# Here are examples of setting some of the properties. The documentation lists the acceptable values for each of them
                    +
                    +# Aiming mode (visual cue):
                    +Rho::Barcode.aimMode = "none"
                    +Rho::Barcode.aimMode = "dot"
                    +Rho::Barcode.aimMode = "slab"
                    +Rho::Barcode.aimMode = "reticle"
                    +
                    +# Aiming type (processing mode):
                    +Rho::Barcode.aimType = "trigger"
                    +Rho::Barcode.aimType = "timedHold"
                    +Rho::Barcode.aimType = "timedRelease"
                    +Rho::Barcode.aimType = "presentation"
                    +Rho::Barcode.aimType = "pressAndRelease"
                    +Rho::Barcode.aimType = "continuousRead"
                    +
                    +# Generate an "Enter" keypress after a barcode is recognized. Useful for sending forms automatically after a scan
                    +Rho::Barcode.autoEnter = true
                    +
                    +# Select the beam width of the scanner (only supported on some devices)
                    +Rho::Barcode.beamWidth = "normal"
                    +Rho::Barcode.beamWidth = "narrow"
                    +Rho::Barcode.beamWidth = "wide"
                    +                   
                    +                 
                    Change audible options
                    +

                    You can customize or eliminate the beep that the device emits when a barcode is recognized. Support and valid ranges for these values depend on the device.

                    +
                    :::javascript
                    +
                    +           
                    +// Maximum volume (default)
                    +Rho.Barcode.decodeVolume = 5;
                    +// Low-pitched sound
                    +Rho.Barcode.decodeFrequency = 1000;
                    +// One-second long
                    +Rho.Barcode.decodeDuration = 1000;
                    +
                    +Rho.Barcode.take({}, scan_received_callback);
                    +                   
                    +                 
                    :::ruby
                    +
                    +           
                    +# Maximum volume (default)
                    +Rho::Barcode.decodeVolume = 5
                    +# Low-pitched sound
                    +Rho::Barcode.decodeFrequency = 1000
                    +# One-second long
                    +Rho::Barcode.decodeDuration = 1000
                    +
                    +Rho::Barcode.take({}, url_for(:action => :scan_received_callback))
                    +                   
                    +                 
                    + +

                    Remarks

                    + +
                    Bluetooth Scanner Overview

                    Once associated with the Device a Bluetooth Scanner will remain associated even after losing the BT connection. In order to associate a different Bluetooth scanner with the device it is necessary to scan the ‘unpairing’ barcode and then invoke the ‘disabled’ method followed by the ‘enabled’ method, this will allow you to scan the BT association barcode with a different scanner. You can override this default behavior using the disconnectBtOnDisable property.

                    + +

                    The following messages will be received from the Bluetooth Scanner in the bluetoothStatus event:

                    + +

                    ‘BTScanAssociationBarcode’

                    + +

                    Means the device is ready to be associated with a BT scanner. You must scan the +association barcode. It is only necessary to scan the association +barcode when you first associate a scanner with the device, this pairing will be remembered until +you scan the unpairing barcode.

                    + +

                    ‘BluetoothConnected’

                    + +

                    The remote scanner has successfully connected to the device.

                    + +

                    ‘BluetoothDisconnected’

                    + +

                    The remote scanner has become disconnected from the device, this may be due to loss of battery, being out +of range or scanning the ‘unpairing’ barcode. The scanner will attempt to reconnect automatically for +a period of time once it regains power or goes out of range, if it fails to reconnect after the specified +timeout the reconnect button on the device should be pushed. Once the unpairing barcode is scanned +it is necessary to disable the scanner and then re-enable it before another scanner can be associated.

                    +
                    Viewfinder Position Parameters

                    On Symbol Technologies' scanners the scanner viewfinder window is not infinitely resizable, when setting ViewFinderX, ViewFinderY, ViewFinderWidth and ViewFinderHeight ensure you do not exceed the size of the screen and it is recommended to use the same aspect ratio as your device. For applications designed to handle screen rotation it is recommended to use a scan window whose longest side will fit within both the screen width and screen height. If your viewfinder position fails to be applied it is recommended you query your log file to see which parameter is causing trouble, or reposition the window away from the edges of the screen.

                    +
                    Scanning and Camera Interaction

                    In some device configurations the scanner and camera share the same hardware. Where two modules share the same physical hardware they cannot be enabled simultaneously, in this circumstance once the scanner is enabled it must be disabled before the camera can be used, and vice versa.

                    +
                    Get Scanner Properties

                    On WM/CE, it is first necessary to enable the scanner before most of the properties can be retrieved. The case of scanner properties will differ across platforms. On WM/CE, some of the scanner properties are not exposed to set but can be retrieved. On Android, only supported scanner properties can be retrieved in “getAllProperties” method.

                    +
                    Set Scanner Properties

                    On WM/CE, for some properties, it is first necessary to apply those properties before enabling the scanner.

                    +
                    Android Camera Barcode limitation

                    As google barcode scanning library(Zxing library) supported only in Landscape mode. Barcode scanning window only appears at centre of screen in Landscape mode.

                    +
                    DataWedge Interaction With Native Apps

                    In order to use the scanner with RhoElements Native Apps you will need to either disable DataWedge or create a DataWedge profile for your app. +Disabling Datawedge

                    + +
                      +
                    1. Start the DataWedge app
                    2. +
                    3. Click the menu button > “Settings” and untick “DataWedge enabled”.
                    4. +
                    + + +

                    RhoElements Datawedge Profile

                    + +
                      +
                    1. Install your RhoElements native app,
                    2. +
                    3. Start the DataWedge app
                    4. +
                    5. Click the menu button > “New Profile” and enter a name,
                    6. +
                    7. Click on the link to the new profile in the profile list,
                    8. +
                    9. Click on “Associated apps” in the “Applications” section,
                    10. +
                    11. Click the menu button > “New app/activity”,
                    12. +
                    13. Select the package name for your app,
                    14. +
                    15. Select “*”,
                    16. +
                    17. Click the “Back” capacitive button,
                    18. +
                    19. Make sure the “Profile enabled” checkbox is ticked.
                    20. +
                    21. Uncheck all three “Enabled” checkboxes under the sections of: +“Barcode input”, “Keystroke output” and “Intent output”.
                    22. +
                    + +
                    + +

                    Licensing

                    + +
                    This API is considered a RhoElements API and therefore requires a paid subscription to use (either Silver or Gold level). You can review the subscription plans on our licensing page here or on rhomobile.com/pricing.
                    \ No newline at end of file diff --git a/docs/en/5.5/api/barcode.xml b/docs/en/5.5/api/barcode.xml new file mode 100644 index 00000000..c7fc2b91 --- /dev/null +++ b/docs/en/5.5/api/barcode.xml @@ -0,0 +1,2232 @@ + + + + + + + + + + The Barcode Module provides access to control the functionality of the device's scanner. Because RhoMobile Suite is designed to run on both Consumer devices and Symbol Technologies' enterprise devices support for the Barcode API will vary for each method and properties depending on which platform you are running on. Please note that a lot these APIs are optimized for the extended functionality that Symbol Technologies devices provide. Check the platform indicators in each property or method section. In general if you are developing for a consumer device the number of symbologies available to you will be limited to just the most common ones, eg EAN13, UPCA etc and your scanning will be via the device camera. If your application is running on Symbol Technologies' hardware you will have much finer control over a more fully featured Scanner, often with a choice of scanner hardware on the device. In general if you wish to capture a single barcode in a 'one shot' use case, eg your App just wants to capture a single barcode to be submitted to a price comparison website then use Barcode.take(callback); if your application is expecting a number of barcodes to be received, common in enterprise scenarios for example a user in a warehouse then use Barcode.enable(callback). The Barcode API will not run on non-Symbol Technologies Windows Mobile / CE devices.Only the foreground application is given access to the scanning hardware, when an application is sent to the background its state will be saved and it will automatically relinquish control of the scanner. When brought back to the foreground, an application previously using the barcode API will have its previous configuration reapplied automatically.In VC70 scanner will work only if connected in SSI Mode. In Symbol android devices, it is recommended to use EMDK for KitKat devices and not to use EMDK in JellyBean devices. + + The Barcode Module provides access to control the functionality of the device's scanner. Check the platform indicators in each property or method section. In general if you are developing for a device with only a camera, the number of symbologies available to you will be limited to just the most common ones, eg EAN13, UPCA etc and your scanning will be via the device camera. If your application is running on more traditional Symbol Technologies' hardware you will have much finer control over a more fully featured Scanner, often with a choice of scanner hardware on the device. In general if you wish to capture a single barcode in a 'one shot' use case, eg your App just wants to capture a single barcode to be submitted to a price comparison website then use Barcode.take(callback); if your application is expecting a number of barcodes to be received, common in enterprise scenarios for example a user in a warehouse then use Barcode.enable(callback). Only the foreground application is given access to the scanning hardware, when an application is sent to the background its state will be saved and it will automatically relinquish control of the scanner. When brought back to the foreground, an application previously using the barcode API will have its previous configuration reapplied automatically. A VC70 scanner will work only if connected in SSI Mode. + + + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["barcode"] + +The `barcode` extension is also included automatically if you specify the following in your `build.yml` + :::ruby + app_type: "rhoelements" + +NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + + +## Enabling the API +There are two methods of enabling the Barcode API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Barcode API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.barcode.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + These properties are used to configure the barcode scanner or barcode decoding algorithms, depending on your device. + + 1.0.0 + WM, CE, Android,WP8 + Scanners on Symbol Technologies' devices + When true, automatically appends the character code for 'enter' to the end of any barcodes scanned. This is useful if you want to submit forms following a scan without further interaction. This property will only take effect if you have not specified a callback to the enable method. AutoEnter and AutoTab are mutually exclusive properties. + + + 1.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices + When true, automatically appends the tab character to the end of any barcodes scanned. This is useful if you are populating a form and want to jump to the next field in the form without further interaction. This property will only take effect if you have not specified a callback to the enable method. AutoTab and AutoEnter are mutually exclusive properties. + + + 4.0.0 + Android + Scanners on Symbol Technologies' devices + Controls the haptic feedback on decode. This means that if this is set to true, then the device will vibrate when a decode occurs. + + + 1.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices + Describes the linear security level used during decoding. This determines the number of times a barcode must be read before it is decoded. If the successive reads of the barcode do not match, it will not be decoded. + + + Double redundancy based on redundancy flags and code length. Only applicable to laser scanners, not BlockBuster imager scanners. Not supported on Android with EMDK version 3.1 and above. + + + Double redundancy if short barcode or Codabar. + + + Double redundancy for long barcodes, triple for short barcodes. + + + Double redundancy for all barcodes. + + + Triple redundancy for all barcodes. + + + + + 1.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices + Maximum time in milliseconds that laser scanners will emit a beam or imager scanners will enable the imager. A value of 0 indicates an infinite timeout. This parameter is compatible with aimType:trigger, aimType:timedHold, aimType:timedRelease and aimType:pressAndRelease. Note that for regulatory reasons scanTimeout is not configurable on all laser / imager scanners. Scan timeout is extent to hardware capabilities and limitations. + + + 1.0.0 + Describes the type of vertical rastering to use. + Scanners on Symbol Technologies' devices + WM + + + No vertical rastering. + + + Vertical rastering is always full open. To adjust the rastering height use the rasterHeight property. + + + Vertical rastering mode is 'Smart'. + + + Vertical rastering mode is 'Cyclone'. + + + + + 1.0.0 + WM + Laser Scanners on Symbol Technologies' devices + Vertical rastering height to use, as a percentage, when rasterMode:openAlways is applied. This value must be between 0 and 100. + + + 1.0.0 + WM + Scanners on Symbol Technologies' devices + Describes the type of aiming to use. + + + Standard trigger mode. Holding the trigger will start a decoding session. + + + Aiming lasts for the time specified by 'timedAimDuration' before decoding. The opportunity to scan will last until the barcode is decoded or scanTimeout occurs. + + + Aiming lasts until trigger is released. If the timedAimDuration has expired when the trigger is released then a decode session is started until a barcode is decoded or for the remaining time equal to the scanTimeout value. + + + Provided to support Kiosk devices. The scanner illuminates when movement is detected in the range of the scanner window. In order to use this mode the scanner must be initiated with a softscan using the Rho.Barcode.start() method and again after each decode. The device must be equipped with a sensor to detect movement to use presentation mode. MK31XX devices come with presentation mode pre-enabled in the scanner driver and the aimType cannot be modified for these devices. + Provided to support Kiosk devices. The scanner illuminates when movement is detected in the range of the scanner window. In order to use this mode the scanner must be initiated with a softscan using the EB.Barcode.start() method and again after each decode. The device must be equipped with a sensor to detect movement to use presentation mode. MK31XX devices come with presentation mode pre-enabled in the scanner driver and the aimType cannot be modified for these devices. + + + Scan will continue after the trigger is released until scanTimeout occurs. + + + Once the trigger is pulled barcodes will continue to be scanned as long as the trigger is held, enabling rapid scanning, to be used in conjunction with sameSymbolTimeout and differentSymbolTimeout. This value is ignored if viewfinderMode is set to 'dynamicReticle' + + + + + 1.0.0 + WM + Scanners on Symbol Technologies' devices + Aim duration in milliseconds for aimType:timedHold and aimType:timedRelease. + + + 1.0.0 + WM + Scanners on Symbol Technologies' devices + When the aimType:continuousRead property is applied this value defines the interval between which the same barcode can be decoded twice. The value is specified in milliseconds, use 0 to indicate no interval between successive reads. Use this value to prevent accidental duplicate scans. + + + 1.0.0 + WM + Scanners on Symbol Technologies' devices + When the aimType:continuousRead property is applied this value defines the interval between which different barcodes can be scanned. The value is specified in milliseconds, use 0 to indicate no interval between successive reads. Use this setting to allow time for the operator to re-aim the device between successive scans. + + + 1.0.0 + WM + Scanners on Symbol Technologies' devices + Defines the aiming mode to use. + + + No Aiming (Can be overridden by picklistMode). + + + Laser barcode readers will show a dot for aiming. + + + Laser barcode readers will show a slab for aiming. + + + Imager barcode readers will show a reticle for aiming. + + + + + 1.0.0 + WM, CE, Android + Imager / Camera Scanners on Symbol Technologies' devices + Allows the imager to decode only the barcode that is directly under the cross-hair / center of the reticle. This feature is most useful in applications where multiple barcodes may appear in the field of view during a decode session and only one of them is targeted for decode. When enabled picklistMode will override aimMode or, if no aiming is chosen, and use aimMode:reticle. This mode will also interact with viewfinderMode, see the EMDK for C help file for more information. Enabling picklist mode may adversely affect overall decoding performance. + + + Disables picklist mode so any barcode within the field of view can be decoded. + + + Enables picklist mode so that only the barcode under the projected reticle can be decoded. On Windows, if the imager does not support a projected reticle then the behavior is the same as softwareReticle. On Android, this is only supported for Imager (non-viewfinder) based scanners. + + + Enables picklist mode so that only the barcode in the center of the image is decoded. This is most useful when used in conjunction with static and dynamic reticle viewfinder modes. This value is not supported on Android Platform. + + + + + 1.0.0 + WM, CE, Android + Camera Scanners on Symbol Technologies' devices + Configures the mode of the scanner viewfinder window. This attribute is not supported on all Scanners and will interact with the picklistMode parameter, see the EMDK for C help file for more information. + + + Only the viewfinder is enabled (not the reticle). Displays a viewfinder on the screen showing the image being captured by the camera. + + + The viewfinder will not be displayed during aiming or scanning. + + + Displays the viewfinder as well as draws a red reticle in the center of the image which helps with tracking the barcode. + + + Displays the viewfinder as well as draws a red reticle in the center of the image. If the barcode in the image is 'decodable' the reticle turns green to indicate this. This mode requires a second trigger press to decode the barcode after the reticle turns green. Not supported on Android. + + + + + 1.0.0 + WM + Camera Scanners on Symbol Technologies' devices + When scanning a barcode using a Camera scanner the viewfinder preview window will appear this number of pixels from the left hand side of the screen. The images displayed in the viewfinder will be scaled as appropriate. + + + 1.0.0 + WM + Camera Scanners on Symbol Technologies' devices + When scanning a barcode using a Camera scanner the viewfinder preview window will appear this number of pixels from the top of the screen. The images displayed in the viewfinder will be scaled as appropriate. + + + 1.0.0 + WM + Camera Scanners on Symbol Technologies' devices + When scanning a barcode using a Camera scanner the viewfinder preview window will be this number of pixels wide. The images displayed in the viewfinder will be scaled as appropriate. + + + 1.0.0 + WM + Camera Scanners on Symbol Technologies' devices + When scanning a barcode using a Camera scanner the viewfinder preview window will be this number of pixels in height. The images displayed in the viewfinder will be scaled as appropriate. + + + 1.0.0 + WM, CE, Android + Camera Scanners on Symbol Technologies' devices + Configures the feedback given after a successful scan. This value is ignored if aimType is set to continuousRead and no feedback will be given. Not supported on Android with EMDK version 3.1 and above. + + + The last image that was successfully decoded is displayed. The time for which the image is displayed can be configured by the viewfinderFeedbackTime parameter. + + + No feedback is given in the viewfinder after a successful decode. + + + The last image that was successfully decoded is displayed along with a red reticle in the center of the image. The time for which the image is displayed can be configured by the viewfinderFeedbackTime parameter. + + + + + 1.0.0 + WM, CE, Android + Camera Scanners on Symbol Technologies' devices + If the viewfinderFeedback:enabled or viewfinderFeedback:reticle are applied then the decoded barcode will remain on the screen for this duration, specified in milliseconds. Not supported on Android with EMDK version 3.1 and above. + + + 1.0.0 + WM + Imager / Camera Scanners on Symbol Technologies' devices + Sets the focus mode in use. + + + Use fixed focus. + + + Use auto focus. + + + + + 1.0.0 + WM, CE + Imager / Camera Scanners on Symbol Technologies devices + Selects the illumination mode to use. Not currently supported on Android (illumination is always on). + + + Auto-exposure algorithms will decide whether illumination is required. Not currently supported on Android. + + + External illumination is always on. + + + External illumination is always off. + + + + + 1.0.0 + WM + Imager / Camera Scanners on Symbol Technologies' devices. The scanning engine must support DPM barcodes. + Allows Direct Part Marking (DPM) barcodes to be read When true, but may adversely affect overall decoding performance. DPM is a way of stamping barcodes directly on physical objects and is only available on DPM terminals. + + + 1.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices. The scanning engine must support inverse barcodes + Allows the user to select inverse 1D barcodes for decoding. + + + Inverse 1D symbology decoding is enabled. + + + Inverse 1D symbology decoding is disabled. + + + Allows decoding of both positive and inverse 1D symbologies. + + + + + 1.0.0 + WM + Imager / Camera Scanners on Symbol Technologies' devices + Allows poor quality 1D barcodes to be read When true, but this will adversely affect the overall decoding performance. + + + 2.1.0 + WM + Laser Scanners on Symbol Technologies' devices + Specifies the width of the laser beam. All devices will support normal beam widths but other widths may not be supported on your device. + + + Laser beam width is normal. + + + Laser beam width is wide. + + + Laser beam width is narrow. + + + + + 1.0.0 + WM + Laser Scanners on Symbol Technologies' devices + Describes the type of Digital Bar Pulse (DBP) being produced by the scan engine. + + + Tells the scan engine to produce normal DBP. + + + Tells the scan engine to produce composite DBP, which is 2 different sets of DBP data multiplexed together for better decode performance. In order to enable this mode it must be supported by the scanner. + + + + + 1.0.0 + WM + Laser Scanners on Symbol Technologies' devices + Enables or disables the Klasse Eins laser on time function. + + + 1.0.0 + WM + Laser Scanners on Symbol Technologies' devices + Enables or disables adaptive scanning. When set to true, the scan engine will automatically toggle between 2 scan angles, wide and narrow, allowing the scan engine to decode barcodes both in close proximity and far away (~100 inches). Adaptive scanning is only supported in high performance, long working range scan engines such as SE960. + + + 1.0.0 + WM + Laser Scanners on Symbol Technologies' devices + Enables or disables bidirectional redundancy. + + + 2.1.0 + WM + Camera / Imager Scanners on Symbol Technologies' devices + Specifies the format in which the barcode data is returned, binary data is returned in Data URI format with the appropriate mime type. This parameter is designed to be used primarily with image based symbologies (eg. Signature). Binary data will not be output as keystrokes, you must set a decode callback in order to receive scanned data. + + + Scanned data will be returned in Data URI format. + + + Scanned data will be returned in Text format. + + + + + 2.1.0 + WM + Scanners on Symbol Technologies' devices + Specifies the number of bytes allocated to receive the scanned barcode. This parameter is designed to be used primarily with image based symbologies and should not be modified unless absolutely necessary (eg. Signature). + + + 1.0.0 + WM + Bluetooth Scanners on Symbol Technologies' devices + Specifies the time, in seconds, that an external scanner will be allowed to remain idle before the connection is terminated to conserve power. + + + 1.0.0 + WM + Bluetooth Scanners on Symbol Technologies' devices + Forces the scanner to disconnect from the terminal when it is 'disabled'. Since the scanner is disabled when you navigate to a new page, set this value to false if you want to maintain the bluetooth connection to your remote scanner. + + + 2.1.0 + WM + Bluetooth Scanners on Symbol Technologies' devices + If set to true the bluetooth address will be displayed as a barcode on the screen during the pairing process, initiated by calling 'enable' on a bluetooth scanner. Not all devices support this functionality. Note you must specify this parameter before or within the call to 'enable'. + + + 2.1.0 + WM + Bluetooth Scanners on Symbol Technologies' devices + Configures the time (in seconds) allowed to pair with the external bluetooth scanner after calling the 'enable()' method. You must specify this parameter before calling 'enable' to change the default. + + + 4.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices + Returns the friendly name associated with the scanner. + + + 4.0.0 + Android + Scanners on Symbol Technologies' devices + Controls whether LCD Mode is enabled on the scanner. LCD Mode makes it easier to scan barcodes off of LCD screens (like mobile device screens) + + + 1.0.0 + WM + Scanners on Symbol Technologies' devices + Set to false to disable scanning when the battery is low / critical or set to true to enable it. + + + 4.1.0 + WM + Scanners on Symbol Technologies' devices + Only applies to an enabled laser or imaging scanner. Disconnecting the trigger will prevent the scan beam from being emitted, this can temporarily prevent a user from scanning without having to disable the scanner, which can take longer. By default the trigger will be connected when the scanner is first enabled, you do not have to connect it separately. Please note that disconnecting the trigger will also prevent the start method from emitting a laser. This property will only affect the scanner and will have no effect on the 'captureTrigger' API. + + + 4.0.0 + WM + Scanners on Symbol Technologies' devices + By default if you have enabled the Scanner on a page, through either JavaScript or Ruby and navigate to a new page the Scanner will automatically disable. To override this behavior you can set this option to false and once enabled the Scanner will remain so in the foreground application until you disable it. + + + 4.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices + The volume of the device beeper when a barcode is scanned. Volume specified using 0 to 5, with 5 being the loudest. The value of 0 is device dependent, some Windows Mobile / CE devices interpret this as the quietest volume; if you wish to completely disable the beeper on scan please set decodeSound to an empty or invalid sound file. + + + 4.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices + The duration of the device beeper when a barcode is scanned, in milliseconds. + + + 4.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices + The frequency of the device beeper when a barcode is successfully decoded. This should be within the range of the beeper but the API will accept values in the range 0 to 65535. + + + 4.0.0 + WM + Scanners on Symbol Technologies' devices + The frequency of the device beeper when a barcode is scanned but not successfully decoded. This should be within the range of the beeper but the API will accept values in the range 0 to 65535. + + + 4.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices + Path to a local wave file to be played when the scanner successfully decodes a barcode. This setting overrides the scanner beeper. In Android, this settings will not override beeper and hence not supported. + + + 4.0.0 + WM + Scanners on Symbol Technologies' devices + Path to a local wave file to be played when a barcode is scanned but not successfully decoded. This setting overrides the scanner beeper. + + + 4.0.0 + WM, CE, Android, WP8 + All Scanners + The type of scanner in use, will be one of 'Camera', 'Imager' or 'Laser'. Camera scanners capture and process an image taken via the devices camera. Imager scanners rely on capturing and processing an image of the barcode via dedicated scanning hardware. Both camera and imager scanners are capable of decoding 1D and 2D barcodes. Laser scanners are only capable of decoding 1D barcodes and rely on a sweeping laser. + + + 1.0.0 + WM, CE, Android + Scanners on Symbol Technologies' devices + When set to true, the barcode scanner will read all barcode types that the scanner is capable of reading. When set to false, the barcode scanner will not be able to decode any symbologies, this is most useful if you want to set the scanner to a default state before only enabling your required symbologies. The fewer symbologies that are enabled the faster the decoding performance of the scanning engine will be. This property will return true only if all supported symbologies by the scanner are enabled, if only a subset of supported symbologies are enabled then false will be returned. Note that some decoders will not be enabled as some symbologies use the same systems to encode data, making it impossible to differentiate between them. For example: "canpostal" and "auspostal" both use a 4-state system, so devices will only enable either "canpostal" OR "auspostal" when "alldecoders" is enabled. Note that other symbologies also share the 4-state system. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Aztec barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Chinese 2of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Codabar barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables Codabar CLSi formatting when set to true. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a Codabar barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a Codabar barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables Codabar NotisEditing formatting when set to true. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Codabar Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Code11 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies whether to verify 0, 1 or 2 check digits. + + + Scanning engine will verify no Code 11 check digits. + + + Scanning engine will verify one Code 11 check digit. + + + Scanning engine will verify two Code 11 check digits. + + + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a Code 11 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a Code 11 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Code 11 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned Code 11 barcodes. + + + 1.0.0 + WM, CE, Android + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Code128 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, decodes concatenated Code128 output only if the pair belongs to one of the commonly concatenated pairs as defined by the standard. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, barcodes with the EAN128 subtype property set will be read. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, barcodes with the isbt128 subtype property set will be read. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Code128 ISBT concatenation mode property. This feature allows a pair of barcodes which meet certain criteria defined in the ISBT128 spec to be reported as a single barcode. This parameter describes the different concatenation modes available for ISBT128. + + + Will ignore the barcode pair and only output decode data for one of the barcodes. + + + Will not decode if both barcodes are not present or if one of them can not be decoded. + + + Auto-Discriminate. + + + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a Code 128 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a Code 128 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the other 128 property which enables the non EAN and non ISBT 128 subtype. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Code 128 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Code 128 security level and accepts a value between 0 and 3 inclusive. 0: Allows the scanner to operate in its most aggressive state, while providing sufficient security in decoding most 'in-spec' barcodes. 1: Eliminates most mis-decodes. 2: Select this option if security level 1 fails to eliminate mis-decodes. 3: Select this option if security level 1 and 2 fail to eliminate mis-decodes. Be advised that selecting level 3 is an extreme measure against mis-decoding and will significantly impair the decoding ability of the scanner. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Composite AB barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Describes whether UCC link mode is enabled. + + + Link flag is ignored. + + + Composite AB barcodes are always linked. + + + Auto-discriminate whether Composite AB barcodes are linked. + + + + + 2.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + This setting causes the UPC rules specified in the UPC EAN parameters to be used when reporting composite decode data. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Composite C barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Code 39 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables reporting of the Code32 prefix when a Code39 barcode is converted. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables conversion from Code39 to Code 32 barcodes, when set the decoded barcode is converted to Code 32. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables full ASCII conversion of Code 39 barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a Code 39 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a Code 39 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Code 39 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables reporting of the Code 39 check digit when a Code 39 barcode is scanned. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Code 128 security level and accepts a value between 0 and 3 inclusive. 0: This setting allows the scanner to operate in its most aggressive state, while providing sufficient security in decoding most 'in-spec' barcodes. 1: This setting eliminates most mis-decodes. 2: Select this option if security level 1 fails to eliminate mis-decodes. 3: Select this option if security level 1 and 2 fail to eliminate mis-decodes. Be advised that selecting level 3 is an extreme measure against mis-decoding and will significantly impair the decoding ability of the scanner. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Turns on verification of the Code 39 check digit. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Code 93 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a Code 93 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a Code 93 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Code 93 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for D2of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a D2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a D2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the D2of5 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Datamatrix barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for EAN 13 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for EAN 8 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, EAN 8 barcodes will be converted to EAN 13 and EAN 13 parameters used. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for I2of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, EAN 8 barcodes will be converted to EAN 13 and EAN 13 parameters used. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a I2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a I2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the I2of5 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned I2of5 barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables the verification of the I2of5 check digit. + + + Disables verification of the check digit. + + + Enables the USS format for the check digit. + + + Enables the OPCC format for the check digit. + + + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Korean 3of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + Sets Korean 3of5 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 1.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a Korean 3of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a Korean 3of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Macro PDF barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 2.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + When true, the scanner driver will return he barcode data only after the complete macroPdf sequence has been read. If false, the scan driver will return each barcode in the macroPdf sequence as it is read. + + + 2.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + If true, MacroPDF barcodes will be converted to PDF417 codes. + + + 2.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + If true, the scanner driver will not complete read requests while in the middle of a macroPdf sequence. Once a macroPdf sequence has been started it must be completed or canceled before the scan driver will complete other read requests. + + + 1.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for MacroMicroPDF barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 2.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + If true, the scanner driver will return the barcode data only after the complete macroMicroPdf sequence has been read. If false, the scanner driver will return each barcode in the macroMicroPdf sequence as it is read. + + + 2.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + If true, MacroMicroPDF barcodes will be converted to MicroPDF codes. + + + 2.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + If true, the scanner driver will not complete read requests while in the middle of a macroMicroPdf sequence. Once a macroMicroPdf sequence has been started it must be completed or canceled before the scan driver will complete other read requests. + + + 2.0.0 + WM + Not all scanning engines support all symbologies or all symbology properties + If true, the appended info is concatenated to the decoded data before being returned. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Matrix 2of5 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a Matrix 2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a Matrix 2of5 barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned Matrix 2of5 barcodes. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables verification of the Matrix 2of5 symbology check digit. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Maxicode barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Micro PDF barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Micro QR barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for MSI barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the number of MSI check digits to use. + + + Use one check digit for MSI barcodes. + + + Use two check digits for MSI barcodes. + + + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the check digit scheme used to verify MSI barcodes. + + + The first check digit is MOD 11, the second is MOD 10. + + + Both check digits are MOD 10. + + + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the maximum number of allowable characters in a MSI barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the minimum number of allowable characters in a MSI barcode. If your application only expects barcode lengths in a certain range, reducing the allowed range can improve scanning performance. Allowed values are 0 to 55. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the MSI Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned MSI barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for PDF 417 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 2.1.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Signature barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. Signature barcodes return their data in Data URI format, it is recommended you adjust the dataBufferSize and barcodeDataFormat properties when scanning Signature barcodes. + + + 2.1.0 + WM + Not all scanning engines support all symbologies or all symbology properties + Specifies the output height of the captured signature barcode. Signature barcodes return their data in Data URI format, it is recommended you adjust the dataBufferSize and barcodeDataFormat properties when scanning Signature barcodes. Provide a number greater than or equal to 20. + + + 2.1.0 + WM + Not all scanning engines support all symbologies or all symbology properties + Specifies the output width of the captured signature barcode. Signature barcodes return their data in Data URI format, it is recommended you adjust the dataBufferSize and barcodeDataFormat properties when scanning Signature barcodes. Provide a number greater than or equal to 20. + + + 2.1.0 + WM + Not all scanning engines support all symbologies or all symbology properties + Specifies the output quality of the captured signature barcode. Signature barcodes return their data in Data URI format, it is recommended you adjust the dataBufferSize and barcodeDataFormat properties when scanning Signature barcodes. Provide a value between 10 and 100 inclusive. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Australian Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Canadian Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Dutch Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Japanese Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for UK Postal barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned UK Postal barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for US 4-State barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for US 4-State FICS barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for US Planet barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned US Planet barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for US Post Net barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned US Post Net barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for QR Code barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 2.1.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for GS1 DataBar barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. This symbology was previously known as rss. + + + 2.1.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for GS1 Databar Expanded barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. This symbology was previously known as rssExp. + + + 2.1.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for GS1 Databar Limited barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. This symbology was previously known as rssLim. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for TLC 39 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Trioptic 39 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Trioptic 39 Redundancy property, if set the barcode must be decoded twice before being accepted. This will slow scanning but improve reliability. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables decoding of UPC EAN Bookland barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Specifies the bookland format to use when decoding UPC EAN Bookland barcodes. + + + Causes 978 bookland barcodes to be reported in 10 digit mode. + + + Causes 978/979 bookland barcodes to be transmitted as EAN13 as per 2007 ISBN-13 protocol. + + + + + 2.1.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + If true, RSS barcodes will be converted to UPC/EAN format. For this setting to work UPC/EAN symbologies must be enabled. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables decoding of UPC EAN Coupon barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the linear decode property. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, enables random weight check digit verification. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the retry count for auto-discriminating for supplementals. The value must be between 2 - 20 inclusive. + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Sets the Security level for decoding UPC EAN barcodes and accepts a value between 0 and 3 inclusive. 0: This setting allows the scanner to operate in its most aggressive state, while providing sufficient security in decoding most 'in-spec' barcodes. 1: This setting eliminates most mis-decodes. 2: Select this option if security level 1 fails to eliminate mis-decodes. 3: Select this option if security level 1 and 2 fail to eliminate mis-decodes. Be advised that selecting level 3 is an extreme measure against mis-decoding and will significantly impair the decoding ability of the scanner. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, enables the supplemental barcode decoding. Note you must have upcEanSupplementalMode:always set for this parameter to take effect. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, enables the supplemental barcode decoding. Note you must have upcEanSupplementalMode:always set for this parameter to take effect. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Describes the UPC EAN Supplemental mode. + + + Supplementals are ignored. + + + Auto-discriminates supplementals. + + + Will not decode upc/ean without supplementals. + + + The decoder will return the decoded value of the main block right away if it does not belong to any of the supplemental types. If the barcode starts with one of the prefixes it will search the image more aggressively for a supplemental. The scanner will try to scan the supplemental if it is present but if that fails, the main barcode will be returned. + + + Auto-discriminates supplemental for upc/ean codes starting with 378 or 379. Will disable reading of supplementals for any other upc/ean barcodes not starting with these values. The supplemental will be scanned if present but if scanning fails then the main barcode will be returned. + + + Auto-discriminates supplemental for upc/ean codes starting with 978 or 979. Will disable reading of supplementals for any other upc/ean barcodes not starting with these values. The supplemental will be scanned if present but if scanning fails then the main barcode will be returned. + + + Auto-discriminates supplemental for upc/ean codes starting with 414 or 419 or 434 or 439. Will disable reading of supplementals for any other upc/ean barcodes not starting with these values. The supplemental will be scanned if present but if scanning fails then the main barcode will be returned. + + + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for UPCA barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Controls the preamble applied to the UPCA barcode. + + + Applies no preamble to the bar code. + + + Applies system character preamble to the bar code. + + + Applies both system and country code preamble to the bar code. + + + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned UPCA barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for UPCE0 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, scanned UPCE0 barcodes will be converted to UPCA and UPCA parameters used. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Controls the preamble applied to the UPCE0 barcode. + + + Applies no preamble to the bar code. + + + Applies system character preamble to the bar code. + + + Applies both system and country code preamble to the bar code. + + + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned UPCE0 barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for UPCE1 barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, scanned UPCE1 barcodes will be converted to UPCA and UPCA parameters used. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Controls the preamble applied to the UPCE1 barcode. + + + Applies no preamble to the bar code. + + + Applies system character preamble to the bar code. + + + Applies both system and country code preamble to the bar code. + + + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + When true, the barcode check digit(s) will be reported for scanned UPCE1 barcodes. + + + 1.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + Enables or disables the symbology for Webcode barcodes. If your application does not expect to scan this symbology you should disable it to improve scanning performance. Deprecated in Android 4.1 (Jelly Bean). + + + 2.0.0 + WM, CE, Android + Not all scanning engines support all symbologies or all symbology properties + If true, the GT Webcode subtype will be decoded. Deprecated in Android 4.1 (Jelly Bean). + + + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Ring scanner model number. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Ring scanner serial number. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Ring scanner date of manufacture as DDMMYY. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Ring scanner date of service as DDMMYY. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Bluetooth address as FF:FF:FF:FF:FF:FF where FF is a hex number. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Scanner's operating system version. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + The device class of the ring scanner. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Indicates the status of the remote scanner's battery, will be one of 'unknown', 'full', 'medium', 'empty', 'chargingFullRate', 'chargingHalfRate', 'chargingTrickle' or 'discharging' + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + The remaining capacity of the battery, in the range 0 to 100. 'unknown' will be returned if the capacity could not be determined, for example if the scanner had no battery. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + One of 'simple', 'double', 'disabled' or 'unknown' + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + True if authentication is required. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + True if encryption is required. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Up to 5 character PIN code used for Bluetooth authentication. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + 'UseStored' will use the PIN code stored in the memory of the ring scanner, by default '12345'. 'PromptUser' indicates that the ring scanner should be used to scan 5 alpha numeric barcodes to define the PIN, eg. "1", "2", "3", "4", "5" (for PIN 12345). This parameter is not saved permanently on the ring scanner. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + How long the scanner tries to re-establish connection if it goes out of range, in seconds. This value must be a multiple of 5 and in the range 30 to 60 seconds. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + When true, scanner will emit 5 beeps every 5 seconds whilst re-connection in progress. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + 'neverReconnect', 'reconnectOnData' or 'reconnectImmediately' + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Friendly Bluetooth name, e.g. 'MyBTScanner' + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + To use a general inquiry mode, 'general' else, 'limited' + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Bluetooth reconnection scheme. + + + No scheme. + + + When powered on. + + + When device goes out of range. + + + When powered on or when the device goes out of range. + + + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Force saving the barcode assigned to the device to which the scanner has been paired. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Whether or not the ring scanner should give a low battery indication. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Low battery indication cycle time, in seconds. Must be one of 15, 30, 60, 90 or 120. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + The laser scan line width, 'wide' or 'narrow'. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Delay between good scans in proximity continuous mode, measured in milliseconds. Range 0 to 15000. This value must be a multiple of 100. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + If true, the remote scanner beeps and illuminates its green LED on a successful decode. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Feature for ignoring Code 128 barcodes beginning with 420 and 421. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Scanner trigger will wakeup the device from a low power state. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + If you press the trigger on an RSM scanner, proximity enabled will be turned off, even though it still reports its self as being turned on if you query the property. In order to use ProximityEnable you need to also have Mems enabled, this is the motion sensor and if you disable Mems the scanner will not function. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + If you press the trigger on an RSM scanner, proximity enabled will be turned off, even though it still reports its self as being turned on if you query the property. In order to use ProximityEnable you need to also have Mems enabled, this is the motion sensor and if you disable Mems the scanner will not function. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Proximity continuous mode. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Specify the distance for the proximity feature as 'short', 'medium' or 'long' + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Specify whether paging the device is enabled. + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Range 0 to 15 to specify the pattern for the paging beep sequence. + + + + + + Used to gain access to all scanner objects present on the device. For consumer devices you will most likely only have a single scanner, your device's camera but Enterprise grade hardware may have two or more scanners attached. + + This method replaces Barcode.enumerate from RhoElements 2.2 and takes a different prototype. Enumerate now returns an array of objects which can be used to control the specific scanner instance whereas previously it took a callback which returned the 'name' and 'id' of scanners present on the device. + Returns an array of objects which can be used to control the specific scanner instance whereas previously, it took a callback which returned the 'name' and 'id' of scanners present on the device. + + WM, CE, Android, iOS,WP8 + Android, WM, CE + + Array of Barcode objects, one for each hardware scanner on the device. Methods and properties can be set separately on each scanner but if you are using one scanner you must first disable it before being able to use another scanner on the same device. + + + + + 1.0.0 + Symbol Technologies' Scanners which support a hardware or software trigger to invoke the scan. + WM, CE,Android + Enabling the scanner puts it in a state where it will respond to the trigger (on devices with a hardware trigger) or will accept a command to initiate a soft scan (start method). Scanned barcodes will be available to the application through the callback provided to this method. Only one scanner on the device can be enabled at any one time, to switch between the imager and camera scanners (for example) then first disable the currently enabled scanner. If you do not specify a callback to this method you will received the scanned data as keystrokes. Note that it is necessary to enable the scanner on WM/CE devices prior to being able to retrieve the state of properties. + + This method replaces Barcode.enable from RhoElements 2.2 and takes a different prototype, no longer taking a 'deviceName' parameter this method can now be called on the individual scanner instances returned by Barcode.enumerate to control which hardware scanner on the device is enabled. Please consider using Barcode.take if you only require a 'single shot' scan and Barcode.enable if your user will be using the trigger to return scan events. + Enables the specified device specified by the propertyMap hash. Consider using Barcode.take if you only require a 'single shot' scan and Barcode.enable if your user will be using the trigger to return scan events. + + + + Provide a set of properties to configure the scanner, for example enable specific symbologies or check digits. + + Not providing properties to this function will use the scanner's default properties, or those previously set on the Scanner instance. + + + + + Not providing a callback to be invoked when a barcode is scanned will result in that barcode being output as keystrokes. + + + The data decoded by the scanner or imaging device. + + + The source device and human readable decoder type of the decoded barcode or symbol. + + + Hex value representing the decoder type. + + + The time at which the decode occurred (hh:mm:ss) + + + The length of the decoded barcode or symbol. + + + The direction the barcode was scanned, either forward, reverse or unavailable. + + + + + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + If you are using an RS507 barcode scanner you can register to receive connected or disconnected events through this method. + + + + The message describing the bluetooth connection: BluetoothConnected, BluetoothDisconnected or BTScanAssociationBarcode. See below for further descriptions. + + + + + + + 1.0.0 + Symbol Technologies' scanners + Performs a soft trigger start, initiating a scan without pressing the hardware trigger. If the scan does not result in a decode it is necessary to perform a soft stop before another soft start. + WM, CE,Android + + + + 1.0.0 + Symbol Technologies' scanners + Performs a soft trigger stop. + WM, CE,Android + + + + 1.0.0 + Symbol Technologies' scanners + Disables the barcode scanner. This reverts the scanner to its default state and flushes any current decoder settings. + WM, CE,Android + + + + 1.0.0 + iOS, Android + Android + iOS/Android software recognizer + Recognizes a barcode on an image. Returns a string with recognized code, or empty string if the barcode is not recognized. + + + Path to the image that contains the barcode to be recognized. + + + + String with recognized code, or empty string if the barcode is not recognized. + + + + + Return array of properties supported by this scanner. + Symbol Technologies' scanners + + Array of property names supported by this scanner. + + + + + + 1.0.0 + Enable the scanner and start capturing the barcode automatically. On Symbol Technologies' devices the amount of time to scan the barcode is defined by the scanTimeout property. On iPhone and Android if a barcode is found, the user can confirm barcode recognition, or continue to try to recognize the barcode. When the user confirms or cancels, the callback is called. Once the callback has been called the barcode hardware is disabled.This method will work only on scanners which support soft scan. + Enable the scanner and start capturing the barcode automatically. On Symbol Technologies' devices the amount of time to scan the barcode is defined by the scanTimeout property. On Android if a barcode is found, the user can confirm barcode recognition, or continue to try to recognize the barcode. When the user confirms or cancels, the callback is called. Once the callback has been called the barcode hardware is disabled.This method will work only on scanners which support soft scan. + WM, CE, Android, iOS,WP8 + Android, WM, CE + + + Provide a set of properties to configure the scanner, for example enable specific symbologies or check digits. + + Not providing properties to this function will use the scanner's default properties, or those previously set on the Scanner instance. + + + + + + + The data decoded by the scanner or imaging device. + + + Whether or not the barcode was successfully scanned, status will be 'ok' or 'cancel' + + + + + + + 1.0.0 + iOS/Android software recognizer + iOS,WP8 + Deprecated old method for Barcode.take(). + + + Ruby callback URL. + + + Provide a set of properties to configure the scanner, for example enable specific symbologies or check digits. + + Not providing properties to this function will use the scanner's default properties, or those previously set on the Scanner instance. + + + + + + + 4.0.0 + WM + Symbol Technologies' Bluetooth barcode scanners, model RS507 + Instruct the connected RS507 scanner to perform some action. + + + The action the RS507 scanner should perform, can be 'Disconnect' which disconnects the bluetooth RS507; 'unpair' which unpairs the RS507 from the device for association with another device; 'StartPaging' or 'StopPaging' which will cause the RS507 scanner to start or stop emitting a beep, to allow it to be located. + + + + + + + 1.0.0 + Android, iOS, WM + Android, WM + + + +Once associated with the Device a Bluetooth Scanner will remain associated even after losing the BT connection. In order to associate a different Bluetooth scanner with the device it is necessary to scan the 'unpairing' barcode and then invoke the 'disabled' method followed by the 'enabled' method, this will allow you to scan the BT association barcode with a different scanner. You can override this default behavior using the disconnectBtOnDisable property. + +The following messages will be received from the Bluetooth Scanner in the bluetoothStatus event: + +**'BTScanAssociationBarcode'** + +Means the device is ready to be associated with a BT scanner. You must scan the +association barcode. It is only necessary to scan the association +barcode when you first associate a scanner with the device, this pairing will be remembered until +you scan the unpairing barcode. + +**'BluetoothConnected'** + +The remote scanner has successfully connected to the device. + +**'BluetoothDisconnected'** + +The remote scanner has become disconnected from the device, this may be due to loss of battery, being out +of range or scanning the 'unpairing' barcode. The scanner will attempt to reconnect automatically for +a period of time once it regains power or goes out of range, if it fails to reconnect after the specified +timeout the reconnect button on the device should be pushed. Once the unpairing barcode is scanned +it is necessary to disable the scanner and then re-enable it before another scanner can be associated. + + + + +On Symbol Technologies' scanners the scanner viewfinder window is not infinitely resizable, when setting ViewFinderX, ViewFinderY, ViewFinderWidth and ViewFinderHeight ensure you do not exceed the size of the screen and it is recommended to use the same aspect ratio as your device. For applications designed to handle screen rotation it is recommended to use a scan window whose longest side will fit within both the screen width and screen height. If your viewfinder position fails to be applied it is recommended you query your log file to see which parameter is causing trouble, or reposition the window away from the edges of the screen. + + + + + In some device configurations the scanner and camera share the same hardware. Where two modules share the same physical hardware they cannot be enabled simultaneously, in this circumstance once the scanner is enabled it must be disabled before the camera can be used, and vice versa. + + + + On WM/CE, it is first necessary to enable the scanner before most of the properties can be retrieved. The case of scanner properties will differ across platforms. On WM/CE, some of the scanner properties are not exposed to set but can be retrieved. On Android, only supported scanner properties can be retrieved in "getAllProperties" method. + + + + On WM/CE, for some properties, it is first necessary to apply those properties before enabling the scanner. + + + + As google barcode scanning library(Zxing library) supported only in Landscape mode. Barcode scanning window only appears at centre of screen in Landscape mode. + + + + In order to use the scanner with RhoElements Native Apps you will need to either disable DataWedge or create a DataWedge profile for your app. +**Disabling Datawedge** + +1. Start the DataWedge app +2. Click the menu button > "Settings" and untick "DataWedge enabled". + +**RhoElements Datawedge Profile** + +1. Install your RhoElements native app, +2. Start the DataWedge app +3. Click the menu button > "New Profile" and enter a name, +4. Click on the link to the new profile in the profile list, +5. Click on "Associated apps" in the "Applications" section, +6. Click the menu button > "New app/activity", +7. Select the package name for your app, +8. Select "*", +9. Click the "Back" capacitive button, +10. Make sure the "Profile enabled" checkbox is ticked. +11. Uncheck all three "Enabled" checkboxes under the sections of: + "Barcode input", "Keystroke output" and "Intent output". + + + + + + + +
                    + Getting started with barcode scanning is very straightforward. If you do not need to customize the defaults, you need very little code. + + + :scan_received)) +end + +def scan_received + # Did we actually find a barcode ? + # If status is not 'ok', the scan was canceled + if @params["status"] == "ok" + Rho::Log.info(@params["barcode"],"Barcode result") + else + Rho::Log.info("canceled", "Barcode result") + end +end + ]]> + + + + + +
                    +
                    +
                    + + +
                    + By default, Rho::Barcode will select a hardware scanner if present on the device. If you want to let the user choose which scanner to use at any particular time, you must enumerate the available scanners and select one from the set. + + + :scan_received_callback)) +end + +def scan_received_callback + # Did we actually find a barcode ? + # If status is not 'ok', the scan was canceled + if @params["status"] == "ok" + Rho::Log.info(@params["barcode"],"Barcode result") + else + Rho::Log.info("canceled", "Barcode result") + end +end + + +# --------------- +# choose_scanner.erb +# --------------- + + ]]> + + + + + +
                    +
                    +
                    + + +
                    + Specify which symbologies the barcode scanner must recognize. + + + :scan_received_callback)) + + ]]> + + + + + +
                    +
                    +
                    + + +
                    + Examples of setting barcode scanner properties. + + + + + + + + +
                    +
                    +
                    + + +
                    + You can customize or eliminate the beep that the device emits when a barcode is recognized. Support and valid ranges for these values depend on the device. + + + :scan_received_callback)) + ]]> + + + + + +
                    +
                    +
                    +
                    + + + +
                    + This example shows how to enable your device's barcode scanner and access the data gathered by the scanner. Note that this example assumes that your ebapi-modules.js file is in the same folder as the HTML invoking it. On symbol devices, data wedge needs to be disabled or the Enterprise Browser will not be able to claim any of the scanners. + + + Barcode API Test + + + + + + +

                    Barcode API Test

                    +
                    + Barcode Data:
                    + Time:
                    +
                    + + + ]]> +
                    +
                    +
                    +
                    +
                    +
                    +
                    +
                    diff --git a/docs/en/5.5/api/battery.md b/docs/en/5.5/api/battery.md new file mode 100644 index 00000000..eaa7de80 --- /dev/null +++ b/docs/en/5.5/api/battery.md @@ -0,0 +1,217 @@ +#Battery +
                    +

                    The Battery API is used to notify the user of the remaining power in the battery. Windows Mobile / CE devices also support displaying a small indicator to show the available power.

                    +

                    Enabling the API

                    + +

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

                    + +
                    :::ruby
                    +extensions: ["indicators"]
                    +
                    + +

                    The indicators extension is also included automatically if you specify the following in your build.yml

                    + +
                    :::ruby
                    +app_type: "rhoelements"
                    +
                    + +

                    Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown in this build-time settings example.

                    + +

                    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.

                    + +

                    Persistence

                    + +

                    With the old PocketBrowser / RhoElements 1 APIs, any events, such as batteryEvent were canceled when a full navigate was performed. The original reason for this was a limitation of the IE engine on WM5 devices. When moving to the common API this was changed so that callbacks are not canceled.

                    + + + +

                    Methods

                    + +

                    batteryDiagnostics(CallBackHandler callback)

                    The BatteryDiagnostics method returns parameters for further battery analysis. Not all return values will be supported by all batteries. Any parameters that cannot be retrieved will return ‘undefined’. In Android, Currently supported only on the MC18 device

                    +

                    (Currently supported only on the MC18 device)

                    Parameters

                    • callback : CallBackHandler Optional

                    Async Callback Returning Parameters: HASH

                      • stateOfHealthPercent : STRING

                        The current maximum battery capacity as a percentage of the battery rated capacity

                        +

                      • batteryCapacityPercent : STRING

                        The remaining battery capacity percentage

                        +

                      • batteryCapacityMinutes : STRING

                        The remaining battery capacity in minutes. Calculations are based on the averageCurrentConsumption parameter

                        +

                      • batteryExpirationInMonths : STRING

                        Prediction in number of months when the battery should be replaced. Returns undefined for Android.

                        +

                      • previousBatteryReplacement : STRING

                        Duration in days since the battery was last replaced

                        +

                      • timeSinceLastColdBoot : STRING

                        Time in minutes since the device was last cold booted

                        +

                      • requiredChargeTime : STRING

                        Calculates the charge time required in minutes based on the tripDuration and averageCurrentConsumption parameters.

                        +

                      • chargingTime : STRING

                        The duration of time for which the unit was last charging, in minutes

                        +

                    Synchronous Return:

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

                        The current maximum battery capacity as a percentage of the battery rated capacity

                        +

                      • batteryCapacityPercent : STRING

                        The remaining battery capacity percentage

                        +

                      • batteryCapacityMinutes : STRING

                        The remaining battery capacity in minutes. Calculations are based on the averageCurrentConsumption parameter

                        +

                      • batteryExpirationInMonths : STRING

                        Prediction in number of months when the battery should be replaced. Returns undefined for Android.

                        +

                      • previousBatteryReplacement : STRING

                        Duration in days since the battery was last replaced

                        +

                      • timeSinceLastColdBoot : STRING

                        Time in minutes since the device was last cold booted

                        +

                      • requiredChargeTime : STRING

                        Calculates the charge time required in minutes based on the tripDuration and averageCurrentConsumption parameters.

                        +

                      • chargingTime : STRING

                        The duration of time for which the unit was last charging, in minutes

                        +

                    Method Access:

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

                    batteryStatus(HASH propertyMap, CallBackHandler callback)

                    Retrieve the current battery level. If a callback is provided to retrieve the battery then it will be called periodically at a frequency determined by the trigger property.

                    +

                    Parameters

                    • propertyMap : HASH

                      The properties associated with accessing the battery status.

                      +

                      • trigger : STRING Default: Platform Dependant

                        What will cause the batteryStatus callback to fire. It is recommended to use system events to conserve battery life. Please note, that iOS devices have no system triggers and will provide updates only with a specified period (Trigger value will be ignored)

                        +

                        Possible Values :

                        Constant: Rho::Battery.BATTERY_TRIGGER_PERIODIC (For Ruby use "::" for all "." when referencing constants)
                        String:periodic

                        The batteryStatus callback will fire periodically at the specified refresh interval. This is the default setting on Windows Mobile / CE / Embedded but those platforms do also support the system trigger. Not supported on Android.

                        +
                        Constant: Rho::Battery.BATTERY_TRIGGER_SYSTEM (For Ruby use "::" for all "." when referencing constants)
                        String:system

                        The batteryStatus callback will fire when the underlying operating system notifies that there has been a change to the battery level. The resolution of this change will vary depending on operating system, for example on Windows Mobile the notifications only occur when ‘critical’, ‘full’ etc.

                        +
                      • refreshInterval : INTEGER

                        Alternative way of specifying the refreshInterval parameter. If you are using a system trigger then this parameter will be ignored.

                        +

                    • callback : CallBackHandler Optional

                    Async Callback Returning Parameters: HASH

                      • acLineStatus : BOOLEAN

                        Whether or not the device is connected to external power.

                        +

                      • batteryLifePercent : INTEGER

                        Displays the remaining battery power as a percentage value between 0 and 100. For some Zebra Android devices, the API will return a value of 255 at all times while the battery is being charged. The same value also might be displayed for a few seconds initially after reboot while the battery is being discharged. This is in accordance with hardware design specs and should be taken into account when using the API.

                        +

                      • backupBatteryLifePercent : INTEGER

                        The remaining backup battery power as a percentage between 0 and 100. Supported only on Symbol Technologies Windows Mobile / CE / Embedded devices.

                        + Platforms:WM

                      • trigger : STRING

                        Human readable form of what has caused this callback to fire. This value will be OS dependent. On Windows Mobile / CE / Embedded it will be one of: “High Battery”, “Low Battery”, “Critical Battery”, “Charging”, “No Battery”, “Unknown”. In the case of periodic updates, this field will contain the last known status of the battery.

                        + Platforms:WM, CE, Android

                      • batteryLifeKnown : BOOLEAN

                        Supported only on Symbol Technologies' Windows Mobile / CE / Embedded devices. The battery life will not be readable for a period of time after removing from an AC power source and this parameter will state whether the batteryLifePercent value is accurate.

                        + Platforms:WM

                      • backupBatteryLifeKnown : BOOLEAN

                        Supported only on Symbol Technologies' Windows Mobile / CE / Embedded devices. The battery life will not be readable for a period of time after removing from an AC power source and this parameter will state whether the backupBatteryLifePercent value is accurate.

                        + Platforms:WM

                    Synchronous Return:

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

                        Whether or not the device is connected to external power.

                        +

                      • batteryLifePercent : INTEGER

                        Displays the remaining battery power as a percentage value between 0 and 100. For some Zebra Android devices, the API will return a value of 255 at all times while the battery is being charged. The same value also might be displayed for a few seconds initially after reboot while the battery is being discharged. This is in accordance with hardware design specs and should be taken into account when using the API.

                        +

                      • backupBatteryLifePercent : INTEGER

                        The remaining backup battery power as a percentage between 0 and 100. Supported only on Symbol Technologies Windows Mobile / CE / Embedded devices.

                        + Platforms:WM

                      • trigger : STRING

                        Human readable form of what has caused this callback to fire. This value will be OS dependent. On Windows Mobile / CE / Embedded it will be one of: “High Battery”, “Low Battery”, “Critical Battery”, “Charging”, “No Battery”, “Unknown”. In the case of periodic updates, this field will contain the last known status of the battery.

                        + Platforms:WM, CE, Android

                      • batteryLifeKnown : BOOLEAN

                        Supported only on Symbol Technologies' Windows Mobile / CE / Embedded devices. The battery life will not be readable for a period of time after removing from an AC power source and this parameter will state whether the batteryLifePercent value is accurate.

                        + Platforms:WM

                      • backupBatteryLifeKnown : BOOLEAN

                        Supported only on Symbol Technologies' Windows Mobile / CE / Embedded devices. The battery life will not be readable for a period of time after removing from an AC power source and this parameter will state whether the backupBatteryLifePercent value is accurate.

                        + Platforms:WM

                    Method Access:

                    • Class Method: This method can only be accessed via the API class object.
                      • JavaScript: Rho.Battery.batteryStatus(HASH propertyMap, CallBackHandler callback)
                      • Ruby: Rho::Battery.batteryStatus(HASH propertyMap, CallBackHandler callback)

                    hideIcon()

                    Hide the icon if it has been previously set by the ‘showIcon’ call.

                    +

                    (All platforms support batteryStatus, which can be used to draw your own level indicator or display an appropriate graphic.)

                    Synchronous Return:

                    • Void

                    Method Access:

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

                    showIcon(HASH propertyMap)

                    Overlays a small battery icon on top of the view indicating the remaining battery strength. This is particularly useful in full screen applications that cover the system battery level indicator.

                    +

                    (All platforms support batteryStatus, which can be used to draw your own level indicator or display an appropriate graphic.)

                    Parameters

                    • propertyMap : HASH

                      The properties associated with the indicator, its position and color.

                      +

                      • left : INTEGER Default: [Top left of the screen]

                        The absolute horizontal position of the indicator in pixels. This value is relative to the screen and not the view, so non-fullscreen applications should take care not to display the indicator off screen.

                        +

                      • top : INTEGER Default: [Top left of the screen]

                        The absolute vertical position of the indicator in pixels. Positive numbers go towards the bottom of the screen. This value is relative to the screen and not the view, so non-fullscreen applications should take care not to display the indicator off screen.

                        +

                      • layout : STRING Default: [Right]

                        Sets the orientation of the icon, see the remarks section for illustrations.

                        +

                        Possible Values :

                        Constant: Rho::Battery.BATTERY_LAYOUT_LEFT (For Ruby use "::" for all "." when referencing constants)
                        String:left

                        See the remarks section for illustrations of icon layout.

                        +
                        Constant: Rho::Battery.BATTERY_LAYOUT_RIGHT (For Ruby use "::" for all "." when referencing constants)
                        String:right

                        See the remarks section for illustrations of icon layout.

                        +
                        Constant: Rho::Battery.BATTERY_LAYOUT_UP (For Ruby use "::" for all "." when referencing constants)
                        String:up

                        See the remarks section for illustrations of icon layout.

                        +
                        Constant: Rho::Battery.BATTERY_LAYOUT_DOWN (For Ruby use "::" for all "." when referencing constants)
                        String:down

                        See the remarks section for illustrations of icon layout.

                        +
                      • color : STRING

                        The color of the icon. This value must be specified as a Hex value in the format #000000 to #FFFFFF. Alpha values are not supported, i.e. you can only use the component parts RRGGBB.

                        +

                    Synchronous Return:

                    • Void

                    Method Access:

                    • Class Method: This method can only be accessed via the API class object.
                      • JavaScript: Rho.Battery.showIcon(HASH propertyMap)
                      • Ruby: Rho::Battery.showIcon(HASH propertyMap)

                    smartBatteryStatus(CallBackHandler callback)

                    Returns the various parameters relating to battery charge and battery hardware. Not all return values may be supported by all batteries.

                    +

                    (Scanners on Symbol Technologies' Windows Mobile / CE / Embedded devices)

                    Parameters

                    • callback : CallBackHandler Optional

                    Async Callback Returning Parameters: HASH

                      • serialNumber : STRING

                        The serial number of the battery.

                        +

                      • partNumber : STRING

                        The Symbol Technologies' part number of the battery, e.g. 21-65587 Rev. A.

                        +

                      • batteryChargeCycles : INTEGER

                        The number of times the battery has been charged. Partial charges are aggregated, therefore each charge cycle count represents one full charge / discharge cycle. The battery charge cycle count gets updated when the battery charging state changes from charging to not charging. Cycle count may not accurately predict the life of a battery.

                        +

                      • ratedCapacity : INTEGER

                        Rated capacity of the battery in mAh.

                        +

                      • manufactureDate : STRING

                        Date the battery was manufactured expressed as MM/DD/YYYY.

                        +

                      • stateOfHealth : STRING

                        The health of the battery.

                        +

                        Possible Values :

                        Constant: Rho.Battery.SMART_BATTERY_HEALTHY (For Ruby use "::" for all "." when referencing constants)
                        String:Constant: Rho::Battery.SMART_BATTERY_HEALTHY (For Ruby use "::" for all "." when referencing constants)
                        String:healthy

                        The battery is healthy.

                        +
                        Constant: Rho.Battery.SMART_BATTERY_UNHEALTHY (For Ruby use "::" for all "." when referencing constants)
                        String:Constant: Rho::Battery.SMART_BATTERY_UNHEALTHY (For Ruby use "::" for all "." when referencing constants)
                        String:unhealthy

                        The battery is unhealthy.

                        +
                        Constant: Rho.Battery.SMART_BATTERY_UNKNOWN (For Ruby use "::" for all "." when referencing constants)
                        String:Constant: Rho::Battery.SMART_BATTERY_UNKNOWN (For Ruby use "::" for all "." when referencing constants)
                        String:unknown

                        The battery health is unknown.

                        +

                    Synchronous Return:

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

                        The serial number of the battery.

                        +

                      • partNumber : STRING

                        The Symbol Technologies' part number of the battery, e.g. 21-65587 Rev. A.

                        +

                      • batteryChargeCycles : INTEGER

                        The number of times the battery has been charged. Partial charges are aggregated, therefore each charge cycle count represents one full charge / discharge cycle. The battery charge cycle count gets updated when the battery charging state changes from charging to not charging. Cycle count may not accurately predict the life of a battery.

                        +

                      • ratedCapacity : INTEGER

                        Rated capacity of the battery in mAh.

                        +

                      • manufactureDate : STRING

                        Date the battery was manufactured expressed as MM/DD/YYYY.

                        +

                      • stateOfHealth : STRING

                        The health of the battery.

                        +

                        Possible Values :

                        Constant: Rho::Battery.SMART_BATTERY_HEALTHY (For Ruby use "::" for all "." when referencing constants)
                        String:healthy

                        The battery is healthy.

                        +
                        Constant: Rho::Battery.SMART_BATTERY_UNHEALTHY (For Ruby use "::" for all "." when referencing constants)
                        String:unhealthy

                        The battery is unhealthy.

                        +
                        Constant: Rho::Battery.SMART_BATTERY_UNKNOWN (For Ruby use "::" for all "." when referencing constants)
                        String:unknown

                        The battery health is unknown.

                        +

                    Method Access:

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

                    stopBatteryStatus()

                    If the battery status is being retrieved via callback by a previously invoked call to batteryStatus, this method will stop the callback from firing.

                    +

                    Synchronous Return:

                    • Void

                    Method Access:

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

                    Properties

                    + +

                    averageCurrentConsumption : INTEGER

                    Supported only by the MC18 device. Sets an average current consumption (in mA) that is used in subsequent power-related calculations. If set to 0, the value will be provided by the device driver based on the running average.

                    +

                    Property Access:

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

                    refreshInterval : INTEGER

                    A callback to retrieve the battery strength can be specified to occur periodically with the batteryStatus method. This value specifies the periodicity of the callback as well as the update frequency of the battery icon, if shown. Setting this value to zero will disable the batteryStatus callback. Note that most platforms will not support periodic updates to the battery level, this is only supported on Windows Mobile / CE / Embedded.

                    +

                    Default: 5000

                    Property Access:

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

                    tripDuration : INTEGER

                    Supported only by the MC18 device. Sets the desired working time (in minutes) out of the cradle, which is used in subsequent power-related calculations. If set to 0, the driver default value of 45 minutes will be used.

                    +

                    Property Access:

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

                    Examples

                    + +
                    Retrieve the Battery status
                    +

                    Synchronously: If you are interested only in the current battery level, for example to decide whether you have sufficient battery for the worker to start their shift, then you can immediately determine the level as follows

                    +
                    :::javascript
                    +
                    +            
                    +  function battery_status_sync(){
                    +    batteryValues = Rho.Battery.batteryStatus({});
                    +    console.log("Battery Level is: " + batteryValues['batteryLifePercent']);
                    +  }
                    +                    
                    +                    
                    :::ruby
                    +
                    +            
                    +  def battery_status_sync
                    +    batteryValues = Rho::Battery.batteryStatus
                    +    puts "Battery Level is: " + batteryValues['batteryLifePercent']
                    +  end
                    +                    
                    +                    
                    +

                    Asynchronously: If you want to be notified of changes to the battery level, then you can register to receive values through a callback

                    +
                    :::javascript
                    +
                    +            
                    +  function battery_status_async(){
                    +    console.log("Registering Battery Callback");
                    +    Rho.Battery.batteryStatus({},batteryEvent);
                    +  }
                    +
                    +   function batteryEvent(params){
                    +    console.log("Battery Event Fired:");
                    +    console.log("Battery Event (Asynchronous). AC Line Status: " + params["acLineStatus"] + " Battery Life Percent: " + params["batteryLifePercent"] + " Backup Battery Life Percent: " + params["backupBatteryLifePercent"] + " Status: " + params["batteryStatus"] + " Battery Life Known: " + params["batteryLifeKnown"] + " Backup Battery Life Known: " + params["backupBatteryLifeKnown"]);
                    +  }
                    +  
                    +                    
                    :::ruby
                    +
                    +            
                    +  def battery_status_async
                    +    puts "Registering Battery Callback"
                    +    Rho::Battery.batteryStatus(url_for(:action => :batteryEvent))
                    +  end
                    +
                    +   def batteryEvent
                    +    puts "Battery Event Fired: #{@params}"
                    +    puts "Battery Event (Asynchronous). AC Line Status: #{@params["acLineStatus"]}, Battery Life Percent: #{@params["batteryLifePercent"]}, Backup Battery Life Percent: #{@params["backupBatteryLifePercent"]}, Status: #{@params["batteryStatus"]}, Battery Life Known: #{@params["batteryLifeKnown"]}, Backup Battery Life Known: #{@params["backupBatteryLifeKnown"]}"
                    +  end
                    +  
                    +                    
                    Working with the Battery indicator
                    +

                    If you just want to display the battery indicator in the default position and default color, then call as follows.

                    +
                    :::javascript
                    +
                    +            
                    +  function show_battery_icon(){
                    +    Rho.Battery.showIcon({});
                    +  }
                    +                    
                    +                    
                    :::ruby
                    +
                    +            
                    +  def show_battery_icon
                    +    Rho::Battery.showIcon({})
                    +  end
                    +                    
                    +                    
                    +

                    To display the battery icon at the default position but blue and vertical specify as follows.

                    +
                    :::javascript
                    +
                    +            
                    +  function show_battery_icon(){
                    +    Rho.Battery.showIcon({ left: 0, top: 40, color: '#FF0000', layout: Rho.Battery.BATTERY_LAYOUT_RIGHT });
                    +  }
                    +  
                    +                    
                    :::ruby
                    +
                    +            
                    +  def show_battery_icon
                    +    Rho::Battery.showIcon { left: 0, top: 40, color: '#FF0000', layout: Rho::Battery.BATTERY_LAYOUT_RIGHT }
                    +  
                    +                    
                    + +

                    Remarks

                    + +
                    Icon Layout

                    Windows Mobile / CE and Handheld devices support the display of a small battery icon. This section explains the layout parameter, which can be provided to showIcon(…).

                    + +

                    Layout:Left

                    + +

                    Left Layout Battery Indicator

                    + +

                    Layout:Right

                    + +

                    Right Layout Battery Indicator

                    + +

                    Layout:Up

                    + +

                    Up Layout Battery Indicator

                    + +

                    Layout:Down

                    + +

                    Down Layout Battery Indicator

                    +
                    Overlapping Indicators

                    The position of the signal and battery indicators should not be set to overlap.

                    +
                    Screen Orientation

                    The indicator positions are absolute and so when rotating the screen you should also move the indicator positions accordingly to accommodate the new screen layout.

                    +
                    + +

                    Licensing

                    + +
                    This API is considered a RhoElements API and therefore requires a paid subscription to use (either Silver or Gold level). You can review the subscription plans on our licensing page here or on rhomobile.com/pricing.
                    \ No newline at end of file diff --git a/docs/en/5.5/api/battery.xml b/docs/en/5.5/api/battery.xml new file mode 100644 index 00000000..22ac9ac9 --- /dev/null +++ b/docs/en/5.5/api/battery.xml @@ -0,0 +1,470 @@ + + + + The Battery API is used to notify the user of the remaining power in the battery. Windows Mobile / CE devices also support displaying a small indicator to show the available power. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + :::ruby + extensions: ["indicators"] + +The `indicators` extension is also included automatically if you specify the following in your `build.yml` + :::ruby + app_type: "rhoelements" + +> Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your `build.yml` as shown in this [build-time settings example](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + +## Persistence +With the old PocketBrowser / RhoElements 1 APIs, any events, such as `batteryEvent` were canceled when a full navigate was performed. The original reason for this was a limitation of the IE engine on WM5 devices. When moving to the common API this was changed so that callbacks are not canceled. + + + +## Enabling the API +There are two methods of enabling the Battery API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Battery API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.battery.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + +## Persistence +With the old PocketBrowser APIs, any events, such as `batteryEvent` were canceled when a full navigate was performed. The original reason for this was a limitation of the IE engine on WM5 devices. When moving to the common API this was changed so that callbacks are not canceled. + + + + + + + + WM, CE, iOS + WM, CE + A callback to retrieve the battery strength can be specified to occur periodically with the batteryStatus method. This value specifies the periodicity of the callback as well as the update frequency of the battery icon, if shown. Setting this value to zero will disable the batteryStatus callback. Note that most platforms will not support periodic updates to the battery level, this is only supported on Windows Mobile / CE / Embedded. + + + CE, Android + Supported only by the MC18 device. Sets the desired working time (in minutes) out of the cradle, which is used in subsequent power-related calculations. If set to 0, the driver default value of 45 minutes will be used. + + + CE, Android + Supported only by the MC18 device. Sets an average current consumption (in mA) that is used in subsequent power-related calculations. If set to 0, the value will be provided by the device driver based on the running average. + + + + + + Retrieve the current battery level. If a callback is provided to retrieve the battery then it will be called periodically at a frequency determined by the trigger property. + WM, CE, Android, iOS + WM, CE, Android + + + The properties associated with accessing the battery status. + + + What will cause the batteryStatus callback to fire. It is recommended to use system events to conserve battery life. Please note, that iOS devices have no system triggers and will provide updates only with a specified period (Trigger value will be ignored) + What will cause the batteryStatus callback to fire. It is recommended to use system events to conserve battery life. + + + The batteryStatus callback will fire periodically at the specified refresh interval. This is the default setting on Windows Mobile / CE / Embedded but those platforms do also support the system trigger. Not supported on Android. + + + The batteryStatus callback will fire when the underlying operating system notifies that there has been a change to the battery level. The resolution of this change will vary depending on operating system, for example on Windows Mobile the notifications only occur when 'critical', 'full' etc. + + + + + Alternative way of specifying the refreshInterval parameter. If you are using a system trigger then this parameter will be ignored. + + + + + + + + + Whether or not the device is connected to external power. + + + Displays the remaining battery power as a percentage value between 0 and 100. For some Zebra Android devices, the API will return a value of 255 at all times while the battery is being charged. The same value also might be displayed for a few seconds initially after reboot while the battery is being discharged. This is in accordance with hardware design specs and should be taken into account when using the API. + + + WM + The remaining backup battery power as a percentage between 0 and 100. Supported only on Symbol Technologies Windows Mobile / CE / Embedded devices. + + + WM, CE, Android + Human readable form of what has caused this callback to fire. This value will be OS dependent. On Windows Mobile / CE / Embedded it will be one of: "High Battery", "Low Battery", "Critical Battery", "Charging", "No Battery", "Unknown". In the case of periodic updates, this field will contain the last known status of the battery. + + + WM + Supported only on Symbol Technologies' Windows Mobile / CE / Embedded devices. The battery life will not be readable for a period of time after removing from an AC power source and this parameter will state whether the batteryLifePercent value is accurate. + + + WM + Supported only on Symbol Technologies' Windows Mobile / CE / Embedded devices. The battery life will not be readable for a period of time after removing from an AC power source and this parameter will state whether the backupBatteryLifePercent value is accurate. + + + + + + + If the battery status is being retrieved via callback by a previously invoked call to batteryStatus, this method will stop the callback from firing. + WM, CE, Android, iOS + WM, CE, Android + + + + Returns the various parameters relating to battery charge and battery hardware. Not all return values may be supported by all batteries. + WM + Scanners on Symbol Technologies' Windows Mobile / CE / Embedded devices + + + + The serial number of the battery. + + + The Symbol Technologies' part number of the battery, e.g. 21-65587 Rev. A. + + + The number of times the battery has been charged. Partial charges are aggregated, therefore each charge cycle count represents one full charge / discharge cycle. The battery charge cycle count gets updated when the battery charging state changes from charging to not charging. Cycle count may not accurately predict the life of a battery. + + + Rated capacity of the battery in mAh. + + + Date the battery was manufactured expressed as MM/DD/YYYY. + + + The health of the battery. + + + The battery is healthy. + + + The battery is unhealthy. + + + The battery health is unknown. + + + + + + + + + The BatteryDiagnostics method returns parameters for further battery analysis. Not all return values will be supported by all batteries. Any parameters that cannot be retrieved will return 'undefined'. In Android, Currently supported only on the MC18 device + CE, Android + Currently supported only on the MC18 device + + + + The current maximum battery capacity as a percentage of the battery rated capacity + + + The remaining battery capacity percentage + + + The remaining battery capacity in minutes. Calculations are based on the averageCurrentConsumption parameter + + + Prediction in number of months when the battery should be replaced. Returns undefined for Android. + + + Duration in days since the battery was last replaced + + + Time in minutes since the device was last cold booted + + + Calculates the charge time required in minutes based on the tripDuration and averageCurrentConsumption parameters. + + + The duration of time for which the unit was last charging, in minutes + + + + + + + Overlays a small battery icon on top of the view indicating the remaining battery strength. This is particularly useful in full screen applications that cover the system battery level indicator. + WM, CE, Android + All platforms support batteryStatus, which can be used to draw your own level indicator or display an appropriate graphic. + + + The properties associated with the indicator, its position and color. + + + The absolute horizontal position of the indicator in pixels. This value is relative to the screen and not the view, so non-fullscreen applications should take care not to display the indicator off screen. + + + The absolute vertical position of the indicator in pixels. Positive numbers go towards the bottom of the screen. This value is relative to the screen and not the view, so non-fullscreen applications should take care not to display the indicator off screen. + + + Sets the orientation of the icon, see the remarks section for illustrations. + + + See the remarks section for illustrations of icon layout. + + + See the remarks section for illustrations of icon layout. + + + See the remarks section for illustrations of icon layout. + + + See the remarks section for illustrations of icon layout. + + + + + The color of the icon. This value must be specified as a Hex value in the format #000000 to #FFFFFF. Alpha values are not supported, i.e. you can only use the component parts RRGGBB. + + + + + + + + Hide the icon if it has been previously set by the 'showIcon' call. + WM, CE, Android + All platforms support batteryStatus, which can be used to draw your own level indicator or display an appropriate graphic. + + + + 1.0.0 + WM, CE, Android, iOS + WM, CE, Android + + + +
                    + Synchronously: If you are interested only in the current battery level, for example to decide whether you have sufficient battery for the worker to start their shift, then you can immediately determine the level as follows + + + + + + + + +
                    +
                    + Asynchronously: If you want to be notified of changes to the battery level, then you can register to receive values through a callback + + + :batteryEvent)) + end + + def batteryEvent + puts "Battery Event Fired: #{@params}" + puts "Battery Event (Asynchronous). AC Line Status: #{@params["acLineStatus"]}, Battery Life Percent: #{@params["batteryLifePercent"]}, Backup Battery Life Percent: #{@params["backupBatteryLifePercent"]}, Status: #{@params["batteryStatus"]}, Battery Life Known: #{@params["batteryLifeKnown"]}, Backup Battery Life Known: #{@params["backupBatteryLifeKnown"]}" + end + ]]> + + + + + +
                    +
                    +
                    + + +
                    + If you just want to display the battery indicator in the default position and default color, then call as follows. + + + + + + + + +
                    +
                    + To display the battery icon at the default position but blue and vertical specify as follows. + + + + + + + + +
                    +
                    +
                    +
                    + + + +
                    + This example shows how to show/hide the Battery icon as well as a way to adjust for a change in screen orientation. This example assumes that the ebapi-modules.js file is in the same folder as the html file invoking it. + + + + + Battery API Test + + + + + +

                    Battery API Test

                    +
                    +
                    +
                    +
                    +
                    + + + ]]> +
                    +
                    +
                    +
                    +
                    +
                    + + + + Windows Mobile / CE and Handheld devices support the display of a small battery icon. This section explains the layout parameter, which can be provided to showIcon(...). + +Layout:Left +----------- +![Left Layout Battery Indicator](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAI4AAABiCAIAAAAJGXymAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIBQouCLvI+XcAAAGaSURBVHja7d3tjYIwAIBhe3EARnAD2aCMwggdwREYwVFgA9xAN3AD7u/luJy1UfHjeX+aapo+oeDlwDBN0yqjEMJKyxVj/LIKrxIqVEKFSqiECpVQCRUqPVfrG35WjLFpGmt6bfv9/nQ6PZSqaZrdbmfpr63v+xwqG6BzlVCh0iddAd6vcRxTSgVvbNu2bdufr6SUxnEsO/nfaUpvRXU+n4dhKLsonauXfdT9pmQDfLsNsPhA1qOpig9kuQIUKlRCJVSohEqoUAnVR5f7l/XtdltV1f9jNpuNBV2equs6/41kAxQqVEIlVKiESqhQCZVQoRIqoUIlVKiESqhQCZVQoRIqoUIlVEKFSouWeydISuniTTvFz+TSLakOh8PFMe7qsQEKFSqhQiVUQoVKqITqg1pXVRVjvDjOU6OXp6rr+tdPKPxZCMFi2QCVd1S9xCwzd+l584ep1XX9bFN6K6rMXTqnruuebUo2QOcqoRIqV4Cz+r73u8AFHY/HnGFhmqascb4CL1qM0QboXCVUqIRKqFAJlVChEioV9Q38vGIHwMPikwAAAABJRU5ErkJggg== "Battery Indicator") + +Layout:Right +------------ +![Right Layout Battery Indicator](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAI4AAABiCAIAAAAJGXymAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIBQouHk8cTCYAAAGRSURBVHja7d3hbYJAGIBh0nQANpAR2ADdhE1khBuBUc4R3IARbgP7t6lpOAgnYp7np7GG8IaPq9Gz6rquYlePPF/O1FFIJRVSSYVUSCUVUiGVVLyX75wnnU6nvu+drKVijLfb7aWpmqYZhsGpX2oYhg1TGYDuVUglFR+xAnw2juM4jiv+MITQtu3vR87n84rXads2hFDokD4q1TRN69Y2KaU/j2y1RtrwkAxA9riq2FDOLSCEINX+cuZ2SskAtFhHKqmQCqmkQiqkkor34o2lgpqmmf2mYUrpfr9LtbO+72c/6RVjvFwuBqB7FVIhlVRIhVRSIRVSSYVUSCUVUkmFVEglFVIhlVRIhVRSIRVSSYVUZPBNkIJyNlPL34xLqoJWb6ZmALpXIRVSSYVUSCUVUknFAXhjaX+zm/tUVVXXtVT7izEagAZg3p5c/13IKy7/Z88/uLLhIR14UHZd92C56/WakyDz1QxAi3WkkoqPWAFO0+R3gcv9w7TlCpCirADdq5AKqaRCKqSSCqmQSipK+gHwTQYZtwZTVQAAAABJRU5ErkJggg== "Battery Indicator") + +Layout:Up +--------- +![Up Layout Battery Indicator](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGIAAACOCAIAAABFQUqgAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIBQouKm6ouJMAAAGWSURBVHja7d3RkYIwFEBR3LEAO9AOpINnKZaQDmjBkrAD7EA7sAO2gP1YJjFonHO/HYQzJA5gdDPPc1fQNE3P57P77Ha7Xd/3RZuYy4qI7uOLiMLD/Om0IEyYMGHChAmTMGHCtHabFd7jeDxeLpdKG08p3W632oewXecC/XQ61du4QWduwoQJkzBhwoQJ0xe26GIlIkquNg6HQ70DOJ/PJfs2juP1en3NrgzDMH9pwzAYdOYmTJgwYRImTJgwYcKESZgwYcKECRMmYcKECRMmTJiEaWmZX59vYl3937JX2mcypZRe9n2XFYuIcRwNOnMTJkyYMAkTJkyYMGHCJEyYMGFqocy7l4WL/d5V9gLIfCaDTpgwYWrzky6lNE1Tc0fb933ez7flP/Vt8XGmQYcJEyZMmIQJEyZMmDBhEiZMmDC1U+bdy7wlDc4mTMKE6QOmcMsOF2XZoTBhwoQJEyZMwoQJEyZMmDAJE6bKWXZYmcmgEyZMmN7cZsmL9vt91f/mfWP3+/3xeDgPJEmSJDV6TRcRFP7tF5VvpjOfDnyyAAAAAElFTkSuQmCC "Battery Indicator") + +Layout:Down +----------- +![Down Layout Battery Indicator](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGIAAACOCAIAAABFQUqgAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIBQotLKzmTmUAAAF9SURBVHja7d3hkUNQFIDR2EkBOqAEHVyl6EQLSkgpdKAEOtCBbcGwrCfn+51InMmTEXMji4iXJEmSJCnJsi0PKoqiLMtH7v80TfM8/8222rZdH1rbtlsEfiwoTJgw3bD3vqd9Pp9pmpLb27Ism6a5lGkYhuSYImIfk0WHCRMmTJgwCRMmTJgwYcIkTJgwXd7OXy+7rluWJbm9zfP8Uqaqqiw6YcKEKU2muq6zBKvr2qfJosOECRMmYcKECRMmTJiECRMmTIn0XRegdr/t/ZczLTphwoQpzW86Y4dbmYwdChMmTJgwYcIkTJgwYcKECZMwYTozY4dnMhk7FCZMmDBhwoRJmDBhwoQJEyZhwoQJEyZMmIQJEyZMmDB9Y5vu6xsRu/9Y83Vg2G9LBwcg+76/y2BgRJx3Y96IsOgcmzBhwiRMmDBhwvTA3he8xrIsfd+ft/ErnJI4pfr3k0qLzrEJEyZMmDAJEyZMmG5Ztq7rkeeP43j/Sfs8zw+Ouv8CFfQAjSZxPXkAAAAASUVORK5CYII= "Battery Indicator") + + + + The position of the signal and battery indicators should not be set to overlap. + + + + The indicator positions are absolute and so when rotating the screen you should also move the indicator positions accordingly to accommodate the new screen layout. + + + When using the this feature on a CE device using the IE engine, screen distortion may be noticed when scrolling. This is due to a limitation of the IE engine and can be worked around using any of the following options: + +* Not using debug buttons - If your app must use the IE engine, do not use debug buttons in the app. +* If you need to use the signal or battery indicators either: + * Don't scroll the page. + * Don't use the signal / battery indicators + * Use the Webkit engine. + + +
                    +
                    diff --git a/docs/en/5.5/api/btdiscover.md b/docs/en/5.5/api/btdiscover.md new file mode 100644 index 00000000..87454add --- /dev/null +++ b/docs/en/5.5/api/btdiscover.md @@ -0,0 +1,10 @@ +#Btdiscover +
                    +

                    Example extension api

                    +

                    This is example of API. Implementation contain in extension.

                    + + + +

                    Methods

                    + +
                    \ No newline at end of file diff --git a/docs/en/5.5/api/btdiscover.xml b/docs/en/5.5/api/btdiscover.xml new file mode 100644 index 00000000..3c858794 --- /dev/null +++ b/docs/en/5.5/api/btdiscover.xml @@ -0,0 +1,29 @@ + + + + + Example extension api + This is example of API. Implementation contain in extension. + + + + + + + + + + + + + + + + + + + 1.0.0 + + + + diff --git a/docs/en/5.5/api/camera.md b/docs/en/5.5/api/camera.md new file mode 100644 index 00000000..efd0af88 --- /dev/null +++ b/docs/en/5.5/api/camera.md @@ -0,0 +1,568 @@ +#Camera +
                    +

                    The Camera API provides access to the device camera(s). Use this API to give users the ability to take a photo via one of the cameras and return it to the application. Photos can either be stored on the device as an image file or returned as a DataURI object for storage and/or display. Optionally, image files also can be transfered to online storage using the Network API.

                    +

                    Enabling the API

                    + +

                    To use this API, the following extension must be included in the build.yml:

                    + +
                    :::ruby
                    +extensions: ["mediacapture"]
                    +
                    + +

                    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

                    + +

                    capture(CallBackHandler callback)

                    Capture the image and save it to a file.

                    +

                    Parameters

                    • callback : CallBackHandler Mandatory

                    Async Callback Returning Parameters: HASH

                      • status : STRING

                        Whether or not the image was successfully captured. The returned string will be one of ‘ok’ or ‘error’.

                        +

                      • imageUri : STRING

                        If the specified ‘outputFormat’ was ‘image’ then this field is the URI to the taken image stored on the device. If the specified ‘outputFormat’ was ‘dataUri’ then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified ‘outputFormat’ was ‘imagePath’ then this field will have the image path on the device. User can use image path to transfer image over http.

                        +

                      • imageHeight : INTEGER

                        The actual height of the image that was captured, this may differ from the requested height as the Camera will only support a finite resolutions.

                        +

                      • imageWidth : INTEGER

                        The actual width of the image that was captured, this may differ from the requested width as the Camera will only support a finite resolutions.

                        +

                      • imageFormat : STRING

                        The format in which the image was captured, either ‘png’ or ‘jpg’.

                        +

                      • message : STRING

                        If the returned status is ‘error’ then this field will contain more information on the error.

                        +

                    Synchronous Return:

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

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.capture(CallBackHandler callback)
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Camera.capture(CallBackHandler callback)
                      • Ruby: Rho::Camera.capture(CallBackHandler callback)

                    choosePicture(HASH propertyMap, CallBackHandler callback)

                    Choose a picture from the album.

                    +

                    Parameters

                    • propertyMap : HASH Optional

                      Provide a set of properties to configure an image, for example to specify the image size or color mode. In WM/CE,Android and WP8 devices user can only specify the outputFormat in the property bag. In iOS devices user can specify next options: compressionFormat, desiredWidth, desiredHeight, outputFormat, colorModel, enableEditing.

                      + +
                                              In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri.On wp8, wm when 'outputFormat' is 'image' then imageUri or image_uri shall have Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when 'outputFormat' is 'image'
                      +
                      + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

                      Not providing properties to this function will use the Camera’s default properties, or those previously set on the Camera instance.

                      +

                    • callback : CallBackHandler Mandatory

                    Async Callback Returning Parameters: HASH

                      • status : STRING

                        Whether or not the image was successfully chosen from the gallery. The returned string will be one of ‘ok’, ‘cancel’ or ‘error’.

                        +

                      • imageUri : STRING

                        If the specified ‘outputFormat’ was ‘image’ then this field is the URI to the taken image stored on the device.On wp8,wm when ‘outputFormat’ is ‘image’ then imageUri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when ‘outputFormat’ is ‘image’, this image will have an auto-generated name. If the specified ‘outputFormat’ was ‘dataUri’ then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified ‘outputFormat’ was ‘imagePath’ then this field will have the image path on the device. User can use image path to transfer image over http.

                        + Platforms:Android, WM, CE, iOS, WP8

                      • imageHeight : INTEGER

                        The height of the image.

                        +

                      • imageWidth : INTEGER

                        The width of the image.

                        +

                      • imageFormat : STRING

                        The format of the image, either ‘png’ or ‘jpg’.

                        +

                      • message : STRING

                        If the returned status is ‘error’ then this field will contain more information on the error. To maintain backward compatibility WM and Android platforms provides message for cancel status as well.

                        +

                      • image_uri : STRING

                        If the specified ‘outputFormat’ was ‘image’ then this field is the URI to the taken image stored on the device.On wp8,wm when ‘outputFormat’ is ‘image’ then imageUri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when ‘outputFormat’ is ‘image’, this image will have an auto-generated name. If the specified ‘outputFormat’ was ‘dataUri’ then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified ‘outputFormat’ was ‘imagePath’ then this field will have the image path on the device. User can use image path to transfer image over http.

                        + Platforms:Android, WM, CE, iOS, WP8

                      • image_height : INTEGER

                        It is recommended to use imageHeight in preference to this parameter.

                        +

                      • image_width : INTEGER

                        It is recommended to use imageWidth in preference to this parameter.

                        +

                      • image_format : STRING

                        It is recommended to use imageFormat in preference to this parameter.

                        +

                    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.Camera.choosePicture(HASH propertyMap, CallBackHandler callback)
                      • Ruby: Rho::Camera.choosePicture(HASH propertyMap, CallBackHandler callback)

                    copyImageToDeviceGallery(STRING pathToImage)

                    Replaces: save_image_to_device_gallery

                    Save an image to the device gallery.

                    +

                    Parameters

                    • pathToImage : STRING

                      The real path to the image that is to be saved in the device gallery. You need to use the RhoApplication method expandDatabaseBlobFilePath to have the real path, such as Rho::RhoApplication::expandDatabaseBlobFilePath(img.image_uri).

                      +

                    Synchronous Return:

                    • Void

                    Method Access:

                    • Class Method: This method can only be accessed via the API class object.
                      • JavaScript: Rho.Camera.copyImageToDeviceGallery(STRING pathToImage)
                      • Ruby: Rho::Camera.copyImageToDeviceGallery(STRING pathToImage)

                    getAllProperties(CallBackHandler callback)

                    This method will return all of object/value pairs for the propertyNames of the API class.

                    +

                    Parameters

                    • callback : CallBackHandler Optional

                    Async Callback Returning Parameters: HASH

                      • : STRING

                    Synchronous Return:

                    • HASH :

                      Map of all available properties

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

                    Method Access:

                    • Instance Method: This method can be accessed via an instance object of this class:
                      • myObject.getAllProperties(CallBackHandler callback)
                    • Default Instance: This method can be accessed via the default instance object of this class.
                      • JavaScript: Rho.Camera.getAllProperties(CallBackHandler callback)
                      • Ruby: Rho::Camera.getAllProperties(CallBackHandler callback)

                    getCameraByType(STRING cameraType, CallBackHandler callback)

                    Returns the camera of requested type if that camera exist – else return nil.

                    +

                    Parameters

                    • cameraType : STRING

                      CameraType: ‘back’ or ‘front’ in the case of Android, iOS and WP8 and ‘color’ or ‘imager’ in the case of WM, CE devices

                      +

                    • callback : CallBackHandler Optional

                    Async Callback Returning Parameters: SELF_INSTANCE

                      Synchronous Return:

                      • SELF_INSTANCE :

                        Camera with requested type or nil if not requested type does not exist. Refer example section for more details.

                        + : 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.Camera.getCameraByType(STRING cameraType, CallBackHandler callback)
                        • Ruby: Rho::Camera.getCameraByType(STRING cameraType, CallBackHandler callback)

                      getDefault()

                      This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

                      +

                      Synchronous Return:

                      • SELF_INSTANCE :

                        Default object of Module.

                        +

                      Method Access:

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

                      getProperties(ARRAY arrayofNames, CallBackHandler callback)

                      This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                      +

                      Parameters

                      • arrayofNames : ARRAY

                        List of properties I want to know about

                        +

                        • Object : STRING

                      • callback : CallBackHandler Optional

                      Async Callback Returning Parameters: HASH

                        • : STRING

                      Synchronous Return:

                      • HASH :

                        Map of properties I want to know about

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

                      Method Access:

                      • Instance Method: This method can be accessed via an instance object of this class:
                        • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                      • Default Instance: This method can be accessed via the default instance object of this class.
                        • JavaScript: Rho.Camera.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                        • Ruby: Rho::Camera.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                      getProperty(STRING propertyName, CallBackHandler callback)

                      This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                      +

                      Parameters

                      • propertyName : STRING

                        The property to return info about.

                        +

                      • callback : CallBackHandler Optional

                      Async Callback Returning Parameters: STRING

                        Synchronous Return:

                        • STRING :

                          The property to return info about.

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

                        Method Access:

                        • Instance Method: This method can be accessed via an instance object of this class:
                          • myObject.getProperty(STRING propertyName, CallBackHandler callback)
                        • Default Instance: This method can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.getProperty(STRING propertyName, CallBackHandler callback)
                          • Ruby: Rho::Camera.getProperty(STRING propertyName, CallBackHandler callback)

                        hidePreview()

                        Hides the preview opened by using showPreview.

                        +

                        Synchronous Return:

                        • Void

                        Method Access:

                        • Instance Method: This method can be accessed via an instance object of this class:
                          • myObject.hidePreview()
                        • Default Instance: This method can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.hidePreview()
                          • Ruby: Rho::Camera.hidePreview()

                        setDefault(SELF_INSTANCE: Rho::Camera defaultInstance)

                        This method allows you to set the attributes of the default object instance by passing in an object of the same class.

                        +

                        Parameters

                        • defaultInstance : SELF_INSTANCE: Rho::Camera

                          An instance object that is of the same class.

                          +

                        Synchronous Return:

                        • Void

                        Method Access:

                        • Class Method: This method can only be accessed via the API class object.
                          • JavaScript: Rho.Camera.setDefault(SELF_INSTANCE: Rho::Camera defaultInstance)
                          • Ruby: Rho::Camera.setDefault(SELF_INSTANCE: Rho::Camera defaultInstance)

                        setProperties(HASH propertyMap)

                        This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                        +

                        Parameters

                        • propertyMap : HASH

                          Map of properties I want to set

                          +

                          • Object : STRING

                        Synchronous Return:

                        • Void

                        Method Access:

                        • Instance Method: This method can be accessed via an instance object of this class:
                          • myObject.setProperties(HASH propertyMap)
                        • Default Instance: This method can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.setProperties(HASH propertyMap)
                          • Ruby: Rho::Camera.setProperties(HASH propertyMap)

                        setProperty(STRING propertyName, STRING propertyValue)

                        This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                        +

                        Parameters

                        • propertyName : STRING

                          The one property name that I want to set

                          +

                        • propertyValue : STRING

                          The one property value that I want to set

                          +

                        Synchronous Return:

                        • Void

                        Method Access:

                        • Instance Method: This method can be accessed via an instance object of this class:
                          • myObject.setProperty(STRING propertyName, STRING propertyValue)
                        • Default Instance: This method can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.setProperty(STRING propertyName, STRING propertyValue)
                          • Ruby: Rho::Camera.setProperty(STRING propertyName, STRING propertyValue)

                        showPreview(HASH propertyMap)

                        Shows the preview in user configurable viewer window.

                        +

                        Parameters

                        • propertyMap : HASH Optional

                          Provide a set of properties to configure the camera.

                          + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

                          Not providing properties to this function will use the Camera’s default properties, or those previously set on the Camera instance.

                          +

                        Synchronous Return:

                        • Void

                        Method Access:

                        • Instance Method: This method can be accessed via an instance object of this class:
                          • myObject.showPreview(HASH propertyMap)
                        • Default Instance: This method can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.showPreview(HASH propertyMap)
                          • Ruby: Rho::Camera.showPreview(HASH propertyMap)

                        takePicture(HASH propertyMap, CallBackHandler callback)

                        Start the camera application to take a picture. The user can capture the displayed image by interacting with the resident camera app. In Windows, this method always shows the preview in full screen and user can use the native button to capture the image.

                        + +
                                    On wp8,wm when 'outputFormat' is 'image' then imageUri/image_uri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when 'outputFormat' is 'image'
                        +
                        + +

                        Note: To display an image, it is recommended that you use the full path to the image instead of a relative path. To do this, you can use the expandDatabaseBlobFilePath method of the Application module as such:

                        + +
                        Ruby
                        + +
                        :::ruby
                        +Rho::RhoApplication.expandDatabaseBlobFilePath(x.image_uri)
                        +
                        + +
                        JavaScript
                        + +
                        :::js
                        +Rho.RhoApplication.expandDatabaseBlobFilePath(x.image_uri)
                        +
                        +

                        Parameters

                        • propertyMap : HASH Optional

                          Provide a set of properties to configure the camera, for example to specify the flashMode or compressionFormat.

                          + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

                          Not providing properties to this function will use the Camera’s default properties, or those previously set on the Camera instance.

                          +

                        • callback : CallBackHandler Mandatory

                        Async Callback Returning Parameters: HASH

                          • status : STRING

                            Whether or not the image was successfully captured. The returned string will be one of ‘ok’, ‘cancel’ or ‘error’.

                            + Platforms:Android, WM, CE, iOS, WP8

                          • imageUri : STRING

                            If the specified ‘outputFormat’ was ‘image’ then this field is the URI to the taken image stored on the device.On wp8,wm when ‘outputFormat’ is ‘image’ then imageUri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when ‘outputFormat’ is ‘image’, this image will have an auto-generated name. If the specified ‘outputFormat’ was ‘dataUri’ then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified ‘outputFormat’ was ‘imagePath’ then this field will have the image path on the device. User can use image path to transfer image over http.

                            + Platforms:Android, WM, CE, iOS, WP8

                          • imageHeight : INTEGER

                            The actual height of the image that was captured, this may differ from the requested height as the Camera will only support a finite resolutions.

                            + Platforms:Android, WM, CE, iOS, WP8

                          • imageWidth : INTEGER

                            The actual width of the image that was captured, this may differ from the requested width as the Camera will only support a finite resolutions.

                            + Platforms:Android, WM, CE, iOS, WP8

                          • imageFormat : STRING

                            The format in which the image was captured, either ‘png’ or ‘jpg’.

                            + Platforms:Android, WM, CE, iOS

                          • message : STRING

                            If the returned status is ‘error’ then this field will contain more information on the error. To maintain backward compatibility WM and Android platforms provides message for cancel status as well.

                            + Platforms:Android, WM, CE, iOS, WP8

                          • image_uri : STRING

                            If the specified ‘outputFormat’ was ‘image’ then this field is the URI to the taken image stored on the device.On wp8,wm when ‘outputFormat’ is ‘image’ then imageUri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when ‘outputFormat’ is ‘image’, this image will have an auto-generated name. If the specified ‘outputFormat’ was ‘dataUri’ then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified ‘outputFormat’ was ‘imagePath’ then this field will have the image path on the device. User can use image path to transfer image over http.

                            + Platforms:Android, WM, CE, iOS, WP8

                          • image_height : INTEGER

                            It is recommended to use imageHeight in preference to this parameter.

                            + Platforms:Android, WM, CE, iOS, WP8

                          • image_width : INTEGER

                            It is recommended to use imageWidth in preference to this parameter.

                            + Platforms:Android, WM, CE, iOS, WP8

                          • image_format : STRING

                            It is recommended to use imageFormat in preference to this parameter.

                            + Platforms:Android, WM, CE, iOS

                        Synchronous Return:

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

                        Method Access:

                        • Instance Method: This method can be accessed via an instance object of this class:
                          • myObject.takePicture(HASH propertyMap, CallBackHandler callback)
                        • Default Instance: This method can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.takePicture(HASH propertyMap, CallBackHandler callback)
                          • Ruby: Rho::Camera.takePicture(HASH propertyMap, CallBackHandler callback)
                        + +

                        Properties

                        + +

                        aimMode : STRING

                        Specifies the aim behaviour when taking a picture. Applicable only for imager module.

                        + +
                                    This Property shall accept/return one among the values mentioned in constant section which starts with AIM_...
                        +
                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.aimMode
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.aimMode
                          • Ruby: Rho::Camera.aimMode

                        cameraType : STRING Read Only

                        Replaces:camera_type

                        This property is device specific. The value for this property can be either ‘back’ or ‘front’ in the case of Android/iOS/WP8 devices.In the case of WM/CE it could be either ‘imager’ or ‘color’. WM/CE devices will use ‘color'as default and if color camera not available the default value will be 'imager’. Android/iOS/WP8 devices will use ‘back'as default and if back camera not available the default value will be 'front’,

                        + +
                                    This Property shall return one among the values mentioned in constant section which starts with CAMERA_TYPE_...
                        +
                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.cameraType
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.cameraType
                          • Ruby: Rho::Camera.cameraType

                        captureSound : STRING 4.0.0

                        Path to a sound file resident on the device which will be played when the image is captured.

                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.captureSound
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.captureSound
                          • Ruby: Rho::Camera.captureSound

                        colorModel : STRING 2.0.0

                        Replaces:color_model

                        Where supported by the hardware this property can be used to select whether to capture a color or a grayscale image.

                        + +
                                    This Property shall accept/return one among the values mentioned in constant section which starts with COLOR_MODEL_...
                        +
                        +

                        Default: rgb

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.colorModel
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.colorModel
                          • Ruby: Rho::Camera.colorModel

                        compressionFormat : STRING 4.0.0

                        Replaces:format

                        The format of the captured image in subsequent calls to takePicture(). If you do not define this property when you use choose_picture with iOS, the type of image in Gallery will be recognized, and the same format will be used for saving the image to applications data. In windows and WP8 devices the format will be always jpg type.

                        + +
                                    This Property shall accept/return one among the values mentioned in constant section which starts with COMPRESSION_FORMAT_...
                        +
                        +

                        Default: jpg

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.compressionFormat
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.compressionFormat
                          • Ruby: Rho::Camera.compressionFormat

                        desiredHeight : INTEGER 2.0.0

                        Replaces:desired_height

                        Camera hardware is limited to taking photos in a finite number of resolutions, eg 2048x1536, 640x480 etc. Specifying a desiredHeight will request to take the photo with the specified height but if it is not supported by the hardware then the closest match will be selected. The callback received when a photo is taken contains the actual resolution of the captured photo.

                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.desiredHeight
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.desiredHeight
                          • Ruby: Rho::Camera.desiredHeight

                        desiredWidth : INTEGER 2.0.0

                        Replaces:desired_width

                        Camera hardware is limited to taking photos in a finite number of resolutions, eg 2048x1536, 640x480 etc. Specifying a desiredWidth will request to take the photo with the specified width but if it is not supported by the hardware then the closest match will be selected. The callback received when a photo is taken contains the actual resolution of the captured photo.

                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.desiredWidth
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.desiredWidth
                          • Ruby: Rho::Camera.desiredWidth

                        enableEditing : BOOLEAN 2.0.0

                        Replaces:enable_editing

                        Enables post photo capture image customizing; image will captured reduced to screen size (not full size of camera sensor).

                        +

                        Default: true

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.enableEditing
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.enableEditing
                          • Ruby: Rho::Camera.enableEditing

                        fileName : STRING 4.0.0

                        The image file path without file extension to store captured image in subsequent calls to takePicture() or capture(). Default filename will be IMG_timestamp and will be saved under root directory. The filename extension will be added automatically according to compressionFormat property value.

                        + +
                                    In Wp8, only filename can be changed, by default the path shall be under picture=>CameraRoll
                        +
                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.fileName
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.fileName
                          • Ruby: Rho::Camera.fileName

                        flashMode : STRING 2.0.0

                        Replaces:flash_mode

                        Specifies the flash behavior when taking a picture.

                        + +
                                    This Property shall accept/return one among the values mentioned in constant section which starts with FLASH_...
                        +
                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.flashMode
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.flashMode
                          • Ruby: Rho::Camera.flashMode

                        maxHeight : INTEGER Read Only

                        The maximum height of images which can be captured. This is measured in pixels. On WM/CE devices this is applicable only for color camera. Imager does not support this property.

                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.maxHeight
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.maxHeight
                          • Ruby: Rho::Camera.maxHeight

                        maxWidth : INTEGER Read Only

                        The maximum width of images which can be captured. This is measured in pixels. On WM/CE devices this is applicable only for color camera. Imager does not support this property.

                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.maxWidth
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.maxWidth
                          • Ruby: Rho::Camera.maxWidth

                        outputFormat : STRING 4.0.0

                        Specifies the way to return the captured image to the application.

                        + +
                                    This Property shall accept/return one among the values mentioned in constant section which starts with OUTPUT_FORMAT_...
                        +
                        +

                        Default: imagePath

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.outputFormat
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.outputFormat
                          • Ruby: Rho::Camera.outputFormat

                        previewHeight : INTEGER 4.0.0

                        In cases where the resident camera application on the device is not used this API is used to control the position of the viewfinder preview window when taking a photo.

                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.previewHeight
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.previewHeight
                          • Ruby: Rho::Camera.previewHeight

                        previewLeft : INTEGER 4.0.0

                        Replaces:left

                        In cases where the resident camera application on the device is not used this API is used to control the position of the viewfinder preview window when taking a photo.

                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.previewLeft
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.previewLeft
                          • Ruby: Rho::Camera.previewLeft

                        previewTop : INTEGER 4.0.0

                        Replaces:top

                        In cases where the resident camera application on the device is not used this API is used to control the position of the viewfinder preview window when taking a photo.

                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.previewTop
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.previewTop
                          • Ruby: Rho::Camera.previewTop

                        previewWidth : INTEGER 4.0.0

                        In cases where the resident camera application on the device is not used this API is used to control the position of the viewfinder preview window when taking a photo.

                        +

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.previewWidth
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.previewWidth
                          • Ruby: Rho::Camera.previewWidth

                        saveToDeviceGallery : BOOLEAN 2.0.0

                        Replaces:save_to_shared_gallery

                        If true, the picture you take will be added to the device photo gallery.

                        +

                        Default: false

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.saveToDeviceGallery
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.saveToDeviceGallery
                          • Ruby: Rho::Camera.saveToDeviceGallery

                        supportedSizeList : ARRAY Read Only

                        List of resolutions (width and height in pixels) supported by the camera. On WM/CE devices this feature is supported only by color camera and it is not supported by imager. Refer example section for more details.

                        +

                      • Object : HASH

                        • width : INTEGER

                        • height : INTEGER

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.supportedSizeList
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.supportedSizeList
                          • Ruby: Rho::Camera.supportedSizeList

                        useSystemViewfinder : BOOLEAN 4.0.0

                        Setting the value of this property to “true”, shall open the System ViewFinder with its properties. None of the Rho camera properties shall be applicable.

                        +

                        Default: false

                        Property Access:

                        • Instance: This property can be accessed via an instance object of this class:
                          • myObject.useSystemViewfinder
                        • Default Instance: This property can be accessed via the default instance object of this class.
                          • JavaScript: Rho.Camera.useSystemViewfinder
                          • Ruby: Rho::Camera.useSystemViewfinder
                        + +

                        Constants

                        + +
                        CAMERA_TYPE_BACK

                        Back camera. This is not supported in WM/CE devices.

                        +
                        CAMERA_TYPE_FRONT

                        Front camera. This is not supported in WM/CE devices.

                        +
                        CAMERA_TYPE_IMAGER

                        Camera is an imager. This is supported only in WM/CE devices.

                        +
                        CAMERA_TYPE_COLOR

                        Camera is color camera. This is supported only in WM/CE devices.

                        +
                        COMPRESSION_FORMAT_JPG

                        JPG compression.

                        +
                        COMPRESSION_FORMAT_PNG

                        PNG compression.

                        +
                        OUTPUT_FORMAT_IMAGE

                        This shall provide the image uri. This can be used to display image directly on the page. An example is shown in the example section

                        +
                        OUTPUT_FORMAT_DATAURI

                        This is a base 64 encoding of the image and can be used to easily embed the image on the page or store the image in a database. On some consumer devices, captured image will be rotated 90 degrees while displaying.

                        +
                        OUTPUT_FORMAT_IMAGE_PATH

                        If this value used for setting the outputFormat property, the takePicture or capture API will return imageUri as the path to the saved image in the device. User can use this image path to transfer the file to an http server if required. An example is given to demonstrate, transferring a file to http server.This property is not applicable for Android and windows phone 8.

                        +
                        COLOR_MODEL_RGB

                        A colour image is captured.

                        +
                        COLOR_MODEL_GRAYSCALE

                        A grayscale image is captured.

                        +
                        FLASH_ON

                        Flash will be used.

                        +
                        FLASH_OFF

                        Flash will not be used.

                        +
                        FLASH_AUTO

                        Flash will be used if lighting conditions deem it necessary. This is not supported in WM/CE devices.

                        +
                        FLASH_RED_EYE

                        Flash with red eye reduction is used. This is supported only in Android devices.

                        +
                        FLASH_TORCH

                        The flash is turned on in torch mode. This is supported only in Android devices.

                        +
                        AIM_ON

                        Switches the imager’s aim to ON

                        +
                        AIM_OFF

                        Switches the imager’s aim to OFF

                        +
                        + +

                        Examples

                        + +
                        Take picture with default camera
                        +

                        Take an image with as little code as possible, using all default values.

                        +
                        :::javascript
                        +
                        +           
                        +function take_picture_with_default_camera() {
                        +  // Capture an image from the default camera on the device, using the default image settings
                        +  Rho.Camera.takePicture({}, picture_taken_callback);
                        +}
                        +
                        +function picture_taken_callback(params) {
                        +  // Did we receive an image?
                        +  if (params["status"]=="ok") {
                        +    // Assuming we have an <img id="#captured_image"> tag, we will be able to see the image that was just captured
                        +    $("#captured_image").attr("src", Rho.Application.expandDatabaseBlobFilePath(params["imageUri"]));
                        +  }
                        +}
                        +                   
                        +                 
                        :::ruby
                        +
                        +           
                        +def take_picture_with_default_camera
                        +  # Capture an image from the default camera on the device, using the default image settings
                        +  Rho::Camera.takePicture({}, :picture_taken_callback)
                        +end
                        +
                        +def picture_taken_callback
                        +  # Did we really take a picture?
                        +  if (@params["status"]=="ok")
                        +    # If so, show it
                        +    Rho::WebView.navigate(url_for(:action => :show_picture, :query => {:image => Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"])}))
                        +  else
                        +    # Otherwise we are done here
                        +    Rho::WebView.navigate(url_for(:action => :index))
                        +  end
                        +end
                        +                   
                        +                 
                        Choose which camera to use when taking images
                        +

                        On devices with more than one camera, you can select which camera to use for taking pictures.

                        +
                        :::javascript
                        +
                        +           
                        +<div id="camera_list">
                        +</div>
                        +
                        +
                        +var cameras = [];
                        +
                        +function choose_camera() {
                        +  // get all available cameras
                        +  cameras = Rho.Camera.enumerate();
                        +
                        +  // build an HTML list
                        +  var cameraList = "<ul>";
                        +
                        +  for (var cameraIndex=0; cameraIndex<cameras.length; cameraIndex++) {
                        +    var camera = cameras[cameraIndex];
                        +    // Create a link for each camera with an onclick handler
                        +    cameraList = cameraList +'<li><a href="#" class="take_picture_with_selected_camera" onclick="take_picture_with_camera('+cameraIndex+')">'+camera.cameraType+'</a></li>';
                        +  }
                        +
                        +  cameraList = cameraList+"</ul>";
                        +
                        +  // make camera list visible to the user
                        +  $("#camera_list").html(cameraList);
                        +}
                        +
                        +function take_picture_with_camera(cameraIndex) {
                        +  var camera = cameras[cameraIndex];
                        +  camera.takePicture({}, picture_taken_callback);
                        +}
                        +                   
                        +                 
                        :::ruby
                        +
                        +           
                        +# controller.rb
                        +def choose_camera
                        +  $cameras = Rho::Camera.enumerate
                        +  render
                        +end
                        +
                        +def take_picture_using_chosen_camera
                        +  camera = $cameras[@params["cameraIndex"].to_i]
                        +  camera.takePicture({}, url_for(:action => :picture_taken_callback))
                        +end
                        +
                        +
                        +# choose_camera.erb
                        +<ul data-role="listview">
                        +  <% $cameras.each_with_index do |camera, index| %>
                        +    <li><a href="<%= url_for(:action => :take_picture_using_chosen_camera, :query => {:camera_index => index}) %>"><%= camera.cameraType %></li>
                        +  <% end %>
                        +</ul>
                        +                   
                        +                 
                        Saving a picture to the device's gallery
                        +

                        Apart from taking new pictures, you can also save images to the built-in gallery. In the following examples, the picture we are adding to the gallery is one that was just taken with the camera, but you can add any other image you can access by filename.

                        +
                        :::javascript
                        +
                        +           
                        +function take_picture_and_save_it_to_gallery() {
                        +  Rho.Camera.choosePicture({}, picture_taken_callback_save_to_gallery);
                        +}
                        +
                        +function picture_taken_callback_save_to_gallery(params) {
                        +  if (params["status"]=="ok") {
                        +    Rho.Camera.copyImageToDeviceGallery(Rho.Application.expandDatabaseBlobFilePath(params["imageUri"]));
                        +
                        +    alert("Image saved to gallery");
                        +  }
                        +}
                        +                   
                        +                 
                        :::ruby
                        +
                        +           
                        +def take_picture_and_save_it_to_gallery
                        +  Rho::Camera.choosePicture({}, url_for(:action => :picture_taken_callback_save_to_gallery))
                        +end
                        +
                        +def picture_taken_callback_save_to_gallery
                        +  # Did we really take a picture?
                        +  if (@params["status"]=="ok")
                        +    # If so, save it to the gallery
                        +    Rho::Camera.copyImageToDeviceGallery(Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"]))
                        +  end
                        +
                        +  Rho::WebView.navigate(url_for(:action => :index))
                        +
                        +end
                        +                   
                        +                 
                        Control image properties
                        +

                        You can tweak multiple options to get an image exactly as you need it

                        +
                        :::javascript
                        +
                        +           
                        +function control_image_properties() {
                        +  // Instead of accepting the defaults, let's set some properties to our liking
                        +
                        +  // We will ask for a PNG file...
                        +  Rho.Camera.compressionFormat = "png";
                        +
                        +  // ...a particular image size...
                        +  Rho.Camera.desiredWidth = 1024;
                        +  Rho.Camera.desiredHeight = 768;
                        +
                        +  // ...and force the flash to be used
                        +  Rho.Camera.flashMode = "on";
                        +
                        +  // Now, take the picture
                        +  Rho.Camera.takePicture({}, picture_taken_callback);
                        +}
                        +
                        +function picture_taken_callback(params) {
                        +  // Did we receive an image?
                        +  if (params["status"]=="ok") {
                        +    // show it in our <img id="captured_image"> tag
                        +    $("#captured_image").attr("src", Rho.Application.expandDatabaseBlobFilePath(params["imageUri"]));
                        +  }
                        +
                        +}
                        +                   
                        +                 
                        :::ruby
                        +
                        +           
                        +def control_image_properties
                        +  # Instead of accepting the defaults, let's set some properties to our liking
                        +
                        +  # We will ask for a PNG file...
                        +  Rho::Camera.compressionFormat = "png"
                        +
                        +  # ...a particular image size...
                        +  Rho::Camera.desiredWidth = 1024
                        +  Rho::Camera.desiredHeight = 768
                        +
                        +  # ...and force the flash to be used
                        +  Rho::Camera.flashMode = "on"
                        +
                        +  # Now, take the picture
                        +  Rho::Camera.takePicture({}, :picture_taken_callback)
                        +end
                        +
                        +def picture_taken_callback
                        +  # Did we really take a picture?
                        +  if (@params["status"]=="ok")
                        +    # If so, show it
                        +    Rho::WebView.navigate(url_for(:action => :show_picture, :query => {:image => Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"])}))
                        +  else
                        +    # Otherwise we are done here
                        +    Rho::WebView.navigate(url_for(:action => :index))
                        +  end
                        +end
                        +                   
                        +                 
                        Determine camera capabilities
                        +

                        You can get all available camera properties in a single call.

                        +
                        :::javascript
                        +
                        +           
                        +function determine_camera_capabilities() {
                        +  var capabilitiesList = "<ul>";
                        +
                        +  // Get all capabilities of the camera...
                        +  var capabilities = Rho.Camera.getAllProperties();
                        +
                        +  // ... compose a nicely formatted list with their names and values ...
                        +  for (var capability in capabilities) {
                        +    capabilitiesList+="<li>"+capability+": "+capabilities[capability]+"</li>";
                        +  }
                        +
                        +  capabilitiesList += "</ul>";
                        +
                        +  // ... and show it
                        +  $("#camera_capabilities").html(capabilitiesList);
                        +}
                        +                   
                        +                 
                        :::ruby
                        +
                        +           
                        +# controller.rb
                        +
                        +def determine_camera_capabilities
                        +  # Get all camera properties
                        +  @properties = Rho::Camera.getAllProperties
                        +  render
                        +end
                        +
                        +# determine_camera_capabilities.erb
                        +    <ul data-role="listview">
                        +
                        +    <% @properties.each_pair do |name,value| %>
                        +      <li><%= name %> : <%= value %></li>
                        +    <% end %>
                        +
                        +    </ul>
                        +                   
                        +                 
                        Select picture from device gallery
                        +

                        Apart from taking new pictures, the Camera API also lets you access existing images on the device’s gallery.

                        +
                        :::javascript
                        +
                        +           
                        +function select_picture_from_gallery() {
                        +  Rho.Camera.choose_picture({}, picture_taken_callback);
                        +}
                        +
                        +function picture_taken_callback(params) {
                        +  // Did we receive an image?
                        +  if (params["status"]=="ok") {
                        +    // Show it in an <img> tag
                        +    $("#captured_image").attr("src", Rho.Application.expandDatabaseBlobFilePath(params["imageUri"]));
                        +  }
                        +}
                        +                   
                        +                 
                        :::ruby
                        +
                        +           
                        +def select_picture_from_gallery
                        +  Rho::Camera.choosePicture({}, url_for(:action => :picture_taken_callback))
                        +end
                        +
                        +def picture_taken_callback
                        +  # Did we really take a picture?
                        +  if (@params["status"]=="ok")
                        +    # If so, show it
                        +    Rho::WebView.navigate(url_for(:action => :show_picture, :query => {:image => Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"])}))
                        +  else
                        +    # Otherwise we are done here
                        +    Rho::WebView.navigate(url_for(:action => :index))
                        +  end
                        +end
                        +                   
                        +                 
                        Getting a camera instance by cameraType
                        +

                        Camera API also lets you access camera instance by cameraType.

                        +
                        :::javascript
                        +
                        +                    
                        +//get the instance by cameraType and takePicture using that instance
                        +function get_color_camera_instance() {
                        +  var camInst = Rho.Camera.getCameraByType('color');
                        +  camInst.takePicture({'outputFormat':'image'}, my_callback);
                        +}
                        +
                        +                   
                        +                  
                        Getting the list of resolutions supported by the camera
                        +

                        Camera resolution is hardware specific. Camera API supports getting the supported resolutions of a camera instance.

                        +
                        :::javascript
                        +
                        +                    
                        +function getsupporteSizeList()
                        +{
                        +var instArray = Rho.Camera.enumerate();
                        +var reslnArray = instArray[0].supportedSizeList;
                        +alert(reslnArray[0].width);
                        +alert(reslnArray[0].height);
                        +alert(reslnArray[1].width);
                        +alert(reslnArray[1].height);
                        +}
                        +                   
                        +                  
                        Transfering an image to HTTP server
                        +

                        This example demonstrate how user can transfer an image to http server. This will be useful when application is running on a remote server.

                        +
                        :::javascript
                        +
                        +                    
                        +//enumerate the available cameras on the device
                        +var camArray = EB.Camera.enumerate();
                        +
                        +//below is the callback fired by network api after image upload to the server is completed
                        +var upload_file_callback = function (args){
                        +        status = args['status'];
                        +		//a status ok indicates image transferred successfully
                        +        alert(status);
                        +       }
                        +
                        +//below is the camera call back fired after takePicture is called
                        +var camera_callbackFunc = function(cbData){ 
                        +  alert(cbData.imageUri); 
                        +  //set the upload file properties; Refer network module for more details
                        +  var uploadfileProps = {
                        +           url: 'http://10.233.82.51:8081/upload_image_file',
                        +          //authType: "basic",
                        +          //authUser: "admin",
                        +          //authPassword: "password",
                        +          filename: cbData.imageUri,
                        +          body: "uploading file",
                        +          fileContentType: "image/jpeg"
                        +        };
                        +   
                        +   //below is the network module API used for uploading images when camera fire the callback
                        +   EB.Network.uploadFile(uploadfileProps, upload_file_callback);      
                        + };
                        + 
                        + //below is the test function which is used for capturing an image with outputFormat set as imagePath
                        +function Test_image_transfer1()
                        +{ 
                        +  //invoke takePicture API with outputFormat as imagePath and set the callback method
                        +  camArray[0].takePicture({'fileName' : '/Application/Test/myImagename', 'outputFormat': 'imagePath'}, camera_callbackFunc);
                        +}
                        + //below is the test function which is used for choosing a picture from device with outputFormat set as imagePath
                        +function Test_image_transfer2()
                        +{ 
                        +  //invoke choosePicture API with outputFormat as imagePath and set the callback method
                        +  EB.Camera.choosePicture({'outputFormat': 'image'}, camera_callbackFunc);
                        +}
                        +      
                        +
                        +                   
                        +                  
                        Dispalying an image using image uri.
                        +

                        This example demonstrate how user can dispaly an image using image uri. The callback will return a image uri when outputFormat is set to ‘image’

                        +
                        :::javascript
                        +
                        +                    
                        +//enumerate the available cameras on the device
                        +var camArray = EB.Camera.enumerate();
                        +
                        +
                        +
                        +//below is the camera call back fired after takePicture is called
                        +var camera_callbackFunc = function(cbData){ 
                        +
                        +  //uri will have relative path info only
                        +  //user has to form the absolute local server path as shown below
                        +  uri = 'http://localhost:'+EB.System.localServerPort + cbData.imageUri;
                        +  //set the image uri to the image element
                        +  document.getElementById('imageUri').src = uri ;
                        +  
                        + };
                        + 
                        + //below is the test function which is used for capturing an image with outputFormat set as image
                        +function Test_image_uri()
                        +{ 
                        +  //invoke takePicture API with outputFormat as image and set the callback method
                        +  camArray[0].takePicture({'outputFormat': 'image'}, camera_callbackFunc);
                        +}
                        +      
                        +
                        +                   
                        +                  
                        + +

                        Remarks

                        + +
                        SD Card Access

                        SD Card access is enabled by default; grants of additional access will be ignored. The following extensions are able to write to the SD card by default.

                        +
                        Camera Preview

                        Despite a user-selected full screen mode, preview rendering size will be overridden by the driver on some WM/CE devices.

                        +
                        DataUri

                        DataUri output is dependent on availability of virtual space. DataUri may fail, be unresponsive, cause reboot, degraded performance or fail to load in certain devices. In such cases, image path is recommended.

                        +
                        ImageUri

                        Image Uri display is dependent on browser capability.

                        +
                        GetSupportedProperties in WP8

                        WP8 does not support getSupportedProperties or SetSupportedProperties.

                        +
                        colorModel as Grayscale in Android

                        Grayscale is supported only in the front camera of Android consumer devices.

                        +
                        Invalid/Null values for properties in Android and iOS

                        Only valid and non-empty values for properties are supported in Android and iOS.

                        +
                        Ruby Support

                        Due to platform limitations, imager and color camera are not supported in ruby applications for CE5 and CE6 devices.

                        +
                        Camera in Suspend mode

                        All WM and CE7 devices automatically turn off both color and imager cameras when the device is suspended. User must restart the camera to resume. Whereas CE5 (eg: MC9000) and CE6 (eg: MC31) devices retain the preview on resuming from suspend state.

                        +
                        Image saving after taking picture

                        In some devices (eg: Samsung), an image will be saved in landscape mode even if captured in portrait mode. This behavior is determined by the device’s default settings.

                        +
                        WM/CE devices lacking support

                        Due to platform limitations, the ES400, MC65 and MC67 do not support the color camera.

                        +
                        takePicture resolution issue on low-memory devices with WM

                        Due to platform limitations, the ES400, MC65 and MC67 do not support a color camera. The imager on the MC55 with WM does not support the Fullscreen window (eg: takePicture). Parameters such as previewLeft, previewWidth, previewTop and previewHeight are supported by the device to set up a user-defined viewer window.

                        +
                        takePicture resolution issue on low-memory devices with WM

                        Processor limitations of some devices may cause a low-resolution image captures to appear as a small preview with a black background when transitioning back to the application.

                        +
                        Android KitKat gallery displays black image

                        For images captured with the camera using a Rho app, the image might initially appear black. Refresh the view to correct the problem.

                        +
                        Android preview

                        High-resolution settings are not recommended for low-memory devices. Image previews on tablet devices might appear stretched or shrunken.

                        +
                        \ No newline at end of file diff --git a/docs/en/5.5/api/camera.xml b/docs/en/5.5/api/camera.xml new file mode 100644 index 00000000..11535610 --- /dev/null +++ b/docs/en/5.5/api/camera.xml @@ -0,0 +1,1011 @@ + + + + + The Camera API provides access to the device camera(s). Use this API to give users the ability to take a photo via one of the cameras and return it to the application. Photos can either be stored on the device as an image file or returned as a DataURI object for storage and/or display. Optionally, image files also can be transfered to online storage using the Network API. + +## Enabling the API +To use this API, the following extension must be included in the `build.yml`: + :::ruby + extensions: ["mediacapture"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + + +## Enabling the API + +There are two methods of enabling the Camera API: + +* Include all 'ebapi' modules +* Include only the API modules you need + +Both methods are explained below. + +Either way, the included files will be found in: +`/Enterprise Browser/JavaScript Files/Enterprise Browser`, +a directory on the computer that contains the Enterprise Browser installation. + +### Include all JS API modules +To include all JavaScript APIs, copy the `ebapi-modules.js` file to a location accessible by your app's files and include the JavaScript modules file in your app. For instance, to include the modules file in your `index.html`, copy the file to the same directory as your index.html and add the following line to the HEAD section of your index.html file: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> This will define the EB class within the page. **Note that the path for this file is relative to the current page** (index.html). Any page on which the modules are required will need to have the required .js file(s) included in this fashion. + +### Include only the modules you need +To include individual APIs, you must first include the `ebapi.js` in your HTML, and then the additional required API file(s). For instance, to use the Camera API, add the following code to the HTML file(s). Again, this assumes that relevant API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.camera.js"></script> + +> In the code lines above, notice that `ebapi.js` is included first, followed by `eb.camera.js`, which is the Camera API for Enterprise Browser. **This coding is required on each HTML page whenever an individual API will be called from that page**. + + + Android, iOS, WM, CE, WP8 + WM, Android + + + + + + + + + + + + + + + Back camera. This is not supported in WM/CE devices. + + + Front camera. This is not supported in WM/CE devices. + + + Camera is an imager. This is supported only in WM/CE devices. + + + Camera is color camera. This is supported only in WM/CE devices. + + + + JPG compression. + + + PNG compression. + + + + This shall provide the image uri. This can be used to display image directly on the page. An example is shown in the example section + + + This is a base 64 encoding of the image and can be used to easily embed the image on the page or store the image in a database. On some consumer devices, captured image will be rotated 90 degrees while displaying. + + + If this value used for setting the outputFormat property, the takePicture or capture API will return imageUri as the path to the saved image in the device. User can use this image path to transfer the file to an http server if required. An example is given to demonstrate, transferring a file to http server.This property is not applicable for Android and windows phone 8. + + + + A colour image is captured. + + + A grayscale image is captured. + + + + Flash will be used. + + + Flash will not be used. + + + Flash will be used if lighting conditions deem it necessary. This is not supported in WM/CE devices. + + + Flash with red eye reduction is used. This is supported only in Android devices. + + + The flash is turned on in torch mode. This is supported only in Android devices. + + + + Switches the imager's aim to ON + + + Switches the imager's aim to OFF + + + + These properties are used to configure the Camera. + + + + + + + + + + + + + + + Android, iOS, WP8, WM, CE + WM, CE, Android + This property is device specific. The value for this property can be either 'back' or 'front' in the case of Android/iOS/WP8 devices.In the case of WM/CE it could be either 'imager' or 'color'. WM/CE devices will use 'color'as default and if color camera not available the default value will be 'imager'. Android/iOS/WP8 devices will use 'back'as default and if back camera not available the default value will be 'front', + This Property shall return one among the values mentioned in constant section which starts with CAMERA_TYPE_... + + This property is device specific. The value for this property can be either 'back' or 'front' in the case of Android devices.In the case of windows it could be either 'imager' or 'color'. WM/CE devices will use 'color'as default and if color camera not available the default value will be 'imager'. Android devices will use 'back'as default and if back camera not available the default value will be 'front'. + This Property shall return one among the values mentioned in constant section which starts with CAMERA_TYPE_... + + + + Android, iOS, WP8, WM, CE + WM, CE, Android + The maximum width of images which can be captured. This is measured in pixels. On WM/CE devices this is applicable only for color camera. Imager does not support this property. + + + Android, iOS, WP8, WM, CE + WM, CE, Android + The maximum height of images which can be captured. This is measured in pixels. On WM/CE devices this is applicable only for color camera. Imager does not support this property. + + + + + + + + + Android, WP8, WM, CE, iOS + WM, CE, Android + List of resolutions (width and height in pixels) supported by the camera. On WM/CE devices this feature is supported only by color camera and it is not supported by imager. Refer example section for more details. + + + 2.0.0 + Android, iOS, WM, CE, WP8 + WM, CE, Android + Camera hardware is limited to taking photos in a finite number of resolutions, eg 2048x1536, 640x480 etc. Specifying a desiredWidth will request to take the photo with the specified width but if it is not supported by the hardware then the closest match will be selected. The callback received when a photo is taken contains the actual resolution of the captured photo. + + + 2.0.0 + Android, iOS, WM, CE, WP8 + WM, CE, Android + Camera hardware is limited to taking photos in a finite number of resolutions, eg 2048x1536, 640x480 etc. Specifying a desiredHeight will request to take the photo with the specified height but if it is not supported by the hardware then the closest match will be selected. The callback received when a photo is taken contains the actual resolution of the captured photo. + + + 4.0.0 + Android, iOS, WM, CE, WP8 + WM, CE, Android + The image file path without file extension to store captured image in subsequent calls to takePicture() or capture(). Default filename will be IMG_timestamp and will be saved under root directory. The filename extension will be added automatically according to compressionFormat property value. + In Wp8, only filename can be changed, by default the path shall be under picture=>CameraRoll + + + 4.0.0 + JPG is supported on all devices, Android, WP8 and Windows Mobile does not support PNG images + Android, iOS, WM, CE, WP8 + WM, CE, Android + The format of the captured image in subsequent calls to takePicture(). If you do not define this property when you use choose_picture with iOS, the type of image in Gallery will be recognized, and the same format will be used for saving the image to applications data. In windows and WP8 devices the format will be always jpg type. + This Property shall accept/return one among the values mentioned in constant section which starts with COMPRESSION_FORMAT_... + + The format of the captured image in subsequent calls to takePicture(). On windows devices the format will be always .jpg type. + This Property shall accept/return one among the values mentioned in constant section which starts with COMPRESSION_FORMAT_... + + + + + 4.0.0 + Android, iOS, WM, CE, WP8 + WM, CE, Android + Specifies the way to return the captured image to the application. + This Property shall accept/return one among the values mentioned in constant section which starts with OUTPUT_FORMAT_... + Specifies the way to return the captured image to the application. + This Property shall accept/return one among the values mentioned in constant section which starts with OUTPUT_FORMAT_... + + + + + 2.0.0 + Android, iOS + Android + Where supported by the hardware this property can be used to select whether to capture a color or a grayscale image. + This Property shall accept/return one among the values mentioned in constant section which starts with COLOR_MODEL_... + Where supported by the hardware this property can be used to select whether to capture a color or a grayscale image. + This Property shall accept/return one among the values mentioned in constant section which starts with COLOR_MODEL_... + + + + + 2.0.0 + iOS + Enables post photo capture image customizing; image will captured reduced to screen size (not full size of camera sensor). + + + 2.0.0 + Android, WM, CE, iOS, WP8 + Android, WM, CE + Specifies the flash behavior when taking a picture. + This Property shall accept/return one among the values mentioned in constant section which starts with FLASH_... + Specifies the flash behavior when taking a picture. + This Property shall accept/return one among the values mentioned in constant section which starts with FLASH_... + + + + 2.0.0 + iOS,Android + Android + If true, the picture you take will be added to the device photo gallery. + + + 4.0.0 + Android, WM, CE + Android, WM, CE + Path to a sound file resident on the device which will be played when the image is captured. + + + 4.0.0 + WM, CE + In cases where the resident camera application on the device is not used this API is used to control the position of the viewfinder preview window when taking a photo. + + + 4.0.0 + WM, CE + In cases where the resident camera application on the device is not used this API is used to control the position of the viewfinder preview window when taking a photo. + + + 4.0.0 + WM, CE + In cases where the resident camera application on the device is not used this API is used to control the position of the viewfinder preview window when taking a photo. + + + 4.0.0 + WM, CE + In cases where the resident camera application on the device is not used this API is used to control the position of the viewfinder preview window when taking a photo. + + + 4.0.0 + Android + Setting the value of this property to "true", shall open the System ViewFinder with its properties. None of the Rho camera properties shall be applicable. + + + WM, CE + Specifies the aim behaviour when taking a picture. Applicable only for imager module. + This Property shall accept/return one among the values mentioned in constant section which starts with AIM_... + Specifies the aim behaviour when taking a picture. Applicable only for imager module. + This Property shall accept/return one among the values mentioned in constant section which starts with AIM_... + + + + + + + + + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + Returns the cameras present on your device, allowing you to access your device's front or back camera. + + Array of objects. + + + + + Android, iOS, WP8, WM, CE + Android, WM, CE + Returns the camera of requested type if that camera exist - else return nil. + + + CameraType: 'back' or 'front' in the case of Android, iOS and WP8 and 'color' or 'imager' in the case of WM, CE devices + CameraType: 'back' or 'front' in the case of Android and 'color' or 'imager' in the case of WM, CE devices + + + + Camera with requested type or nil if not requested type does not exist. Refer example section for more details. + + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + Start the camera application to take a picture. The user can capture the displayed image by interacting with the resident camera app. In Windows, this method always shows the preview in full screen and user can use the native button to capture the image. + On wp8,wm when 'outputFormat' is 'image' then imageUri/image_uri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when 'outputFormat' is 'image' +> Note: To display an image, it is recommended that you use the full path to the image instead of a relative path. To do this, you can use the [`expandDatabaseBlobFilePath`](Application#mexpandDatabaseBlobFilePath) method of the [Application module](Application) as such: + +##### Ruby + :::ruby + Rho::RhoApplication.expandDatabaseBlobFilePath(x.image_uri) + +##### JavaScript + :::js + Rho.RhoApplication.expandDatabaseBlobFilePath(x.image_uri) + + + + Provide a set of properties to configure the camera, for example to specify the flashMode or compressionFormat. + + Not providing properties to this function will use the Camera's default properties, or those previously set on the Camera instance. + + + + + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + Whether or not the image was successfully captured. The returned string will be one of 'ok', 'cancel' or 'error'. + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device.On wp8,wm when 'outputFormat' is 'image' then imageUri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when 'outputFormat' is 'image', this image will have an auto-generated name. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + The actual height of the image that was captured, this may differ from the requested height as the Camera will only support a finite resolutions. + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + The actual width of the image that was captured, this may differ from the requested width as the Camera will only support a finite resolutions. + + + Android, WM, CE, iOS + Android, WM, CE + The format in which the image was captured, either 'png' or 'jpg'. + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + If the returned status is 'error' then this field will contain more information on the error. To maintain backward compatibility WM and Android platforms provides message for cancel status as well. + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device.On wp8,wm when 'outputFormat' is 'image' then imageUri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when 'outputFormat' is 'image', this image will have an auto-generated name. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + It is recommended to use imageHeight in preference to this parameter. + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + It is recommended to use imageWidth in preference to this parameter. + + + Android, WM, CE, iOS + Android, WM, CE + It is recommended to use imageFormat in preference to this parameter. + + + + + + Shows the preview in user configurable viewer window. + WM, CE + WM, CE + + + Provide a set of properties to configure the camera. + + Not providing properties to this function will use the Camera's default properties, or those previously set on the Camera instance. + + + + + + Hides the preview opened by using showPreview. + WM, CE + WM, CE + + + Capture the image and save it to a file. + WM, CE + WM, CE + + + + Whether or not the image was successfully captured. The returned string will be one of 'ok' or 'error'. + + + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + + + The actual height of the image that was captured, this may differ from the requested height as the Camera will only support a finite resolutions. + + + The actual width of the image that was captured, this may differ from the requested width as the Camera will only support a finite resolutions. + + + The format in which the image was captured, either 'png' or 'jpg'. + + + If the returned status is 'error' then this field will contain more information on the error. + + + + + + Choose a picture from the album. + + + Android, WM, CE, WP8, iOS + Android, WM, CE + Provide a set of properties to configure an image, for example to specify the image size or color mode. In WM/CE,Android and WP8 devices user can only specify the outputFormat in the property bag. In iOS devices user can specify next options: compressionFormat, desiredWidth, desiredHeight, outputFormat, colorModel, enableEditing. + In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri.On wp8, wm when 'outputFormat' is 'image' then imageUri or image_uri shall have Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when 'outputFormat' is 'image' + Provide a set of properties to configure an image, for example to specify the image size or color mode. In WM/CE,Android devices user can only specify the outputFormat in the property bag. + + Not providing properties to this function will use the Camera's default properties, or those previously set on the Camera instance. + + + + + + + Whether or not the image was successfully chosen from the gallery. The returned string will be one of 'ok', 'cancel' or 'error'. + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device.On wp8,wm when 'outputFormat' is 'image' then imageUri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when 'outputFormat' is 'image', this image will have an auto-generated name. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + + + The height of the image. + + + The width of the image. + + + The format of the image, either 'png' or 'jpg'. + + + If the returned status is 'error' then this field will contain more information on the error. To maintain backward compatibility WM and Android platforms provides message for cancel status as well. + + + Android, WM, CE, iOS, WP8 + Android, WM, CE + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device.On wp8,wm when 'outputFormat' is 'image' then imageUri shall have only Image name with \ sign, on WP8 ImageName shall be suffixed by DTF when 'outputFormat' is 'image', this image will have an auto-generated name. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, In Wp8 dataUri shall provide the thumbnail for the picture taken, It is recommended to use Image over dataUri. If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + If the specified 'outputFormat' was 'image' then this field is the URI to the taken image stored on the device. If the specified 'outputFormat' was 'dataUri' then this field will be the image encoded as a Data URI, If the specified 'outputFormat' was 'imagePath' then this field will have the image path on the device. User can use image path to transfer image over http. + + + It is recommended to use imageHeight in preference to this parameter. + + + It is recommended to use imageWidth in preference to this parameter. + + + It is recommended to use imageFormat in preference to this parameter. + + + + + + iOS, Android + Android + Save an image to the device gallery. + + + The real path to the image that is to be saved in the device gallery. You need to use the RhoApplication method `expandDatabaseBlobFilePath` to have the real path, such as `Rho::RhoApplication::expandDatabaseBlobFilePath(img.image_uri)`. + + + + + + + + + + 4.0.0 + + + + + + +
                        + Take an image with as little code as possible, using all default values. + + + :show_picture, :query => {:image => Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"])})) + else + # Otherwise we are done here + Rho::WebView.navigate(url_for(:action => :index)) + end +end + ]]> + + + tag, we will be able to see the image that was just captured + $("#captured_image").attr("src", Rho.Application.expandDatabaseBlobFilePath(params["imageUri"])); + } +} + ]]> + + +
                        +
                        +
                        + + +
                        + On devices with more than one camera, you can select which camera to use for taking pictures. + + + :picture_taken_callback)) +end + + +# choose_camera.erb + + ]]> + + + + + + +var cameras = []; + +function choose_camera() { + // get all available cameras + cameras = Rho.Camera.enumerate(); + + // build an HTML list + var cameraList = ""; + + // make camera list visible to the user + $("#camera_list").html(cameraList); +} + +function take_picture_with_camera(cameraIndex) { + var camera = cameras[cameraIndex]; + camera.takePicture({}, picture_taken_callback); +} + ]]> + + +
                        +
                        +
                        + + +
                        + Apart from taking new pictures, you can also save images to the built-in gallery. In the following examples, the picture we are adding to the gallery is one that was just taken with the camera, but you can add any other image you can access by filename. + + + :picture_taken_callback_save_to_gallery)) +end + +def picture_taken_callback_save_to_gallery + # Did we really take a picture? + if (@params["status"]=="ok") + # If so, save it to the gallery + Rho::Camera.copyImageToDeviceGallery(Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"])) + end + + Rho::WebView.navigate(url_for(:action => :index)) + +end + ]]> + + + + + +
                        +
                        +
                        + + +
                        + You can tweak multiple options to get an image exactly as you need it + + + :show_picture, :query => {:image => Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"])})) + else + # Otherwise we are done here + Rho::WebView.navigate(url_for(:action => :index)) + end +end + ]]> + + + tag + $("#captured_image").attr("src", Rho.Application.expandDatabaseBlobFilePath(params["imageUri"])); + } + +} + ]]> + + +
                        +
                        +
                        + + +
                        + You can get all available camera properties in a single call. + + + + + <% @properties.each_pair do |name,value| %> +
                      • <%= name %> : <%= value %>
                      • + <% end %> + + + ]]> +
                        + + "; + + // Get all capabilities of the camera... + var capabilities = Rho.Camera.getAllProperties(); + + // ... compose a nicely formatted list with their names and values ... + for (var capability in capabilities) { + capabilitiesList+="
                      • "+capability+": "+capabilities[capability]+"
                      • "; + } + + capabilitiesList += ""; + + // ... and show it + $("#camera_capabilities").html(capabilitiesList); +} + ]]> +
                        +
                        +
                        +
                        +
                        + + +
                        + Apart from taking new pictures, the Camera API also lets you access existing images on the device's gallery. + + + :picture_taken_callback)) +end + +def picture_taken_callback + # Did we really take a picture? + if (@params["status"]=="ok") + # If so, show it + Rho::WebView.navigate(url_for(:action => :show_picture, :query => {:image => Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"])})) + else + # Otherwise we are done here + Rho::WebView.navigate(url_for(:action => :index)) + end +end + ]]> + + + tag + $("#captured_image").attr("src", Rho.Application.expandDatabaseBlobFilePath(params["imageUri"])); + } +} + ]]> + + +
                        +
                        +
                        + + +
                        + Camera API also lets you access camera instance by cameraType. + + + + + +
                        +
                        +
                        + + +
                        + Camera resolution is hardware specific. Camera API supports getting the supported resolutions of a camera instance. + + + + + +
                        +
                        +
                        + + +
                        + This example demonstrate how user can transfer an image to http server. This will be useful when application is running on a remote server. + + + + + +
                        +
                        +
                        + + +
                        + This example demonstrate how user can dispaly an image using image uri. The callback will return a image uri when outputFormat is set to 'image' + + + + + +
                        +
                        +
                        +
                        + + + SD Card access is enabled by default; grants of additional access will be ignored. The following extensions are able to write to the SD card by default. + + + Despite a user-selected full screen mode, preview rendering size will be overridden by the driver on some WM/CE devices. + + + DataUri output is dependent on availability of virtual space. DataUri may fail, be unresponsive, cause reboot, degraded performance or fail to load in certain devices. In such cases, image path is recommended. + + + Image Uri display is dependent on browser capability. + + + WP8 does not support getSupportedProperties or SetSupportedProperties. + + + Grayscale is supported only in the front camera of Android consumer devices. + + + Only valid and non-empty values for properties are supported in Android and iOS. + + + Due to platform limitations, imager and color camera are not supported in ruby applications for CE5 and CE6 devices. + + + All WM and CE7 devices automatically turn off both color and imager cameras when the device is suspended. User must restart the camera to resume. Whereas CE5 (eg: MC9000) and CE6 (eg: MC31) devices retain the preview on resuming from suspend state. + + + In some devices (eg: Samsung), an image will be saved in landscape mode even if captured in portrait mode. This behavior is determined by the device's default settings. + + + Due to platform limitations, the ES400, MC65 and MC67 do not support the color camera. + + + Due to platform limitations, the ES400, MC65 and MC67 do not support a color camera. The imager on the MC55 with WM does not support the Fullscreen window (eg: takePicture). Parameters such as previewLeft, previewWidth, previewTop and previewHeight are supported by the device to set up a user-defined viewer window. + + + Processor limitations of some devices may cause a low-resolution image captures to appear as a small preview with a black background when transitioning back to the application. + + + For images captured with the camera using a Rho app, the image might initially appear black. Refresh the view to correct the problem. + + + High-resolution settings are not recommended for low-memory devices. Image previews on tablet devices might appear stretched or shrunken. + + + +
                        +
                        diff --git a/docs/en/5.5/api/cardreader.md b/docs/en/5.5/api/cardreader.md new file mode 100644 index 00000000..5a433bf9 --- /dev/null +++ b/docs/en/5.5/api/cardreader.md @@ -0,0 +1,172 @@ +#CardReader +
                        +

                        The Card Reader module decodes the card data when read through a card reader attachment. Currently this is available only on Symbol Technologies devices.Only the foreground application is given access to the card reader hardware, when an application is sent to the background its state will be saved and it will automatically relinquish control of the card reader. When brought back to the foreground, an application previously using the card reader will have its previous configuration (eg. pinTimeout) reapplied to the card reader automatically.

                        +

                        Enabling the API

                        + +

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

                        + +
                        :::ruby
                        +extensions: ["cardreader"]
                        +
                        + +

                        The cardreader extension is also included automatically if you specify the following in your build.yml.

                        + +
                        :::ruby
                        +app_type: "rhoelements"
                        +
                        + +

                        NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

                        + +

                        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

                        + +

                        close()

                        Closes the card reader.

                        +

                        Synchronous Return:

                        • Void

                        Method Access:

                        • Instance Method: This method can be accessed via an instance object of this class:
                          • myObject.close()
                        • Default Instance: This method can be accessed via the default instance object of this class.
                          • JavaScript: Rho.CardReader.close()
                          • Ruby: Rho::CardReader.close()

                        getAllProperties(CallBackHandler callback)

                        This method will return all of object/value pairs for the propertyNames of the API class.

                        +

                        Parameters

                        • callback : CallBackHandler Optional

                        Async Callback Returning Parameters: HASH

                          • : STRING

                        Synchronous Return:

                        • HASH :

                          Map of all available properties

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

                        Method Access:

                        • Instance Method: This method can be accessed via an instance object of this class:
                          • myObject.getAllProperties(CallBackHandler callback)
                        • Default Instance: This method can be accessed via the default instance object of this class.
                          • JavaScript: Rho.CardReader.getAllProperties(CallBackHandler callback)
                          • Ruby: Rho::CardReader.getAllProperties(CallBackHandler callback)

                        getDefault()

                        This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

                        +

                        Synchronous Return:

                        • SELF_INSTANCE :

                          Default object of Module.

                          +

                        Method Access:

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

                        getProperties(ARRAY arrayofNames, CallBackHandler callback)

                        This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                        +

                        Parameters

                        • arrayofNames : ARRAY

                          List of properties I want to know about

                          +

                          • Object : STRING

                        • callback : CallBackHandler Optional

                        Async Callback Returning Parameters: HASH

                          • : STRING

                        Synchronous Return:

                        • HASH :

                          Map of properties I want to know about

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

                        Method Access:

                        • Instance Method: This method can be accessed via an instance object of this class:
                          • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                        • Default Instance: This method can be accessed via the default instance object of this class.
                          • JavaScript: Rho.CardReader.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                          • Ruby: Rho::CardReader.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                        getProperty(STRING propertyName, CallBackHandler callback)

                        This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                        +

                        Parameters

                        • propertyName : STRING

                          The property to return info about.

                          +

                        • callback : CallBackHandler Optional

                        Async Callback Returning Parameters: STRING

                          Synchronous Return:

                          • STRING :

                            The property to return info about.

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

                          Method Access:

                          • Instance Method: This method can be accessed via an instance object of this class:
                            • myObject.getProperty(STRING propertyName, CallBackHandler callback)
                          • Default Instance: This method can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.getProperty(STRING propertyName, CallBackHandler callback)
                            • Ruby: Rho::CardReader.getProperty(STRING propertyName, CallBackHandler callback)

                          open(CallBackHandler callback)

                          Opens the card reader.

                          +

                          Parameters

                          • callback : CallBackHandler Optional

                          Async Callback Returning Parameters: HASH

                            • data : STRING

                              Data read by the card reader. This may be card data, the PAN data extracted from the card data, encrypted PIN block data, or a message. In case of an ISO/ABA card [eg: a financial card], data is encrypted. For other cards, data is in the clear.

                              +

                            • mode : STRING

                              Describes the data. This will be either: ‘CR’,‘ENCDATA’,‘PAN’, or ‘MESSAGE’. This equates to card data, encrypted PIN block data, PAN data, or a message, respectively.

                              +

                            • encryption : BOOLEAN

                              This provides the information regarding the card reader head configuration. Available only on Android.

                              +

                            • rawData : STRING

                              This is the raw data read by the card reader from all the tracks. Available only on Android and the value is in HEX format.

                              +

                            • track1 : STRING

                              The track1 clear/masked data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track1Status value returned is true.

                              +

                            • track2 : STRING

                              The track2 clear/masked data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track2Status value returned is true.

                              +

                            • track3 : STRING

                              The track3 clear/masked data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track3Status value returned is true.

                              +

                            • track1Status : BOOLEAN

                              The status of the track1 clear/masked data read by the card reader. Available only on Android.

                              +

                            • track2Status : BOOLEAN

                              The status of the track2 clear/masked data read by the card reader. Available only on Android.

                              +

                            • track3Status : BOOLEAN

                              The status of the track3 clear/masked data read by the card reader. Available only on Android.

                              +

                            • track1Encrypted : STRING

                              The track1 encrypted data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track1EncryptedStatus value returned is true.

                              +

                            • track2Encrypted : STRING

                              The track2 encrypted data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track2EncryptedStatus value returned is true.

                              +

                            • track3Encrypted : STRING

                              The track3 encrypted data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track3EncryptedStatus value returned is true.

                              +

                            • track1EncryptedStatus : BOOLEAN

                              The status of the track1 encrypted data read by the card reader. Available only on Android.

                              +

                            • track2EncryptedStatus : BOOLEAN

                              The status of the track2 encrypted data read by the card reader. Available only on Android.

                              +

                            • track3EncryptedStatus : BOOLEAN

                              The status of the track3 encrypted data read by the card reader. Available only on Android.

                              +

                            • ksn : STRING

                              The encrypted KSN serial number read by the card reader. Available only on Android. The value is in HEX format.

                              +

                          Synchronous Return:

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

                          Method Access:

                          • Instance Method: This method can be accessed via an instance object of this class:
                            • myObject.open(CallBackHandler callback)
                          • Default Instance: This method can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.open(CallBackHandler callback)
                            • Ruby: Rho::CardReader.open(CallBackHandler callback)

                          setDefault(SELF_INSTANCE: Rho::CardReader defaultInstance)

                          This method allows you to set the attributes of the default object instance by passing in an object of the same class.

                          +

                          Parameters

                          • defaultInstance : SELF_INSTANCE: Rho::CardReader

                            An instance object that is of the same class.

                            +

                          Synchronous Return:

                          • Void

                          Method Access:

                          • Class Method: This method can only be accessed via the API class object.
                            • JavaScript: Rho.CardReader.setDefault(SELF_INSTANCE: Rho::CardReader defaultInstance)
                            • Ruby: Rho::CardReader.setDefault(SELF_INSTANCE: Rho::CardReader defaultInstance)

                          setProperties(HASH propertyMap)

                          This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                          +

                          Parameters

                          • propertyMap : HASH

                            Map of properties I want to set

                            +

                            • Object : STRING

                          Synchronous Return:

                          • Void

                          Method Access:

                          • Instance Method: This method can be accessed via an instance object of this class:
                            • myObject.setProperties(HASH propertyMap)
                          • Default Instance: This method can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.setProperties(HASH propertyMap)
                            • Ruby: Rho::CardReader.setProperties(HASH propertyMap)

                          setProperty(STRING propertyName, STRING propertyValue)

                          This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                          +

                          Parameters

                          • propertyName : STRING

                            The one property name that I want to set

                            +

                          • propertyValue : STRING

                            The one property value that I want to set

                            +

                          Synchronous Return:

                          • Void

                          Method Access:

                          • Instance Method: This method can be accessed via an instance object of this class:
                            • myObject.setProperty(STRING propertyName, STRING propertyValue)
                          • Default Instance: This method can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.setProperty(STRING propertyName, STRING propertyValue)
                            • Ruby: Rho::CardReader.setProperty(STRING propertyName, STRING propertyValue)
                          + +

                          Properties

                          + +

                          autoEnter : BOOLEAN

                          When enabled, appends a carriage return to any data returned as keystrokes by the cardreader. This is useful for auto submitting returned data without extra interaction necessary.

                          +

                          Default: false

                          Property Access:

                          • Instance: This property can be accessed via an instance object of this class:
                            • myObject.autoEnter
                          • Default Instance: This property can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.autoEnter
                            • Ruby: Rho::CardReader.autoEnter

                          autoTab : BOOLEAN

                          When enabled, appends a tab to any data returned as keystrokes by the cardreader. This is useful when filling out a form so that you can move to the next field without extra interaction necessary.

                          +

                          Default: false

                          Property Access:

                          • Instance: This property can be accessed via an instance object of this class:
                            • myObject.autoTab
                          • Default Instance: This property can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.autoTab
                            • Ruby: Rho::CardReader.autoTab

                          moduleName : STRING

                          Deprecated

                          This method is present to provide backwards compatibility with PocketBrowser code, devices supported by RhoElements will have a single card reader driver installed as part of the platform. If the device has multiple card reader drivers installed this parameter is used to select which driver to use. The drivers present are output in the log file when the card reader is initialized. This parameter is also used to distinguish between an MSR and a DCR, e.g. if you attach a DCR7000 to your device you can specify that only the MSR functionality is used by specifying this parameter as ‘MSR7000’.

                          +

                          Possible Values (STRING):

                          Constant: Rho.CardReader.MSR9000 (For Ruby use "::" for all "." when referencing constants)
                          String: msr9000

                          MSR9000 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSR3000.DLL.

                          +
                          Constant: Rho.CardReader.MSR9001 (For Ruby use "::" for all "." when referencing constants)
                          String: msr9001

                          MSR9001 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSR3000.DLL.

                          +
                          Constant: Rho.CardReader.MSR9500 (For Ruby use "::" for all "." when referencing constants)
                          String: msr9500

                          MSR9500 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRMC50.DLL.

                          +
                          Constant: Rho.CardReader.MSRCAMEO (For Ruby use "::" for all "." when referencing constants)
                          String: msrcameo

                          MSRCAMEO drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRCAMEO.DLL.

                          +
                          Constant: Rho.CardReader.MSR7000 (For Ruby use "::" for all "." when referencing constants)
                          String: msr7000

                          MSR7000 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRMC50.DLL.

                          +
                          Constant: Rho.CardReader.DCR7000 (For Ruby use "::" for all "." when referencing constants)
                          String: dcr7000

                          DCR7000 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRMC50.DLL.

                          +
                          Constant: Rho.CardReader.MSR55 (For Ruby use "::" for all "." when referencing constants)
                          String: msr55

                          MSR55 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRMC55.DLL.

                          +
                          Constant: Rho.CardReader.MSR3000 (For Ruby use "::" for all "." when referencing constants)
                          String: msr3000

                          MSR3000 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSR3000.DLL.

                          +

                          Property Access:

                          • Instance: This property can be accessed via an instance object of this class:
                            • myObject.moduleName
                          • Default Instance: This property can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.moduleName
                            • Ruby: Rho::CardReader.moduleName

                          panData : STRING

                          Sets the card data without the need of a swipe. This accepts any 16 digit number as the string value. Ensure that pinEntry is true before getting the property of panData.

                          +

                          (Only compatible with DCR7000-x00)

                          Property Access:

                          • Instance: This property can be accessed via an instance object of this class:
                            • myObject.panData
                          • Default Instance: This property can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.panData
                            • Ruby: Rho::CardReader.panData

                          pinEntry : BOOLEAN

                          Turns the PIN entry on or off.

                          +

                          (Only compatible with DCR7000-x00)

                          Property Access:

                          • Instance: This property can be accessed via an instance object of this class:
                            • myObject.pinEntry
                          • Default Instance: This property can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.pinEntry
                            • Ruby: Rho::CardReader.pinEntry

                          pinTimeout : INTEGER

                          PIN entry timeout in milliseconds. A value of 65535 sets the timeout to infinite. Accepts values between 0 and 65535.

                          +

                          (Only compatible with DCR7000-x00)

                          Default: 30000

                          Property Access:

                          • Instance: This property can be accessed via an instance object of this class:
                            • myObject.pinTimeout
                          • Default Instance: This property can be accessed via the default instance object of this class.
                            • JavaScript: Rho.CardReader.pinTimeout
                            • Ruby: Rho::CardReader.pinTimeout
                          + +

                          Examples

                          + +
                          Basic Example
                          +

                          The default card reader on the device is enabled when the index view is loaded. When a card is swiped the swipeEvent is called.

                          +
                          :::ruby
                          +            
                          +#/app/Model
                          +def index
                          +    Rho::CardReader.open(url_for(:action => :myswipeevent))
                          +end
                          +  def myswipeevent
                          +       puts "Swipe params: #{@params}"
                          +       puts "Mode is #{@params['mode']}"
                          +       puts "Data is #{@params['data']}"
                          +  end 
                          +                    
                          +                
                          Connect to card reader
                          +

                          Enable card reader and receive a callback when a card is swiped.

                          +
                          :::javascript
                          +
                          +           
                          +function cardreader_callback(params) {
                          +  alert("Received data from card reader: "+params["data"]);
                          +}
                          +
                          +function connect() {
                          +  Rho.CardReader.open(cardreader_callback);
                          +}
                          +                   
                          +                 
                          :::ruby
                          +
                          +           
                          +def connect
                          +  Rho::CardReader.open(url_for(:action => :cardreader_callback))
                          +  redirect :index
                          +end
                          +
                          +def cardreader_callback
                          +  Alert.show_popup("Received card reader data: #{@params[:data]}")
                          +end
                          +                   
                          +                 
                          Set card reader properties
                          +

                          There are two ways to use the card reader. One is to receive a callback when a card is swiped, the other is to have it simulate keypresses. See below for an example of this second option.

                          +
                          :::javascript
                          +
                          +           
                          +// Configure the MSR to output keystrokes instead of calling a function when a card is swiped
                          +// Note the absence of a callback parameter
                          +// Also, After emitting the keystrokes, automatically send a "Tab" keypress
                          +Rho.CardReader.autoTab = true;
                          +Rho.CardReader.open();
                          +
                          +Rho.CardReader.autoEnter = true;
                          +Rho.CardReader.open();
                          +                   
                          +                 
                          :::ruby
                          +
                          +           
                          +# Configure the MSR to output keystrokes instead of calling a function when a card is swiped
                          +# Note the absence of a callback parameter
                          +# Also, After emitting the keystrokes, automatically send a "Tab" keypress
                          +Rho::CardReader.autoTab = true
                          +Rho::CardReader.open()
                          +
                          +# Instead of "Tab", we could request a simulated "Enter" 
                          +Rho::CardReader.autoEnter = true
                          +Rho::CardReader.open()
                          +                   
                          +                 
                          + +

                          Remarks

                          + +
                          General

                          If the CardReader open method is not specified with a callback, the cardreader data will be returned as keystrokes. If both the autotab and autoenter parameters are set to “enabled”, autoenter will take precedence. An opened card reader must be closed before the attached card reader device and associated modulename parameter are changed. Any attempt to set a parameter to an invalid value, will result in no effect on the parameter’s current value. There should be made a delay around 2 secs or more between API calls which interact with hardware.

                          +
                          Operational Modes (Backwards compatibility with PocketBrowser)

                          For the DCR7000 the ModuleName parameter must be set at least once before the readevent parameter is set. If the card reader is an MSR, when a card is swiped it returns the data read from the card. Setting ModuleName to a DCR will cause the card data to be returned followed by the PAN Data before waiting for a PIN to be entered on the keypad. Once entered the PIN will be encrypted and returned by a third ReadEvent. The card must be a validly formatted IATA or ABA card.

                          +
                          Closing the reader while PIN entry pending

                          There is no way to abort a pending PIN entry (other than the customer pressing the Cancel button), for security reasons. Therefore if the reader is closed or RhoElements is quit during that time it will become unresponsive until a PIN is entered or the PIN timeout occurs.

                          +
                          Blank card data

                          In certain circumstances it is possible that the card reader may return empty card data. The JavaScript event function should be able to handle this correctly.

                          +
                          Detaching / Reattaching the Card Reader

                          Applications running in RhoElements should be resilient against the card reader being detached and subsequently reattached. Card data parsing code should be robust against unexpected characters in the first read after reattachment.

                          +
                          Encrypted Card data

                          The encrypted data is supported only on the card readers that are configured for encryption. Since the encrypted data might contain unreadable characters sometimes it is recommended to use only JSON object method rather than JavaScript ‘%s’ notation.

                          +
                          + +

                          Licensing

                          + +
                          This API is considered a RhoElements API and therefore requires a paid subscription to use (either Silver or Gold level). You can review the subscription plans on our licensing page here or on rhomobile.com/pricing.
                          \ No newline at end of file diff --git a/docs/en/5.5/api/cardreader.xml b/docs/en/5.5/api/cardreader.xml new file mode 100644 index 00000000..1da1fb39 --- /dev/null +++ b/docs/en/5.5/api/cardreader.xml @@ -0,0 +1,384 @@ + + + + + The Card Reader module decodes the card data when read through a card reader attachment. Currently this is available only on Symbol Technologies devices.Only the foreground application is given access to the card reader hardware, when an application is sent to the background its state will be saved and it will automatically relinquish control of the card reader. When brought back to the foreground, an application previously using the card reader will have its previous configuration (eg. pinTimeout) reapplied to the card reader automatically. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + :::ruby + extensions: ["cardreader"] + +The `cardreader` extension is also included automatically if you specify the following in your `build.yml`. + :::ruby + app_type: "rhoelements" + +NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + +## Enabling the API +There are two methods of enabling the CardReader API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the CardReader API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.cardreader.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + WM, CE, Android + + + These properties are used to configure the card reader. + + + PIN entry timeout in milliseconds. A value of 65535 sets the timeout to infinite. Accepts values between 0 and 65535. + WM + Only compatible with DCR7000-x00 + + + Turns the PIN entry on or off. + WM + Only compatible with DCR7000-x00 + + + Sets the card data without the need of a swipe. This accepts any 16 digit number as the string value. Ensure that pinEntry is true before getting the property of panData. + WM + Only compatible with DCR7000-x00 + + + When enabled, appends a tab to any data returned as keystrokes by the cardreader. This is useful when filling out a form so that you can move to the next field without extra interaction necessary. + WM, CE, Android + + + + When enabled, appends a carriage return to any data returned as keystrokes by the cardreader. This is useful for auto submitting returned data without extra interaction necessary. + WM, CE, Android + + + + This method is present to provide backwards compatibility with PocketBrowser code, devices supported by RhoElements will have a single card reader driver installed as part of the platform. If the device has multiple card reader drivers installed this parameter is used to select which driver to use. The drivers present are output in the log file when the card reader is initialized. This parameter is also used to distinguish between an MSR and a DCR, e.g. if you attach a DCR7000 to your device you can specify that only the MSR functionality is used by specifying this parameter as 'MSR7000'. + This method is present to provide backwards compatibility with PocketBrowser code, devices supported by the Enterprise Browser will have a single card reader driver installed as part of the platform. If the device has multiple card reader drivers installed this parameter is used to select which driver to use. The drivers present are output in the log file when the card reader is initialized. This parameter is also used to distinguish between an MSR and a DCR, e.g. if you attach a DCR7000 to your device you can specify that only the MSR functionality is used by specifying this parameter as 'MSR7000'. + WM + + + + MSR9000 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSR3000.DLL. + + + MSR9001 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSR3000.DLL. + + + MSR9500 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRMC50.DLL. + + + MSRCAMEO drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRCAMEO.DLL. + + + MSR7000 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRMC50.DLL. + + + DCR7000 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRMC50.DLL. + + + MSR55 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSRMC55.DLL. + + + MSR3000 drivers. Return value while getting the property of moduleName will be its associated DLL name i.e. MSR3000.DLL. + + + + + + + + Opens the card reader. + WM, CE, Android + + + Not providing a callback to be invoked when a card is swiped will result in that card data being output as keystrokes. In case of Android devices the RawData will be shown as keystrokes. + + + Data read by the card reader. This may be card data, the PAN data extracted from the card data, encrypted PIN block data, or a message. In case of an ISO/ABA card [eg: a financial card], data is encrypted. For other cards, data is in the clear. + + + Describes the data. This will be either: 'CR','ENCDATA','PAN', or 'MESSAGE'. This equates to card data, encrypted PIN block data, PAN data, or a message, respectively. + + + This provides the information regarding the card reader head configuration. Available only on Android. + + + This is the raw data read by the card reader from all the tracks. Available only on Android and the value is in HEX format. + + + The track1 clear/masked data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track1Status value returned is true. + + + The track2 clear/masked data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track2Status value returned is true. + + + The track3 clear/masked data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track3Status value returned is true. + + + The status of the track1 clear/masked data read by the card reader. Available only on Android. + + + The status of the track2 clear/masked data read by the card reader. Available only on Android. + + + The status of the track3 clear/masked data read by the card reader. Available only on Android. + + + The track1 encrypted data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track1EncryptedStatus value returned is true. + + + The track2 encrypted data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track2EncryptedStatus value returned is true. + + + The track3 encrypted data read by the card reader. Available only on Android and the value is in HEX format. This value should be used only when the track3EncryptedStatus value returned is true. + + + The status of the track1 encrypted data read by the card reader. Available only on Android. + + + The status of the track2 encrypted data read by the card reader. Available only on Android. + + + The status of the track3 encrypted data read by the card reader. Available only on Android. + + + The encrypted KSN serial number read by the card reader. Available only on Android. The value is in HEX format. + + + + + + + Closes the card reader. + WM, CE, Android + + + + + Enumerates all the available card readers. + + Array of Card reader objects. + + + Android, WM + + + + 1.0.0 + Android, WM + + + If the CardReader open method is not specified with a callback, the cardreader data will be returned as keystrokes. If both the autotab and autoenter parameters are set to "enabled", autoenter will take precedence. An opened card reader must be closed before the attached card reader device and associated modulename parameter are changed. Any attempt to set a parameter to an invalid value, will result in no effect on the parameter's current value. There should be made a delay around 2 secs or more between API calls which interact with hardware. + + + + + + For the DCR7000 the ModuleName parameter must be set at least once before the readevent parameter is set. If the card reader is an MSR, when a card is swiped it returns the data read from the card. Setting ModuleName to a DCR will cause the card data to be returned followed by the PAN Data before waiting for a PIN to be entered on the keypad. Once entered the PIN will be encrypted and returned by a third ReadEvent. The card must be a validly formatted IATA or ABA card. + + + + There is no way to abort a pending PIN entry (other than the customer pressing the Cancel button), for security reasons. Therefore if the reader is closed or RhoElements is quit during that time it will become unresponsive until a PIN is entered or the PIN timeout occurs. + There is no way to abort a pending PIN entry (other than the customer pressing the Cancel button), for security reasons. Therefore if the reader is closed or the Enterprise Browser is quit during that time it will become unresponsive until a PIN is entered or the PIN timeout occurs. + + + + In certain circumstances it is possible that the card reader may return empty card data. The JavaScript event function should be able to handle this correctly. + + + + Applications running in RhoElements should be resilient against the card reader being detached and subsequently reattached. Card data parsing code should be robust against unexpected characters in the first read after reattachment. + Applications running in the Enterprise Browser should be resilient against the card reader being detached and subsequently reattached. Card data parsing code should be robust against unexpected characters in the first read after reattachment. + + + + The encrypted data is supported only on the card readers that are configured for encryption. Since the encrypted data might contain unreadable characters sometimes it is recommended to use only JSON object method rather than JavaScript '%s' notation. + + + + + + +
                          + The default card reader on the device is enabled when the index view is loaded. When a card is swiped the swipeEvent is called. + + :myswipeevent)) +end + def myswipeevent + puts "Swipe params: #{@params}" + puts "Mode is #{@params['mode']}" + puts "Data is #{@params['data']}" + end + ]]> + +
                          +
                          +
                          + + +
                          + Enable card reader and receive a callback when a card is swiped. + + + :cardreader_callback)) + redirect :index +end + +def cardreader_callback + Alert.show_popup("Received card reader data: #{@params[:data]}") +end + ]]> + + + + + +
                          +
                          +
                          + + +
                          + There are two ways to use the card reader. One is to receive a callback when a card is swiped, the other is to have it simulate keypresses. See below for an example of this second option. + + + + + + + + +
                          +
                          +
                          +
                          + + + +
                          + This example shows how to enable the card reader and accept a card swipe. It then, displays the data in a human readable way. This example assumes that the ebapi-modules.js file is in the same directory as the html file invoking it. + + + + + + CardReader API Example + + + + +

                          CardReader API

                          +
                          +
                          +
                          Card Data:
                          +
                          +
                          + + + ]]> +
                          +
                          +
                          +
                          +
                          +
                          +
                          +
                          diff --git a/docs/en/5.5/api/default_instance.xml b/docs/en/5.5/api/default_instance.xml new file mode 100644 index 00000000..a1777e9f --- /dev/null +++ b/docs/en/5.5/api/default_instance.xml @@ -0,0 +1,25 @@ + + + + + + + This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera. + + Default object of Module. + + + + + + This method allows you to set the attributes of the default object instance by passing in an object of the same class. + + + An instance object that is of the same class. + + + + + + + diff --git a/docs/en/5.5/api/device.md b/docs/en/5.5/api/device.md new file mode 100644 index 00000000..fa7c9b18 --- /dev/null +++ b/docs/en/5.5/api/device.md @@ -0,0 +1,301 @@ +#Device +
                          +

                          The Device API provides access to some device level functionality that is only available on Symbol devices such as suspend, calibrate, powerOff, wake, reboot etc.

                          +

                          Enabling the API

                          + +

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

                          + +
                          :::ruby
                          +extensions: ["symboldevice"]
                          +
                          + +

                          The symboldevice extension is also included automatically if you specify the following in your build.yml

                          + +
                          :::ruby
                          +app_type: "rhoelements"
                          +
                          + +

                          NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

                          + +

                          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

                          + +

                          calibrate(CallBackHandler callback)

                          Carries out the screen calibration routine.

                          +

                          Parameters

                          • callback : CallBackHandler Optional

                          Async Callback Returning Parameters: HASH

                            • status : STRING

                              Whether or not the calibration was successfully done, status will be ‘success’ or ‘failed’.

                              +

                            • message : STRING

                              If ‘status’ == ‘success’, the message will contain ‘Calibration was done succesfully.’ and if ‘status’ == ‘failed’, the message will contain ‘Calibration was failed.’.

                              +

                          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.Device.calibrate(CallBackHandler callback)
                            • Ruby: Rho::Device.calibrate(CallBackHandler callback)

                          idle(CallBackHandler callback)

                          Puts the device into idle mode. In this mode, the screen display is turned off. Callback is triggered only for ‘failed’ status.

                          +

                          Parameters

                          • callback : CallBackHandler Optional

                          Async Callback Returning Parameters: HASH

                            • status : STRING

                              If the mode of the device was not changed to idle mode, status will be ‘failed’. In all other cases, it will remain empty.

                              +

                            • message : STRING

                              If ‘status’ == ‘failed’, the message will contain an error message. In all other cases, it will remain empty.

                              +

                          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.Device.idle(CallBackHandler callback)
                            • Ruby: Rho::Device.idle(CallBackHandler callback)

                          powerOff(CallBackHandler callback)

                          Puts the device into power off mode. In this mode the device will draw no power. Only supported on SB1. Callback is triggered only for ‘failed’ status.

                          +

                          Parameters

                          • callback : CallBackHandler Optional

                          Async Callback Returning Parameters: HASH

                            • status : STRING

                              If the powerOff was unsuccessful, status will be ‘failed’. In all other cases, it will remain empty.

                              +

                            • message : STRING

                              If ‘status’ == ‘failed’, the message will contain an error message. In all other cases, it will remain empty.

                              +

                          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.Device.powerOff(CallBackHandler callback)
                            • Ruby: Rho::Device.powerOff(CallBackHandler callback)

                          reboot(STRING bootType, CallBackHandler callback)

                          It reboots the terminal using either a Warm or Cold software boot (as specified). Note on CE6 devices a “ColdCAD” boot is required to replicate the Coldboot key sequence, e.g. 1+9+Power on an MC3000. Callback is triggered only for ‘failed’ status.

                          +

                          Parameters

                          • bootType : STRING

                          • callback : CallBackHandler Optional

                          Async Callback Returning Parameters: HASH

                            • status : STRING

                              If the reboot was unsuccessful, status will be ‘failed’. In all other cases, it will remain empty.

                              +

                            • message : STRING

                              If ‘status’ == ‘failed’, the message will contain an error message. In all other cases, it will remain empty.

                              +

                          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.Device.reboot(STRING bootType, CallBackHandler callback)
                            • Ruby: Rho::Device.reboot(STRING bootType, CallBackHandler callback)

                          suspend(CallBackHandler callback)

                          Puts the device into suspend mode. On suspend, the device goes to hibernation mode. Callback is triggered only for ‘failed’ status. In some devices, the suspend doesnot happen instead it puts the device into an idle state.

                          +

                          Parameters

                          • callback : CallBackHandler Optional

                          Async Callback Returning Parameters: HASH

                            • status : STRING

                              If the suspend was unsuccessful, status will be ‘failed’. In all other cases, it will remain empty.

                              +

                            • message : STRING

                              If ‘status’ == ‘failed’, the message will contain an error message. In all other cases, it will remain empty.

                              +

                          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.Device.suspend(CallBackHandler callback)
                            • Ruby: Rho::Device.suspend(CallBackHandler callback)

                          wake(CallBackHandler callback)

                          In WM/CE, wakes the device from idle state to active state. Callback is triggered only for ‘failed’ status. In Android, it will turn on the display, if it was off. The callback parameter is ignored in Android platform.

                          +

                          Parameters

                          • callback : CallBackHandler Optional

                          Async Callback Returning Parameters: HASH

                            • status : STRING

                              In WM/CE, if the wake was unsuccessful, status will be ‘failed’. In all other cases, it will remain empty.

                              +

                            • message : STRING

                              In WM/CE, if ‘status’ == ‘failed’, the message will contain an error message. In all other cases, it will remain empty.

                              +

                          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.Device.wake(CallBackHandler callback)
                            • Ruby: Rho::Device.wake(CallBackHandler callback)
                          + +

                          Examples

                          + +
                          Setting callback
                          +

                          Setting a callback

                          +
                          :::javascript
                          +	
                          +//Callback is optional, user can call the API with or without callback.
                          +//User can set the callback in the below manner.							
                          +function mycallback(data){
                          +	var myMessage = "Status:" + data.status + "\n";
                          +	if(data.message != ""){
                          +		myMessage += "Message:" + data.message;
                          +	}
                          +	alert(myMessage);
                          +}
                          +
                          +							
                          :::ruby
                          +
                          +#Callback is optional, user can call the API with or without callback.
                          +#User can set the callback in the below manner.							
                          +def mycallback
                          +	myMessage = "Status:" + @params['status'] + "\n";
                          +		if(@params['message'] != "")
                          +			myMessage += "Message:" + @params['message']
                          +		end		
                          +	Alert.show_popup(myMessage)
                          +end							
                          +
                          +							
                          Calibrating the device
                          +

                          Calibrating the device

                          +
                          :::javascript
                          +			
                          +//Calibrating the device with callback
                          +Rho.Device.calibrate(mycallback);	
                          +//On successful calibration, callback will update the 'status' as 'success' and 'message' as 'Calibration was done succesfully.'.
                          +//On unsuccessful calibration, callback will update the 'status' as 'failed' and 'message' as 'Calibration was failed.'.
                          +							
                          +//Calibrating the device without callback
                          +Rho.Device.calibrate();							
                          +
                          +							
                          :::ruby
                          +
                          +#Calibrating the device with callback
                          +Rho::Device.calibrate(mycallback);	
                          +#On successful calibration, callback will update the 'status' as 'success' and 'message' as 'Calibration was done succesfully.'.
                          +#On unsuccessful calibration, callback will update the 'status' as 'failed' and 'message' as 'Calibration was failed.'.
                          +
                          +#Calibrating the device without callback
                          +Rho::Device.calibrate();							
                          +
                          +							
                          Suspending the device
                          +

                          Suspending the device

                          +
                          :::javascript
                          +
                          +//Suspending the device with callback
                          +Rho.Device.suspend(mycallback);
                          +//On successful suspend, callback will not be updated.
                          +//On unsuccessful suspend, callback will update the 'status' as 'failed' and 'message' will contain the error message.
                          +							
                          +//Suspending the device without callback
                          +Rho.Device.suspend();							
                          +
                          +							
                          :::ruby
                          +
                          +#Suspending the device with callback
                          +Rho::Device.suspend(mycallback);
                          +#On successful suspend, callback will not be updated.
                          +#On unsuccessful suspend, callback will update the 'status' as 'failed' and 'message' will contain the error message.
                          +							
                          +#Suspending the device without callback
                          +Rho::Device.suspend();							
                          +
                          +							
                          Power Off the device
                          +

                          Power Off the device

                          +
                          :::javascript
                          +
                          +//Power Off the device with callback
                          +Rho.Device.powerOff(mycallback);	
                          +//On successful powerOff, callback will not be updated.
                          +//On unsuccessful powerOff, callback will update the 'status' as 'failed' and 'message' will contain the error message.
                          +							
                          +//Power Off the device without callback
                          +Rho.Device.powerOff();							
                          +
                          +							
                          :::ruby
                          +
                          +#Power Off the device with callback
                          +Rho::Device.powerOff(mycallback);	
                          +#On successful powerOff, callback will not be updated.
                          +#On unsuccessful powerOff, callback will update the 'status' as 'failed' and 'message' will contain the error message.
                          +							
                          +#Power Off the device without callback
                          +Rho::Device.powerOff();							
                          +
                          +							
                          Switching device to idle mode
                          +

                          Switching device to idle mode

                          +
                          :::javascript
                          +
                          +//Switching device to idle mode with callback
                          +Rho.Device.idle(mycallback);	
                          +//On successful idle, callback will not be updated.
                          +//On unsuccessful idle, callback will update the 'status' as 'failed' and 'message' will contain the error message.
                          +							
                          +//Switching device to idle mode without callback
                          +Rho.Device.idle();							
                          +
                          +							
                          :::ruby
                          +
                          +#Switching device to idle mode with callback
                          +Rho::Device.idle(mycallback);	
                          +#On successful idle, callback will not be updated.
                          +#On unsuccessful idle, callback will update the 'status' as 'failed' and 'message' will contain the error message.
                          +							
                          +#Switching device to idle mode without callback
                          +Rho::Device.idle();							
                          +
                          +							
                          Wake the device
                          +

                          Wake the device

                          +
                          :::javascript
                          +
                          +//Wake the device with callback
                          +//Note: callback is ignored in Android platform. Hence no update will be retrieved on Android platform.
                          +Rho.Device.wake(mycallback);	
                          +//On successful wake, callback will not be updated.
                          +//On unsuccessful wake, callback will update the 'status' as 'failed' and 'message' will contain the error message.
                          +							
                          +//Wake the device without callback
                          +Rho.Device.wake();							
                          +
                          +							
                          :::ruby
                          +
                          +#Wake the device with callback
                          +#Note: callback is ignored in Android platform. Hence no update will be retrieved on Android platform.
                          +Rho::Device.wake(mycallback);	
                          +#On successful wake, callback will not be updated.
                          +#On unsuccessful wake, callback will update the 'status' as 'failed' and 'message' will contain the error message.
                          +							
                          +#Wake the device without callback
                          +Rho::Device.wake();							
                          +
                          +							
                          Rebooting the device
                          +

                          Rebooting the device

                          +
                          :::javascript
                          +
                          +//With callback
                          +
                          +//The callback is updated only for failed cases as mentioned below:-
                          +//For 'Warm' boot, the callback contains 'status' as 'failed' and 'message' as 'Failed to do Warm booting.'.
                          +//For 'Cold' boot, the callback contains 'status' as 'failed' and 'message' as 'Failed to do Cold booting.'.
                          +//For 'ColdCAD' boot, the callback contains 'status' as 'failed' and 'message' as 'Failed to do ColdCAD booting.'.
                          +//Other than 'Warm' or 'Cold' or 'ColdCAD' boot, the callback contains 'status' as 'failed' and 'message' as 'Failed to do Warm booting.'.
                          +
                          +//Rebooting the device using the string value as 'Warm'. 
                          +Rho.Device.reboot("Warm",mycallback);
                          +
                          +//Rebooting the device using the string value as 'Cold'. Note this feature may not be supported on all devices.
                          +Rho.Device.reboot("Cold",mycallback);
                          +							
                          +//Rebooting the device using the string value as 'ColdCAD'. Note this feature may not be supported on all devices.
                          +Rho.Device.reboot("ColdCAD",mycallback);	
                          +
                          +//Rebooting the device with an empty string, results in warm booting of the device. 
                          +Rho.Device.reboot("",mycallback);	
                          +
                          +//Rebooting the device without passing any argument and only with callback, results in warm booting of the device.
                          +Rho.Device.reboot(mycallback);	
                          +
                          +//Rebooting the device with any string other than 'Warm' or 'Cold' or 'ColdCAD', results in warm booting of the device.
                          +Rho.Device.reboot("XYZ",mycallback);
                          +							
                          +//Without callback
                          +//Rebooting the device using the string value as 'Warm'. 
                          +Rho.Device.reboot("Warm");
                          +
                          +//Rebooting the device using the string value as 'Cold'. Note this feature may not be supported on all devices.
                          +Rho.Device.reboot("Cold");
                          +							
                          +//Rebooting the device using the string value as 'ColdCAD'. Note this feature may not be supported on all devices.
                          +Rho.Device.reboot("ColdCAD");	
                          +
                          +//Rebooting the device with an empty string, results in warm booting of the device. 
                          +Rho.Device.reboot("");	
                          +
                          +//Rebooting the device without passing any argument, results in warm booting of the device.
                          +Rho.Device.reboot();	
                          +
                          +//Rebooting the device with any string other than 'Warm' or 'Cold' or 'ColdCAD', results in warm booting of the device.
                          +Rho.Device.reboot("XYZ");								
                          +
                          +							
                          :::ruby
                          +
                          +#With callback
                          +
                          +#The callback is updated only for failed cases as mentioned below:-
                          +#For 'Warm' boot, the callback contains 'status' as 'failed' and 'message' as 'Failed to do Warm booting.'.
                          +#For 'Cold' boot, the callback contains 'status' as 'failed' and 'message' as 'Failed to do Cold booting.'.
                          +#For 'ColdCAD' boot, the callback contains 'status' as 'failed' and 'message' as 'Failed to do ColdCAD booting.'.
                          +#Other than 'Warm' or 'Cold' or 'ColdCAD' boot, the callback contains 'status' as 'failed' and 'message' as 'Failed to do Warm booting.'.
                          +
                          +#Rebooting the device using the string value as 'Warm'. 
                          +Rho::Device.reboot("Warm",mycallback);
                          +
                          +#Rebooting the device using the string value as 'Cold'. Note this feature may not be supported on all devices.
                          +Rho::Device.reboot("Cold",mycallback);
                          +							
                          +#Rebooting the device using the string value as 'ColdCAD'. Note this feature may not be supported on all devices.
                          +Rho::Device.reboot("ColdCAD",mycallback);		
                          +
                          +#Rebooting the device with an empty string, results in warm booting of the device. 
                          +Rho::Device.reboot("",mycallback);	
                          +
                          +#Rebooting the device without passing any argument and only with callback, results in warm booting of the device.
                          +Rho::Device.reboot(mycallback);	
                          +
                          +#Rebooting the device with any string other than 'Warm' or 'Cold' or 'ColdCAD', results in warm booting of the device.
                          +Rho::Device.reboot("XYZ",mycallback);	
                          +							
                          +#Without callback							
                          +#Rebooting the device using the string value as 'Warm'. 
                          +Rho::Device.reboot("Warm");
                          +
                          +#Rebooting the device using the string value as 'Cold'. Note this feature may not be supported on all devices.
                          +Rho::Device.reboot("Cold");
                          +							
                          +#Rebooting the device using the string value as 'ColdCAD'. Note this feature may not be supported on all devices.
                          +Rho::Device.reboot("ColdCAD");		
                          +
                          +#Rebooting the device with an empty string, results in warm booting of the device. 
                          +Rho::Device.reboot("");	
                          +
                          +#Rebooting the device without passing any argument, results in warm booting of the device.
                          +Rho::Device.reboot();	
                          +
                          +#Rebooting the device with any string other than 'Warm' or 'Cold' or 'ColdCAD', results in warm booting of the device.
                          +Rho::Device.reboot("XYZ");						
                          +
                          +							
                          + +

                          Remarks

                          + +
                          General

                          Note that some devices may not support all the API’s or there is a possiblities of discrepancy across BSP’s & platforms.

                          +
                          Power Off

                          Note that some devices may not support power off feature. Those devices may either throw an error message or it may enter into Sleep mode.

                          +
                          Reboot

                          Note that in WM5.0 and above, there is no software difference between a warm and a cold boot as the device uses persistent storage; both the file and registry will remain the same after boot. In WM/CE, not all device support Cold or ColdCAD feature. Device may warm boot even though any of these option has been selected.

                          +
                          Interaction with Unattended Method of the Push Module

                          The suspend functionality is incompatible with the unattended functionality of the push module and they should not be used together.

                          +
                          wake Method

                          The wake functionality can be used along with Push module. For eg: in the push detected event the user can call the wake method to wake the device.

                          +
                          + +

                          Licensing

                          + +
                          This API is considered a RhoElements API and therefore requires a paid subscription to use (either Silver or Gold level). You can review the subscription plans on our licensing page here or on rhomobile.com/pricing.
                          \ No newline at end of file diff --git a/docs/en/5.5/api/device.xml b/docs/en/5.5/api/device.xml new file mode 100644 index 00000000..d01ff0a8 --- /dev/null +++ b/docs/en/5.5/api/device.xml @@ -0,0 +1,486 @@ + + + + The Device API provides access to some device level functionality that is only available on Symbol devices such as suspend, calibrate, powerOff, wake, reboot etc. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + :::ruby + extensions: ["symboldevice"] + +The `symboldevice` extension is also included automatically if you specify the following in your `build.yml` + :::ruby + app_type: "rhoelements" + +NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + +## Enabling the API +There are two methods of enabling the Device API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Device API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.device.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + 5.1.0 + WM, CE, Android + + + + + + + + + Whether or not the calibration was successfully done, status will be 'success' or 'failed'. + + + If 'status' == 'success', the message will contain 'Calibration was done succesfully.' and if 'status' == 'failed', the message will contain 'Calibration was failed.'. + + + + Carries out the screen calibration routine. + WM, CE + + + + + + + If the suspend was unsuccessful, status will be 'failed'. In all other cases, it will remain empty. + + + If 'status' == 'failed', the message will contain an error message. In all other cases, it will remain empty. + + + + Puts the device into suspend mode. On suspend, the device goes to hibernation mode. Callback is triggered only for 'failed' status. In some devices, the suspend doesnot happen instead it puts the device into an idle state. + WM, CE + + + + + + + If the powerOff was unsuccessful, status will be 'failed'. In all other cases, it will remain empty. + + + If 'status' == 'failed', the message will contain an error message. In all other cases, it will remain empty. + + + + Puts the device into power off mode. In this mode the device will draw no power. Only supported on SB1. Callback is triggered only for 'failed' status. + WM, CE + + + + + + + If the mode of the device was not changed to idle mode, status will be 'failed'. In all other cases, it will remain empty. + + + If 'status' == 'failed', the message will contain an error message. In all other cases, it will remain empty. + + + + Puts the device into idle mode. In this mode, the screen display is turned off. Callback is triggered only for 'failed' status. + WM, CE + + + + + + + In WM/CE, if the wake was unsuccessful, status will be 'failed'. In all other cases, it will remain empty. + + + In WM/CE, if 'status' == 'failed', the message will contain an error message. In all other cases, it will remain empty. + + + + In WM/CE, wakes the device from idle state to active state. Callback is triggered only for 'failed' status. In Android, it will turn on the display, if it was off. The callback parameter is ignored in Android platform. + WM, CE, Android + + + + + + + The string value is either "Warm" or "Cold" or "ColdCAD". It will do warm boot, if nothing has been passed as an argument or if the string value is either empty i.e. "" or other than "Warm" or "Cold" or "ColdCAD". Value is case insensitive. Note, some devices may not support the particular 'bootType' values. It may do normal warm boot for such devices. + + + + + If the reboot was unsuccessful, status will be 'failed'. In all other cases, it will remain empty. + + + If 'status' == 'failed', the message will contain an error message. In all other cases, it will remain empty. + + + + It reboots the terminal using either a Warm or Cold software boot (as specified). Note on CE6 devices a "ColdCAD" boot is required to replicate the Coldboot key sequence, e.g. 1+9+Power on an MC3000. Callback is triggered only for 'failed' status. + WM, CE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                          + Setting a callback + + + + + + + +
                          +
                          +
                          + + +
                          + Calibrating the device + + + + + + + +
                          +
                          +
                          + + +
                          + Suspending the device + + + + + + + +
                          +
                          +
                          + + +
                          + Power Off the device + + + + + + + +
                          +
                          +
                          + + +
                          + Switching device to idle mode + + + + + + + +
                          +
                          +
                          + + +
                          + Wake the device + + + + + + + +
                          +
                          +
                          + + +
                          + Rebooting the device + + + + + + + +
                          +
                          +
                          +
                          +
                          +
                          diff --git a/docs/en/5.5/api/deviceMemory.md b/docs/en/5.5/api/deviceMemory.md new file mode 100644 index 00000000..ea856601 --- /dev/null +++ b/docs/en/5.5/api/deviceMemory.md @@ -0,0 +1,25 @@ +#DeviceMemory +
                          +

                          Example extension api

                          +

                          This is example of API. Implementation contain in extension. In Android, this API will work version 4.0 onwards.

                          + + + +

                          Methods

                          + +

                          getAvailableMemory()

                          Returns the available memory present in the device. It will be returned in KB. In iOS this function return current free memory of application, but system memory management can allocate more via free unused memory or memory allocated by another processes. So in this case this function is practically unuseful on iOS – we do not recommned use it on iOS for plane any memory using strategy etc.

                          +

                          Synchronous Return:

                          • INTEGER

                          Method Access:

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

                          getExternalStorage()

                          Returns the available memory present in the user directory of the device. It will be returned in KB.

                          +

                          Synchronous Return:

                          • INTEGER

                          Method Access:

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

                          getInternalStorage()

                          Returns the available memory present in the external storage of the device. It will be returned in KB.

                          +

                          Synchronous Return:

                          • INTEGER

                          Method Access:

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

                          startListeningPlatformMemoryWarning(CallBackHandler callback)

                          Callback to be fired when underlying OS warns for device memory being low or critical

                          +

                          Parameters

                          • callback : CallBackHandler Mandatory

                          Async Callback Returning Parameters: HASH

                            • status : STRING

                              It will be either DEVICE_MEMORY_STATUS_LOW or DEVICE_MEMORY_STATUS_CRITICAL. When it’s value is “low” it means device memory is beginning to run low on memory and when “critical”, the app is in

                              + +
                                                              risk of getting killed.So when on "critical", release all the resources as soon as possible. In Android, the OS can fire mutiple times for both the status. So the user of this should handle appropriately. In iOS only DEVICE_MEMORY_STATUS_CRITICAL received, because System has only one level of memory warning.
                              +
                              +

                          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.DeviceMemory.startListeningPlatformMemoryWarning(CallBackHandler callback)
                            • Ruby: Rho::DeviceMemory.startListeningPlatformMemoryWarning(CallBackHandler callback)

                          stopListeningPlatformMemoryWarning()

                          Stops firing callbacks for the method startListeningPlatformMemoryWarning. Now the application will NOT recieve any callbacks when device Memory is down.

                          +

                          Synchronous Return:

                          • Void

                          Method Access:

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

                          Constants

                          + +
                          DEVICE_MEMORY_STATUS_LOW

                          Device has low free memory – application should free unused resources and prepare to emergency exit

                          +
                          DEVICE_MEMORY_STATUS_CRITICAL

                          Device has critical memory situation – application should prepare to exit or crash ASAP and free unused resources if possible

                          +
                          \ No newline at end of file diff --git a/docs/en/5.5/api/deviceMemory.xml b/docs/en/5.5/api/deviceMemory.xml new file mode 100644 index 00000000..903ef9ec --- /dev/null +++ b/docs/en/5.5/api/deviceMemory.xml @@ -0,0 +1,70 @@ + + + + + Example extension api + This is example of API. Implementation contain in extension. In Android, this API will work version 4.0 onwards. + + + + + Device has low free memory - application should free unused resources and prepare to emergency exit + + + + Device has critical memory situation - application should prepare to exit or crash ASAP and free unused resources if possible + + + + + + + + Callback to be fired when underlying OS warns for device memory being low or critical + Android, iOS + + + + It will be either DEVICE_MEMORY_STATUS_LOW or DEVICE_MEMORY_STATUS_CRITICAL. When it's value is "low" it means device memory is beginning to run low on memory and when "critical", the app is in + risk of getting killed.So when on "critical", release all the resources as soon as possible. In Android, the OS can fire mutiple times for both the status. So the user of this should handle appropriately. In iOS only DEVICE_MEMORY_STATUS_CRITICAL received, because System has only one level of memory warning. + + + + + + + + Stops firing callbacks for the method startListeningPlatformMemoryWarning. Now the application will NOT recieve any callbacks when device Memory is down. + Android, iOS + + + Returns the available memory present in the device. It will be returned in KB. In iOS this function return current free memory of application, but system memory management can allocate more via free unused memory or memory allocated by another processes. So in this case this function is practically unuseful on iOS - we do not recommned use it on iOS for plane any memory using strategy etc. + + + Android, iOS + + + Returns the available memory present in the external storage of the device. It will be returned in KB. + Android, iOS + + + + + Returns the available memory present in the user directory of the device. It will be returned in KB. + Android + + + + + + + + + + + + 1.0.0 + + + + diff --git a/docs/en/5.5/api/eventsource.md b/docs/en/5.5/api/eventsource.md new file mode 100644 index 00000000..c251e9f3 --- /dev/null +++ b/docs/en/5.5/api/eventsource.md @@ -0,0 +1,24 @@ +#EventSource +
                          +

                          Example extension api

                          +

                          This is example of API. Implementation contain in extension.

                          + + + +

                          Methods

                          + +

                          addEventListener(STRING event, CallBackHandler callback)

                          Parameters

                          • event : STRING

                          • callback : CallBackHandler Mandatory

                          Async Callback Returning Parameters: HASH

                            Synchronous Return:

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

                            Method Access:

                            • Instance Method: This method can be accessed via an instance object of this class:
                              • myObject.addEventListener(STRING event, CallBackHandler callback)

                            Destructor close()

                            Synchronous Return:

                            • Void

                            Method Access:

                            • Class Method: This method is a destructor and can only be accessed via the object that was created by the `new` constructor.
                              • JavaScript: myObj.close()
                              • Ruby: @myObj.close()
                            + +

                            Properties

                            + +

                            onerror : CALLBACK

                            {}

                            Property Access:

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

                            onmessage : CALLBACK

                            {}

                            Property Access:

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

                            onopen : CALLBACK

                            {}

                            Property Access:

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

                            readyState : INTEGER Read Only

                            Represents the state of the connection.

                            +

                            Property Access:

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

                            url : STRING Read Only

                            URL passed to EventSource constructor.

                            +

                            Property Access:

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

                            withCredentials : BOOLEAN Read Only

                            Currently will return empty string.

                            +

                            Property Access:

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

                            Constants

                            + +
                            CONNECTING

                            The connection has not yet been established.

                            +
                            OPEN

                            The WebSocket connection is established and communication is possible.

                            +
                            CLOSED

                            The connection has been closed or could not be opened.

                            +
                            \ No newline at end of file diff --git a/docs/en/5.5/api/eventsource.xml b/docs/en/5.5/api/eventsource.xml new file mode 100644 index 00000000..67328db5 --- /dev/null +++ b/docs/en/5.5/api/eventsource.xml @@ -0,0 +1,97 @@ + + + + + Example extension api + This is example of API. Implementation contain in extension. + + + + + The connection has not yet been established. + + + + The WebSocket connection is established and communication is possible. + + + + The connection has been closed or could not be opened. + + + + + + + + + + + + + + + + + + + + + + + + + URL passed to EventSource constructor. + + + + Represents the state of the connection. + + + + Currently will return empty string. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1.0.0 + + + + diff --git a/docs/en/5.5/api/geolocation.md b/docs/en/5.5/api/geolocation.md new file mode 100644 index 00000000..b432ea0b --- /dev/null +++ b/docs/en/5.5/api/geolocation.md @@ -0,0 +1,535 @@ +# Geolocation API + + + +Access geolocation information from your device. + +Refer to our [Geolocation guide](../guide/geolocation) for more discussion of Geolocation, and for examples. + +## Enabling Geolocation + +To use the geolocation API, you need to enable geolocation on the device. Do this by adding that capability to the build.yml file: + + :::yaml + capabilities: + - gps + +**NOTE: We do not have a timeout parameter to automatically turn off the GPS system. If you want to turn off the GPS system, call Geolocation.turnoff.** + +## Using JavaScript API + +You can call the Geolocation methods from JavaScript as well as Ruby. To use the JavaScript API, add the `public/js/rho_javascript_api.js` file -- created at build time as part of the application package -- to the .html, .erb, or .js file calling the JavaScript method. + +The JavaScript API methods with a return value can pass it as a parameter in jQuery-compatible continuation (deferred object, a kind of callback). Possible continuations to handle are done, fail, and complete. + + Rho.Class.method(params).done(function(handler) { /* handler... */ }) + +You must enable JavaScript by putting `rho-javascript` into extensions in your build.yml. + + :::yaml + extensions: ["rho-javascript"] + +You must have a [RhoElements license](../guide/licensing) to use the JavaScript API. + + +

                            Methods

                            + +

                            accuracy()

                            + + +
                            + +
                            + Returns the estimated accuracy of the fix. + Units: Horizontal radius in Meters. +

                            +
                            +

                            + + + + +

                            +
                            +
                            + + +
                            + Float +
                            + + +
                            +

                            Ruby: Geolocation.accuracy

                            +

                            JavaScript: Rho.Geolocation.accuracy();

                            +
                            + + +
                            + Ruby +
                            +      :::ruby
                            +def get_accuracy
                            +  accuracy = Geolocation.accuracy
                            +  Alert.show_popup accuracy
                            +end
                            +    
                            + JavaScript +
                            +      :::javascript
                            +function getAccuracy(){
                            +  var accuracy = Rho.Geolocation.accuracy;
                            +  alert(accuracy);
                            +}
                            +    
                            +
                            +
                            + + +

                            altitude()

                            + + +
                            + +
                            + Returns the altitude if available, if not available 0 is returned. + Units: Meters above sea level. +

                            +
                            +

                            + + + + + +

                            +
                            +
                            + + +
                            + Double +
                            + + +
                            +

                            Ruby: Geolocation.altitude

                            +

                            JavaScript: Rho.Geolocation.altitude();

                            +
                            + + +
                            + Ruby +
                            +      :::ruby
                            +def get_altitude
                            +  altitude = Geolocation.altitude
                            +  Alert.show_popup.altitude
                            +end
                            +    
                            + JavaScript +
                            +      :::javascript
                            +function getAltitude(){
                            +  var altitude = Rho.Geolocation.altitude;
                            +  alert(altitude);
                            +}
                            +    
                            +
                            +
                            + + +

                            haversine_distance( +FLOAT latitude1, +FLOAT longitude1, +FLOAT latitude2, +FLOAT longitude2 +)

                            + + +
                            + +
                            + Returns the distance between two points in miles. +
                            + + +
                            +
                              +
                            • latitude1 - Latitude of the first point in degrees.
                            • +
                            • longitude1 - Longitude of the first point in degrees.
                            • +
                            • latitude2 - Latitude of the second point in degrees.
                            • +
                            • longitude2 - Longitude of the second point in degrees. +
                            +
                            + + +
                            +

                            Ruby: Geolocation.haversine_distance(latitude1, longitude1, latitude2, longitude2)

                            +

                            JavaScript: Rho.Geolocation.haversine_distance(latitude1, longitude1, latitude2, longitude2);

                            +
                            +
                            + + +

                            known_position?, is_known_position()

                            + + +
                            + +
                            + Returns true if the location system is up and running, false otherwise. is_known_position returns null if this feature is not supported on the device platform. +
                            + + +
                            +

                            Ruby: Geolocation.known_position?

                            +

                            JavaScript: Rho.Geolocation.is_known_position();

                            +
                            + + +
                            + Boolean +
                            +
                            + + +

                            latitude()

                            + + +
                            + +
                            + Returns current latitude in degrees. +
                            + + +
                            +

                            Ruby: Geolocation.latitude

                            +

                            JavaScript: Rho.Geolocation.latitude();

                            +
                            + + +
                            + Float +
                            +
                            + + +

                            longitude()

                            + + +
                            + +
                            + Returns current longitude in degrees. +
                            + + +
                            +

                            Ruby: Geolocation.longitude

                            +

                            JavaScript: Rho.Geolocation.longitude();

                            +
                            + + +
                            + Float +
                            +
                            + + +

                            satellites()

                            + + +
                            + +
                            + Returns the number of satellites used to determine the fix. If this information isn't available, null is returned. +

                            +
                            +

                            + + + + +

                            +
                            +
                            + + +
                            + Integer +
                            + + +
                            + Ruby +
                            +      :::ruby
                            +def get_satellites
                            +  satellites = Geolocation.satellites
                            +  Alert.show_popup.satellites
                            +end
                            +    
                            + JavaScript +
                            +      :::javascript
                            +function getSatellites(){
                            +  var satellites = Rho.Geolocation.satellites;
                            +  alert(satellites);
                            +}
                            +    
                            +
                            + + +
                            +

                            Ruby: Geolocation.satellites

                            +

                            JavaScript: Rho.Geolocation.satellites();

                            +
                            +
                            + + +

                            set_notification( +CALLBACK callback_url, +STRING callback_params, +INT ping_gpssystem_interval +)

                            + + +
                            + +
                            +

                            Set callback to track location changes.

                            +NOTE: You only need to call Geolocation.set_notification once. The current behavior of the callback is that it will be called forever until it is stopped; you need to call Geolocation.turnoff to stop it. The previous behavior was that the callback was called once and needed to be reset. +
                            + + +
                            + NOTE: The callback_url parameter must be set in order for Geolocation to function. +

                            Ruby: Geolocation.set_notification(callback_url, callback_params, ping_gpssystem_interval)

                            +

                            JavaScript: Rho.Geolocation.set_notification(callback, callback_params, ping_gpssystem_interval);

                            +
                            + + +
                            +
                              +
                            • callback_url - url for the callback method called upon a location change notification or for the interval set by ping_gpssystem_interval.
                            • +
                            • callback_params - a string added to the body of the callback url. You can use it to identity who is setting up the callback, such as "my_tag=55". In general you do not set callback_param (leave it blank as in "").
                            • +
                            • ping_gpssystem_interval - (optional) If 0, the system interval is used; the callback is executed when the GPS system processes a location update (dependent on the mobile platform). If set to a number (such as 3), the callback is executed at an interval of this number of seconds (such as every three seconds).
                            • +
                            +
                            + + +
                            +

                            When the Geolocation.set_notification callback is called, it will receive a variable called @params, just like a normal Rhodes controller action. Here are the parameters included in the @params variable.

                            +
                              +
                            • known_position - 1 or 0. Return from known_position? method.
                            • +
                            • latitude - Return from call to latitude method.
                            • +
                            • longitude - Return from call to longitude method.
                            • +
                            • available - 1 if geolocation is available, 0 otherwise. For 1, not only does the hardware exist, but also the user can turn GPS off in phone settings, or not allow GPS activity on iPhone, etc.
                            • +
                            • status - "ok" or "error"
                            • +
                            • error_code - error code from RhoError.
                            • +
                            • accuracy - horizontal radius in meters; iOS and Android.
                            • +
                            +
                            +
                            + + +

                            set_notification_ex( +CALLBACK url, +STRING callbackParams, +HASH options +)

                            + + +
                            + +
                            + Extended notification which encompasses the recently added features. + +NOTE: There is no valid data related to distance, which the Geolocation API exposes in WM and hence there is no support for extended notification in WM. +
                            + + +
                            + NOTE: minDistance and minTimeout values are optional; if nothing is provided, whenever a location update is processed by the underlying system, it is sent to the application. It is supported only on Android devices. +
                              +
                            • url - Callback method to be invoked on any notification.
                            • +
                            • callbackParams - To be used when callback is invoked. It is generally used to know the source of the callback. This is optional.
                            • +
                            • options - This is a hash and can consist of the following two keys:
                            • +
                                +
                              • minDistance - Minimum moving distance(in meters) to invoke the callback again.
                              • +
                              • minTimeout - Minimum timeout for next callback invocation.
                              • +
                              +
                            +
                            + + +
                            +

                            Ruby: Geolocation.set_notification_ex(callback url, string callbackParams, options hash)

                            +

                            JavaScript: Rho.Geolocation.set_notification_ex(callback url, string callbackParams, options hash);

                            +
                            + + +
                            +

                            When the callback happens, it will provide the following parameters:

                            +
                              +
                            • known_position - 1 or 0. Return from known_position? method.
                            • +
                            • latitude - Value returned by Geolocation.latitude() method.
                            • +
                            • longitude - Value returned by Geolocation.longitude() method.
                            • +
                            • altitude - Value returned by Geolocation.altitude() method.
                            • +
                            • speed - Value returned by Geolocation.speed() method.
                            • +
                            • accuracy - Value returned by Geolocation.accuracy() method.
                            • +
                            • satellites - Value returned by Geolocation.satellites() method.
                            • +
                            • available - 1 if geolocation is available, 0 otherwise. For 1, not only does the hardware exist, but also the user can turn GPS off in phone settings, or not allow GPS activity on iPhone, etc.
                            • +
                            • status - "ok" or "error"
                            • +
                            • error_code - error code from RhoError.
                            • +
                            +
                            +
                            + + +

                            speed()

                            + + +
                            + +
                            + Returns the speed if it is available. If the speed is not available, 0.0 is returned. On iOS it will return a negative speed when it can not calculate it - for example when device detects location not by GPS but by 3G or Wi-Fi triangulation (also in the case where accuracy is too large - about 50 and more meters). +

                            Units: Meters/sec over ground

                            +

                            +
                            +

                            + + + + + +

                            +
                            +
                            + + +
                            + Float +
                            + + +
                            +

                            Ruby: Geolocation.speed

                            +

                            JavaScript: Rho.Geolocation.speed();

                            +
                            + + +
                            +
                            +      :::ruby
                            +def get_speed
                            +  speed = Geolocation.speed
                            +  Alert.show_popup speed
                            +end
                            +    
                            +
                            +      :::javascript
                            +function getSpeed(){
                            +  var speed = Rho.Geolocation.speed;
                            +  alert(speed);
                            +}
                            +    
                            +
                            +
                            + + +

                            turnoff()

                            + + +
                            + +
                            + Turn off Geolocation. + +NOTE: When you call Geolocation.turnoff(), after the GPS is switched off, you might still receive a few callbacks (this depends on the platform; iOS and Android does not receive callbacks after turnoff). +
                            + + +
                            + Ruby +
                            +      :::ruby
                            +Geolocation.turnoff
                            +    
                            + JavaScript +
                            +      :::javascript
                            +Rho.Geolocation.turnoff();
                            +    
                            +
                            +
                            \ No newline at end of file diff --git a/docs/en/5.5/api/keycapture.md b/docs/en/5.5/api/keycapture.md new file mode 100644 index 00000000..dc077226 --- /dev/null +++ b/docs/en/5.5/api/keycapture.md @@ -0,0 +1,238 @@ +#KeyCapture +
                            +

                            The KeyCapture module is used to intercept or override hardware keys. It is typically used to provide certain application functions through the use of the device’s physical keyboard or other hardware enabled buttons.

                            +

                            Enabling the API

                            + +

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

                            + +
                            :::ruby
                            +extensions: ["hardwarekeys"]
                            +
                            + +

                            The hardwarekeys extension is also included automatically if you specify the following in your build.yml

                            + +
                            :::ruby
                            +app_type: "rhoelements"
                            +
                            + +

                            Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

                            + +

                            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

                            + +

                            captureKey(BOOLEAN dispatch, STRING keyValue, CallBackHandler callback)

                            Notifies the user when a specified physical key is pressed. The key event can also be absorbed so that it isn’t delivered to the web view. If the callback is not set then the capture setting for the given key will be cleared.

                            +

                            Parameters

                            • dispatch : BOOLEAN

                              After a key has been intercepted this parameter will determine whether or not it will still be received by the Web View. For example if you have focus in a text box and are intercepting keys set this to ‘False’ to avoid having the keys appear in the box. For iOS devices this parameter has no effect. If any of the volume keys are captured, real sound volume will not be changed.

                              +

                            • keyValue : STRING

                              Specifies the identifier of the key to capture. This this value is the operating system’s identifier for the key, not the ASCII representation of the key (for example, the ‘a’ key on Windows Mobile devices has a keyValue of 101). Alternatively, this parameter can be set to ‘all’. This value will capture all hardware key presses. This parameter needs to be passed as a string (for example ‘101’ or ‘0x65’ or ‘all’).

                              +

                            • callback : CallBackHandler Optional

                            Async Callback Returning Parameters: HASH

                              • keyValue : INTEGER

                                The internal representation of the key expressed in decimal, e.g. 13 is the return key.

                                + Platforms:WM, CE, Android

                            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.KeyCapture.captureKey(BOOLEAN dispatch, STRING keyValue, CallBackHandler callback)
                              • Ruby: Rho::KeyCapture.captureKey(BOOLEAN dispatch, STRING keyValue, CallBackHandler callback)

                            captureTrigger(CallBackHandler callback)

                            Captures the event whenever a device hardware trigger is pressed or released. If the callback is not set then the capture setting for the trigger will be cleared. The trigger presses cannot be absorbed. All trigger presses will propagate to RhoElements.

                            +

                            Parameters

                            • callback : CallBackHandler Optional

                            Async Callback Returning Parameters: HASH

                              • triggerFlag : INTEGER

                                The combination of the triggers pressed and the state of the triggers. Older devices may report duplicate values for different triggers on the device due to a platform issue, this has been resolved in newer devices.

                                +

                            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.KeyCapture.captureTrigger(CallBackHandler callback)
                              • Ruby: Rho::KeyCapture.captureTrigger(CallBackHandler callback)

                            remapKey(STRING keyValue, STRING remapTo)

                            Captures and consumes a specific key value and spawns a new key event with the remapped key code. If remapTo is empty or null, the remapping for this key value will be cleared.

                            +

                            Parameters

                            • keyValue : STRING

                              Specifies the identifier of the key to capture. This this value is the operating system’s identifier for the key, not the ASCII representation of the key (for example, the ‘a’ key on Windows Mobile devices has a keyValue of 101). This parameter needs to be passed as a string (for example ‘101’ or ‘0x65’).

                              +

                            • remapTo : STRING

                              The operating system’s identifier of the key press event to generate when the keyValue is captured.

                              +

                            Synchronous Return:

                            • Void

                            Method Access:

                            • Class Method: This method can only be accessed via the API class object.
                              • JavaScript: Rho.KeyCapture.remapKey(STRING keyValue, STRING remapTo)
                              • Ruby: Rho::KeyCapture.remapKey(STRING keyValue, STRING remapTo)
                            + +

                            Properties

                            + +

                            homeKeyValue : STRING

                            Specifies a key which, when pressed, will navigate to the start page as defined in the RhoElements configuration. Set to ‘Disabled’ to prevent this behavior.

                            +

                            Default: Disabled

                            Property Access:

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

                            Constants

                            + +
                            IPHONE_VOLUME_UP

                            IPhone volume up keyCode. Used to capture the volume up key when it is pressed.

                            +
                            IPHONE_VOLUME_DOWN

                            IPhone volume down keyCode. Used to capture the volume down key when it is pressed.

                            +
                            + +

                            Examples

                            + +
                            Disabling all keys
                            +

                            This shows how to capture all hardware keys so that they are not propagated through to the page.

                            +
                            :::javascript
                            +
                            +                    
                            +    Rho.KeyCapture.captureKey(false, "ALL", callback);
                            +                            
                            +                            
                            :::ruby
                            +
                            +                    
                            +    Rho::KeyCapture.captureKey false, 'ALL',  url_for(:action => :keyCallback)
                            +                            
                            +                            
                            Capturing all keys
                            +

                            This shows how to get notified when any hardware key is pressed (except trigger keys). In this example, the keys will pass through to the web page.

                            +
                            :::javascript
                            +
                            +                    
                            +    function keyCallback(result)
                            +    {
                            +        alert("this key has just been pressed!: " + result.keyValue);
                            +    }
                            +
                            +    Rho.KeyCapture.captureKey(true, "ALL", keyCallback);
                            +                            
                            +                            
                            :::ruby
                            +
                            +                    
                            +    def keyCallback
                            +
                            +        Rho::Log("this key has just been pressed!: " + @params["keyValue"],"APP")
                            +    end
                            +
                            +    Rho::KeyCapture.captureKey true, 'ALL', url_for(:action => :keyCallback)
                            +                            
                            +                            
                            Remapping ET1 P keys to arrow keys
                            +

                            In this example, the P1 and P2 keys of the ET1 tablet are remapped to the left key and right key respectively.

                            +
                            :::javascript
                            +
                            +                
                            +function remap()
                            +{
                            +    Rho.KeyCapture.remapKey('0x19','0x15'); //P1, left
                            +    Rho.KeyCapture.remapKey('0x18','0x16'); //P2, right
                            +}
                            +                        
                            +                        
                            :::ruby
                            +
                            +                
                            +def remap
                            +
                            +    Rho::KeyCapture.remapKey('0x19','0x15') #P1, left
                            +    Rho::KeyCapture.remapKey('0x18','0x16') #P2, right
                            +end
                            +                        
                            +                        
                            Trigger capture
                            +

                            This example notifies the user when a trigger key is pressed.

                            +
                            :::javascript
                            +
                            +                
                            +function trigger()
                            +{
                            +    Rho.KeyCapture.captureTrigger(triggerCallback);
                            +}
                            +
                            +function triggerCallback(result)
                            +{
                            +    alert("this trigger event has just been received!: " + result.triggerFlag);
                            +}
                            +                        
                            +                        
                            :::ruby
                            +
                            +                
                            +def trigger()
                            +
                            +    Rho::KeyCapture.captureTrigger(url_for(:action => :callbackTrig))
                            +end
                            +
                            +def callbackTrig
                            +
                            +    Rho::Log("this key has just been pressed!: " + @params["triggerFlag"],"APP")
                            +end
                            +                        
                            +                        
                            HomeKeyValue
                            +

                            The following example will navigate to the RhoElements start page when return is pressed.

                            +
                            :::javascript
                            +
                            +                
                            +function goHome()
                            +{
                            +    Rho.KeyCapture.homeKeyValue = '0x0D';
                            +}
                            +                        
                            +                        
                            :::ruby
                            +
                            +                
                            +def goHome
                            +
                            +    Rho::KeyCapture.homeKeyValue = '0x0D'
                            +end
                            +                        
                            +                        
                            iPhoneVolume
                            +

                            The following example shows how to capture the iPhone Volume Up trigger.

                            +
                            :::javascript
                            +
                            +                
                            +    function keyCallback(result)
                            +    {
                            +        if(result.keyValue == Rho.KeyCapture.IPHONE_VOLUME_UP){
                            +            //do something
                            +        }
                            +    }
                            +
                            +    Rho.KeyCapture.captureKey(true, Rho.KeyCapture.IPHONE_VOLUME_UP, keyCallback);
                            +                        
                            +                        
                            :::ruby
                            +
                            +                
                            +    def keyCallback
                            +    {
                            +        if(@params["keyValue"] == Rho::KeyCapture.IPHONE_VOLUME_UP){
                            +            //do something
                            +        }
                            +    }
                            +
                            +    Rho::KeyCapture.captureKey true, Rho::KeyCapture.IPHONE_VOLUME_UP, url_for(:action => :key_Callback)
                            +                        
                            +                        
                            + +

                            Remarks

                            + +
                            Keys which cannot be captured

                            It is not possible to capture the following types of keys:

                            + +
                              +
                            1. Keyboard modifiers such as SHIFT, ALT, ORANGE button, BLUE button etc.
                            2. +
                            3. Device Keys such as the screen backlight or keyboard backlight.
                            4. +
                            5. Hot keys such as phone keys or ‘soft’ buttons, those whose function changes based on the running application.
                            6. +
                            7. The Home key and the power key on Android and iOS devices.
                            8. +
                            9. Depending on the device keyboard driver, some keys may not be easily capturable as they are interpreted as a shifted character by the device. One example of such a key is the ‘#’ character on CE7 devices, whilst the character code for this key is 23 it is interpreted as 33. This applies to both capturing keys and specifying the HomeKeyValue.
                            10. +
                            11. On Android devices, keys reserved for use by the “PTT” apps (such as the left trigger button), if a “PTT” app has been enabled.
                            12. +
                            13. On consumer Jelly Bean (Android) devices, the search button cannot be captured, as it has been reserved for the sole use of “Google Now”.
                            14. +
                            15. On ET1, Search (P3) key is application specific. Dispatching this key within RhoElements wont do anything as it RhoElements doesn’t do anything specific with this key (unlike the menu key which raises the menu). +Although on some device configurations pressing the SHIFT key twice generates CAPS LOCK which can be captured with a key value of 16.
                            16. +
                            + +
                            Precedence of APIs using the same keyValue

                            If captureKey and remapKey have been called with the same keyValue, the remapKey will take precedence. In this case this means that the keyEvent for the inputted key will not be fired as the remapping will occur and consume the key event.

                            + +

                            If the same key has been set as the homeKeyValue and captureKey with a callback, the captureKey will take precedence over the homeKeyValue. For example:

                            + +

                            Rho.KeyCapture.homeKeyValue = '0x0D';

                            + +

                            Rho.KeyCapture.captureKey(true, '0x0D', capturekeyCallback);

                            + +

                            When the specified key is pressed, the event will fire but the homeKey event will not occur.

                            +
                            Precedence of captureKey events

                            Any captureKey calls set with a specific key will take precedence over any captureKey calls with value ‘all’. This means that the ‘all’ callback will not be called when individual keys that have been registered with captureKey are pressed. This also goes for dispatch values. If captureKey ‘all’ has a dispatch value of false, and captureKey with an individual keyCode value has a dispatch value of true, then this individual key will be dispatched to the app when pressed.

                            +
                            Device Lockdown on Symbol Technologies Android devices

                            Because the Home key cannot be captured on the ET1 and MC40 it is possible for users to return to the system home page by pressing it. If you need to prevent this then please consult the Symbol Technologies Android documentation for other device lock-down options.

                            +
                            Capturable keys on iOS devices

                            Only the volume up and volume down keys can be caught on iOS devices.

                            +
                            Capturing Function

                            If you have enabled the function key in the configuration settings and that function key has some special behavior in the Operating system the key will not be capturable unless you also set the ‘FunctionKeysCapturable’ option (see RhoElements Configuration Settings). An example of special behavior is the F6 and F7 keys on the MC75a (non QWERTY) which control the volume up and volume down. Although ‘FunctionKeysCapturable’ will allow you to capture Function keys it will also disable the special Function key behavior. Which buttons map to which function keys will differ from device to device, some devices such as the MC9500 have dedicated, labeled function keys whereas other devices such as the MC75a do not label the fact that their volume / red phone / green phone keys all behave as function keys internally.

                            +
                            Keys with multiple functionalities

                            Some keys which are meant for performing multiple functionalities but performs the single functionality may return the single code value. In that case it is recommended to remap the key code value with the expected desired keycode value.

                            +
                            VC70 Hardware Keys

                            The VC70 has a hardware keys (P1, P2, P3 and P4 as well as a brightness button) which are not capturable by the KeyCapture module. Additionally the the default Operating system behavior (like volume up / down) of hardware keys can not be blocked when RhoElements is running in full-screen mode.

                            +
                            ES400 Application Keys

                            The ES400 has a hardware messaging key with an envelope icon on it that does not function like a standard Application Key. To disable this key go to ‘Settings’ on the device, then ‘Personal’, then ‘KeyRemap’ and remap it to a key not in use. Also note that the ‘Sym’ key on the ES400 is not capturable.

                            +
                            F5 Key

                            In Internet Explorer the F5 key is used to refresh the current page. It is not recommended to rely on this functionality on Windows Mobile and it is not supported.

                            +
                            PTT Keys

                            On Android, PTT keys are capturable using captureTrigger method only.

                            +
                            Accelerator Keys

                            The following keys will be affected by the ‘AccelerateKey’ tag. Accelerator Keys are only applicable when RhoElements is run with the Internet Explorer engine on a Windows CE device.

                            + +

                            Key Code Usual Behavior Special behavior in Internet Explorer

                            + +

                            Left Arrow 0x25 Cursor left Scroll window left +Right Arrow 0x27 Cursor right Scroll window right +Up Arrow 0x26 Cursor up Scroll window up +Down Arrow 0x28 Cursor down Scroll window down +Backspace 0x08 Delete previous character. Navigate to previous page +Enter 0x0D Cursor line feed Submit form +Tab 0x09 Advance to next control Advance to next control

                            +
                            Remapping a key to itself

                            If a key is remapped to itself, the app will appear to hang if that key is pressed because it will generate another press of the same key, and so on forever. A similar endless loop will occur if, for example, key 1 is remapped to key 2, and key 2 is remapped to key 1.

                            +
                            Symbol Keys

                            On some devices certain keys containing special characters, these keys are known as symbol keys and they trigger two separate key events. This happens because such characters are translated by the platform into the combination of a Shift and a Base Key. Characters behaving in such way are $, %, &, “, (, ), !, :, ?, #, _, @. Capturing symbol key input via the SIP is not possible on WM/CE as all symbol keys return the same value; there is no such limitation on the physical keys representing the special characters.

                            +
                            Device Specific Exceptions

                            Certain devices may map their function keys to apparently normal keys. For example, the VC6090 maps the ‘{’ key to F12 and the ‘}’ key to F14. To capture those two keys it is necessary to enable F12 and F14 in the Configuration Settings. You may also find on some devices special keys like ‘OK’ return the same code as a function key, depending on your keyboard layout. The MK3100 and other kiosk devices will report their symbol keys as ‘0’ rather than assigning each key a different value.

                            +
                            Use of Key Capture module on Localized Operating Systems

                            Users of the key capture module with Chinese, Korean and Japanese operating systems should bear the following in mind: Internally the KeyCapture module stores key representations as VK codes, therefore the key event will always return VK_PROCESSKEY (229) and keys can not be individually specified. In JavaScript the DOM element’s keyup event can be used as an indication of which key has been pressed.

                            +
                            Build Configuration

                            To build the keycapture API into your application you must specify the ‘hardwarekeys’ extension and specify your application type to be ‘rhoelements’.

                            +
                            + +

                            Licensing

                            + +
                            This API is considered a RhoElements API and therefore requires a paid subscription to use (either Silver or Gold level). You can review the subscription plans on our licensing page here or on rhomobile.com/pricing.
                            \ No newline at end of file diff --git a/docs/en/5.5/api/keycapture.xml b/docs/en/5.5/api/keycapture.xml new file mode 100644 index 00000000..c5e53ffa --- /dev/null +++ b/docs/en/5.5/api/keycapture.xml @@ -0,0 +1,460 @@ + + + + + The KeyCapture module is used to intercept or override hardware keys. It is typically used to provide certain application functions through the use of the device's physical keyboard or other hardware enabled buttons. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["hardwarekeys"] + +The `hardwarekeys` extension is also included automatically if you specify the following in your `build.yml` + :::ruby + app_type: "rhoelements" + +> Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + + +## Enabling the API +There are two ways to enable Enterprise Browser APIs: + +* Include all 'ebapi' modules +* Include only the API modules you need + +Both methods are explained below. + +Either way, the included files will be from: +`/Enterprise Browser/JavaScript Files/Enterprise Browser`, +a directory on the computer that contains the Enterprise Browser installation. + +### Include all JS API modules +To include all JavaScript APIs, copy the `ebapi-modules.js` file to a location accessible by your app's files and include the JavaScript modules file in your app. For instance, to include the modules file in your `index.html`, copy the file to the same directory as your index.html and add the following line to the HEAD section of your index.html file: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> This will define the EB class within the page. **Note that the path for this file is relative to the current page** (index.html). Any page on which the modules are required will need to have the required .js file(s) included in this fashion. + +### Include only the modules you need + +To include individual APIs, you must first include the `ebapi.js` in your HTML, and then the additional required API file(s). For instance, to use the KeyCapture API, add the following code to the HTML file(s). Again, this assumes that relevant API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="keycapture.js"></script> + +> In the code lines above, notice that `ebapi.js` is included first, followed by `eb.keycapture.js`, which is the KeyCapture API for Enterprise Browser. **This coding is required on each HTML page whenever an individual API will be called from that page**. + + + + + + + + + IPhone volume up keyCode. Used to capture the volume up key when it is pressed. + + + IPhone volume down keyCode. Used to capture the volume down key when it is pressed. + + + + + + Specifies a key which, when pressed, will navigate to the start page as defined in the RhoElements configuration. Set to 'Disabled' to prevent this behavior. + Specifies a key which, when pressed, will navigate to the start page as defined in the config.xml file. Set to 'Disabled' to prevent this behavior. + WM + + + + + + Notifies the user when a specified physical key is pressed. The key event can also be absorbed so that it isn't delivered to the web view. If the callback is not set then the capture setting for the given key will be cleared. + iOS, WM, Android + WM, Android + + + WM, CE, Android + After a key has been intercepted this parameter will determine whether or not it will still be received by the Web View. For example if you have focus in a text box and are intercepting keys set this to 'False' to avoid having the keys appear in the box. For iOS devices this parameter has no effect. If any of the volume keys are captured, real sound volume will not be changed. + After a key has been intercepted this parameter will determine whether or not it will still be received by the Web View. For example if you have focus in a text box and are intercepting keys set this to 'False' to avoid having the keys appear in the box. If any of the volume keys are captured, real sound volume will not be changed. + + + Specifies the identifier of the key to capture. This this value is the operating system's identifier for the key, not the ASCII representation of the key (for example, the 'a' key on Windows Mobile devices has a keyValue of 101). Alternatively, this parameter can be set to 'all'. This value will capture all hardware key presses. This parameter needs to be passed as a string (for example '101' or '0x65' or 'all'). + + + + + + The internal representation of the key expressed in decimal, e.g. 13 is the return key. + WM, CE, Android + + + + + + + Captures and consumes a specific key value and spawns a new key event with the remapped key code. If remapTo is empty or null, the remapping for this key value will be cleared. + WM, CE, Android + + + Specifies the identifier of the key to capture. This this value is the operating system's identifier for the key, not the ASCII representation of the key (for example, the 'a' key on Windows Mobile devices has a keyValue of 101). This parameter needs to be passed as a string (for example '101' or '0x65'). + + + The operating system's identifier of the key press event to generate when the keyValue is captured. + + + + + + Captures the event whenever a device hardware trigger is pressed or released. If the callback is not set then the capture setting for the trigger will be cleared. The trigger presses cannot be absorbed. All trigger presses will propagate to RhoElements. + Captures the event whenever a device hardware trigger is pressed or released. If the callback is not set then the capture setting for the trigger will be cleared. The trigger presses cannot be absorbed. All trigger presses will propagate to the Enterprise Browser. Note: On Android, PTT keys are capturable using captureTrigger method only. + WM, CE, Android + + + + + The combination of the triggers pressed and the state of the triggers. Older devices may report duplicate values for different triggers on the device due to a platform issue, this has been resolved in newer devices. + + + + + + + 1.0.0 + WM, CE, Android, iOS + WM, CE, Android + + + + +
                            + This shows how to capture all hardware keys so that they are not propagated through to the page. + + + + + + :keyCallback) + ]]> + + +
                            +
                            +
                            + + + +
                            + This shows how to get notified when any hardware key is pressed (except trigger keys). In this example, the keys will pass through to the web page. + + + + + + :keyCallback) + ]]> + + +
                            +
                            +
                            + + + +
                            + In this example, the P1 and P2 keys of the ET1 tablet are remapped to the left key and right key respectively. + + + + + + + + +
                            +
                            +
                            + + + +
                            + This example notifies the user when a trigger key is pressed. + + + + + + :callbackTrig)) +end + +def callbackTrig + + Rho::Log("this key has just been pressed!: " + @params["triggerFlag"],"APP") +end + ]]> + + +
                            +
                            +
                            + + + +
                            + The following example will navigate to the RhoElements start page when return is pressed. + + + + + + + + +
                            +
                            +
                            + + + +
                            + The following example shows how to capture the iPhone Volume Up trigger. + + + + + + :key_Callback) + ]]> + + +
                            +
                            +
                            +
                            + + + + It is not possible to capture the following types of keys: + +1. Keyboard modifiers such as SHIFT, ALT, ORANGE button, BLUE button etc. +2. Device Keys such as the screen backlight or keyboard backlight. +3. Hot keys such as phone keys or 'soft' buttons, those whose function changes based on the running application. +4. The Home key and the power key on Android and iOS devices. +5. Depending on the device keyboard driver, some keys may not be easily capturable as they are interpreted as a shifted character by the device. One example of such a key is the '#' character on CE7 devices, whilst the character code for this key is 23 it is interpreted as 33. This applies to both capturing keys and specifying the HomeKeyValue. +6. On Android devices, keys reserved for use by the "PTT" apps (such as the left trigger button), if a "PTT" app has been enabled. +7. On consumer Jelly Bean (Android) devices, the search button cannot be captured, as it has been reserved for the sole use of "Google Now". +8. On ET1, Search (P3) key is application specific. Dispatching this key within RhoElements wont do anything as it RhoElements doesn't do anything specific with this key (unlike the menu key which raises the menu). +Although on some device configurations pressing the SHIFT key twice generates CAPS LOCK which can be captured with a key value of 16. + It is not possible to capture the following types of keys: + +1. Keyboard modifiers such as SHIFT, ALT, ORANGE button, BLUE button etc. +2. Device Keys such as the screen backlight or keyboard backlight. +3. Hot keys such as phone keys or 'soft' buttons, those whose function changes based on the running application. +4. The Home key and the power key on Android and devices. +5. Depending on the device keyboard driver, some keys may not be easily capturable as they are interpreted as a shifted character by the device. One example of such a key is the '#' character on CE7 devices, whilst the character code for this key is 23 it is interpreted as 33. This applies to both capturing keys and specifying the HomeKeyValue. +6. On Android devices, keys reserved for use by the "PTT" apps (such as the left trigger button), if a "PTT" app has been enabled. +7. On consumer Jelly Bean (Android) devices, the search button cannot be captured, as it has been reserved for the sole use of "Google Now". +8. On ET1, Search (P3) key is application specific. Dispatching this key within the Enterprise Browser wont do anything as the Enterprise Browser doesn't do anything specific with this key (unlike the menu key which raises the menu). +Although on some device configurations pressing the SHIFT key twice generates CAPS LOCK which can be captured with a key value of 16. + + + + If captureKey and remapKey have been called with the same keyValue, the remapKey will take precedence. In this case this means that the keyEvent for the inputted key will not be fired as the remapping will occur and consume the key event. + +If the same key has been set as the homeKeyValue and captureKey with a callback, the captureKey will take precedence over the homeKeyValue. For example: + +`Rho.KeyCapture.homeKeyValue = '0x0D';` + +`Rho.KeyCapture.captureKey(true, '0x0D', capturekeyCallback);` + +When the specified key is pressed, the event will fire but the homeKey event will not occur. + If captureKey and remapKey have been called with the same keyValue, the remapKey will take precedence. In this case this means that the keyEvent for the inputted key will not be fired as the remapping will occur and consume the key event. + +If the same key has been set as the homeKeyValue and captureKey with a callback, the captureKey will take precedence over the homeKeyValue. For example: + + :::javascript + EB.KeyCapture.homeKeyValue = '0x0D'; + EB.KeyCapture.captureKey(true, '0x0D', capturekeyCallback); + +When the specified key is pressed, the event will fire but the homeKey event will not occur. + + + + Any captureKey calls set with a specific key will take precedence over any captureKey calls with value 'all'. This means that the 'all' callback will not be called when individual keys that have been registered with captureKey are pressed. This also goes for dispatch values. If captureKey 'all' has a dispatch value of false, and captureKey with an individual keyCode value has a dispatch value of true, then this individual key will be dispatched to the app when pressed. + + + + Because the Home key cannot be captured on the ET1 and MC40 it is possible for users to return to the system home page by pressing it. If you need to prevent this then please consult the Symbol Technologies Android documentation for other device lock-down options. + + + + Only the volume up and volume down keys can be caught on iOS devices. + + + + If you have enabled the function key in the configuration settings and that function key has some special behavior in the Operating system the key will not be capturable unless you also set the 'FunctionKeysCapturable' option (see RhoElements Configuration Settings). An example of special behavior is the F6 and F7 keys on the MC75a (non QWERTY) which control the volume up and volume down. Although 'FunctionKeysCapturable' will allow you to capture Function keys it will also disable the special Function key behavior. Which buttons map to which function keys will differ from device to device, some devices such as the MC9500 have dedicated, labeled function keys whereas other devices such as the MC75a do not label the fact that their volume / red phone / green phone keys all behave as function keys internally. + If you have enabled the function key in the configuration settings and that function key has some special behavior in the Operating system the key will not be capturable unless you also set the 'FunctionKeysCapturable' option (see the Configuration Reference). An example of special behavior is the F6 and F7 keys on the MC75a (non QWERTY) which control the volume up and volume down. Although 'FunctionKeysCapturable' will allow you to capture Function keys it will also disable the special Function key behavior. Which buttons map to which function keys will differ from device to device, some devices such as the MC9500 have dedicated, labeled function keys whereas other devices such as the MC75a do not label the fact that their volume / red phone / green phone keys all behave as function keys internally. + + + + Some keys which are meant for performing multiple functionalities but performs the single functionality may return the single code value. In that case it is recommended to remap the key code value with the expected desired keycode value. + + + + The VC70 has a hardware keys (P1, P2, P3 and P4 as well as a brightness button) which are not capturable by the KeyCapture module. Additionally the the default Operating system behavior (like volume up / down) of hardware keys can not be blocked when RhoElements is running in full-screen mode. + The VC70 has a hardware keys (P1, P2, P3 and P4 as well as a brightness button) which are not capturable by the KeyCapture module. Additionally the the default Operating system behavior (like volume up / down) of hardware keys can not be blocked when the app is running in full-screen mode. + + + + The ES400 has a hardware messaging key with an envelope icon on it that does not function like a standard Application Key. To disable this key go to 'Settings' on the device, then 'Personal', then 'KeyRemap' and remap it to a key not in use. Also note that the 'Sym' key on the ES400 is not capturable. + + + + In Internet Explorer the F5 key is used to refresh the current page. It is not recommended to rely on this functionality on Windows Mobile and it is not supported. + + + + On Android, PTT keys are capturable using captureTrigger method only. + + + + The following keys will be affected by the 'AccelerateKey' tag. Accelerator Keys are only applicable when RhoElements is run with the Internet Explorer engine on a Windows CE device. + +Key Code Usual Behavior Special behavior in Internet Explorer + +Left Arrow 0x25 Cursor left Scroll window left +Right Arrow 0x27 Cursor right Scroll window right +Up Arrow 0x26 Cursor up Scroll window up +Down Arrow 0x28 Cursor down Scroll window down +Backspace 0x08 Delete previous character. Navigate to previous page +Enter 0x0D Cursor line feed Submit form +Tab 0x09 Advance to next control Advance to next control + The following keys will be affected by the 'AccelerateKey' tag, see the Key Capture Overview for a more detailed explanation of Accelerator Keys. Accelerator Keys are only applicable when the app is run with the Internet Explorer engine on a Windows CE device. + +* Key (Code) + * Usual - Usual Behavior + * I.E. - Special behavior in Internet Explorer +* Left Arrow (0x25) + * Usual - Cursor left + * I.E. - Scroll window left +* Right Arrow (0x27) + * Usual - Cursor right + * I.E. - Scroll window right +* Up Arrow (0x26) + * Usual - Cursor up + * I.E. - Scroll window up +* Down Arrow (0x28) + * Usual - Cursor down + * I.E. - Scroll window down +* Backspace (0x08) + * Usual - Delete previous character + * I.E. - Navigate to previous page +* Enter (0x0D) + * Usual - Cursor line feed + * I.E. - Submit form +* Tab (0x09) + * Usual - Advance to next control + * I.E. - Advance to next control + + + + If a key is remapped to itself, the app will appear to hang if that key is pressed because it will generate another press of the same key, and so on forever. A similar endless loop will occur if, for example, key 1 is remapped to key 2, and key 2 is remapped to key 1. + + If a key is remapped to itself, the app will appear to hang if that key is pressed because it will generate another press of the same key, and so on forever. A similar endless loop will occur if, for example, key 1 is remapped to key 2, and key 2 is remapped to key 1. + + + + + On some devices certain keys containing special characters, these keys are known as symbol keys and they trigger two separate key events. This happens because such characters are translated by the platform into the combination of a Shift and a Base Key. Characters behaving in such way are $, %, &, ", (, ), !, :, ?, #, _, @. Capturing symbol key input via the SIP is not possible on WM/CE as all symbol keys return the same value; there is no such limitation on the physical keys representing the special characters. + + + + Certain devices may map their function keys to apparently normal keys. For example, the VC6090 maps the '{' key to F12 and the '}' key to F14. To capture those two keys it is necessary to enable F12 and F14 in the Configuration Settings. You may also find on some devices special keys like 'OK' return the same code as a function key, depending on your keyboard layout. The MK3100 and other kiosk devices will report their symbol keys as '0' rather than assigning each key a different value. + + + + Users of the key capture module with Chinese, Korean and Japanese operating systems should bear the following in mind: Internally the KeyCapture module stores key representations as VK codes, therefore the key event will always return VK_PROCESSKEY (229) and keys can not be individually specified. In JavaScript the DOM element's keyup event can be used as an indication of which key has been pressed. + + + + To build the keycapture API into your application you must specify the 'hardwarekeys' extension and specify your application type to be 'rhoelements'. + + +
                            +
                            diff --git a/docs/en/5.5/api/keystate.md b/docs/en/5.5/api/keystate.md new file mode 100644 index 00000000..c0d81f84 --- /dev/null +++ b/docs/en/5.5/api/keystate.md @@ -0,0 +1,78 @@ +#KeyState +
                            +

                            The KeyState API is used to display small icons to the user indicating the current shifted state of the hardware keyboard. The KeyState indicator will display icons for Shift, Alt, Control, Function, Caps, Num lock and Orange key states, growing from the right as necessary if more than one key state is set at once. This API is only supported on a subset of Symbol Technologies' Windows Mobile / CE / Embedded handheld devices (see remarks).

                            +

                            Enabling the API

                            + +

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

                            + +
                            :::ruby
                            +extensions: ["indicators"]
                            +
                            + +

                            The indicators extension is also included automatically if you specify the following in your build.yml.

                            + +
                            :::ruby
                            +app_type: "rhoelements"
                            +
                            + +

                            NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

                            + +

                            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

                            + +

                            hideStates()

                            Stops showing keystate icons representing the shifted state of the hardware keyboard.

                            +

                            Synchronous Return:

                            • Void

                            Method Access:

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

                            showStates(HASH propertyMap)

                            Display keystate icons representing the shifted state of the hardware keyboard.

                            +

                            Parameters

                            • propertyMap : HASH Optional

                              The properties associated with the keystate indicator, its size and position.

                              +

                              Not specifying any properties will display the keystate indicators at the bottom right hand corner of the screen.

                              +

                              • right : INTEGER Default: [Keystate Indicators start at the bottom right of the screen]

                                The absolute horizontal position of the keystate indicators in pixels. This is the rightmost edge of the rightmost indicator, where multiple indicators are displayed simultaneously they will grow from right to left.

                                +

                              • top : INTEGER Default: [Keystate Indicators start at the bottom right of the screen]

                                The absolute vertical position of the keystate indicators in pixels.

                                +

                              • width : INTEGER Default: [A sensible width based on Screen Resolution]

                                The width of each keystate indicator in pixels.

                                +

                              • height : INTEGER Default: [A sensible height based on Screen Resolution]

                                The width of each keystate indicator in pixels.

                                +

                            Synchronous Return:

                            • Void

                            Method Access:

                            • Class Method: This method can only be accessed via the API class object.
                              • JavaScript: Rho.KeyState.showStates(HASH propertyMap)
                              • Ruby: Rho::KeyState.showStates(HASH propertyMap)
                            + +

                            Examples

                            + +
                            Show the Keystate Indicators
                            +

                            If you just want to display the keystate indicators in their default positions with size 25x25 pixels then call as follows.

                            +
                            :::javascript
                            +
                            +                            
                            +function show_keystates(){
                            +    Rho.Keystate.showStates({width:25;height:25});
                            +}
                            +                        
                            :::ruby
                            +
                            +                
                            +def show_keystates
                            +    Rho::Keystate.showStates({width:25;height:25})
                            +end
                            +                        
                            + +

                            Remarks

                            + +
                            Devices lacking support

                            Due to platform limitations this API is not available on the following Zebra Technologies devices:

                            + +
                              +
                            • ES400
                            • +
                            • MC45
                            • +
                            • MC65
                            • +
                            • VC70
                            • +
                            • MC45
                            • +
                            • Workabout Pro 4
                            • +
                            + +
                            Rotating the Screen

                            The keystate indicator positions are absolute and so when rotating the screen you should also reposition the keystate accordingly to accommodate the new screen layout.

                            +
                            + +

                            Licensing

                            + +
                            This API is considered a RhoElements API and therefore requires a paid subscription to use (either Silver or Gold level). You can review the subscription plans on our licensing page here or on rhomobile.com/pricing.
                            \ No newline at end of file diff --git a/docs/en/5.5/api/keystate.xml b/docs/en/5.5/api/keystate.xml new file mode 100644 index 00000000..7bf2974d --- /dev/null +++ b/docs/en/5.5/api/keystate.xml @@ -0,0 +1,149 @@ + + + + + The KeyState API is used to display small icons to the user indicating the current shifted state of the hardware keyboard. The KeyState indicator will display icons for Shift, Alt, Control, Function, Caps, Num lock and Orange key states, growing from the right as necessary if more than one key state is set at once. This API is only supported on a subset of Symbol Technologies' Windows Mobile / CE / Embedded handheld devices (see remarks). + The KeyState API is used to display small icons to the user indicating the current shifted state of the hardware keyboard. The KeyState indicator will display icons for Shift, Alt, Control, Function, Caps, Num lock and Orange key states, growing from the right as necessary if more than one key state is set at once. This API is only supported on a subset of Symbol Technologies' Windows Mobile / CE / Embedded handheld devices (see remarks). + +> Note: When using the keyState indicator on a VC5090 device, there is the possibility that the display will be slightly distorted while the keyState indicator is displayed. This only occurs when the keyState indicator or other similar overlays are on set to be visible. +Other overlays consist of, but are not necessarily limited to: +* addressBar +* backbutton +* forwardbutton +* gobutton +* minimizebutton +* quitbutton +* reloadButton +* sipbutton +* stopbutton + + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + :::ruby + extensions: ["indicators"] + +The `indicators` extension is also included automatically if you specify the following in your `build.yml`. + :::ruby + app_type: "rhoelements" + +NOTE: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + +## Enabling the API +There are two methods of enabling the KeyState API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the KeyState API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.keystate.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + Display keystate icons representing the shifted state of the hardware keyboard. + WM + + + + The properties associated with the keystate indicator, its size and position. + + + The absolute horizontal position of the keystate indicators in pixels. This is the rightmost edge of the rightmost indicator, where multiple indicators are displayed simultaneously they will grow from right to left. + + + The absolute vertical position of the keystate indicators in pixels. + + + The width of each keystate indicator in pixels. + + + The width of each keystate indicator in pixels. + + + + Not specifying any properties will display the keystate indicators at the bottom right hand corner of the screen. + + + + + + + Stops showing keystate icons representing the shifted state of the hardware keyboard. + WM + + + + + 1.0.0 + WM + + + +
                            + If you just want to display the keystate indicators in their default positions with size 25x25 pixels then call as follows. + + + + + + + + +
                            +
                            +
                            +
                            + + + + Due to platform limitations this API is not available on the following Zebra Technologies devices: + +* ES400 +* MC45 +* MC65 +* VC70 +* MC45 +* Workabout Pro 4 + + + + The keystate indicator positions are absolute and so when rotating the screen you should also reposition the keystate accordingly to accommodate the new screen layout. + + +
                            +
                            diff --git a/docs/en/5.5/api/logcapture.md b/docs/en/5.5/api/logcapture.md new file mode 100644 index 00000000..a1f03c4d --- /dev/null +++ b/docs/en/5.5/api/logcapture.md @@ -0,0 +1,35 @@ +#LogCapture +
                            +

                            The LogCapture class is used for capturing logging events.

                            +

                            Enabling the API

                            + +

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

                            + +
                            :::ruby
                            +extensions: ["logCapture"]
                            +
                            + +

                            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

                            + +

                            clear()

                            Clear captured events.

                            +

                            Synchronous Return:

                            • Void

                            Method Access:

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

                            numLines()

                            Return number of captured lines.

                            +

                            Synchronous Return:

                            • INTEGER

                            Method Access:

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

                            read()

                            Read captured items.

                            +

                            Synchronous Return:

                            • STRING

                            Method Access:

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

                            start()

                            Start capture log events.

                            +

                            Synchronous Return:

                            • Void

                            Method Access:

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

                            stop()

                            Stop capture log events.

                            +

                            Synchronous Return:

                            • Void

                            Method Access:

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

                            Properties

                            + +

                            excludeCategories : STRING

                            Comma-separated list of excluded log categories.

                            +

                            Property Access:

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

                            maxLines : INTEGER

                            Maximum number of captured lines.

                            +

                            Default: 1024

                            Property Access:

                            • Instance: This property can be accessed via an instance object of this class:
                              • myObject.maxLines
                            \ No newline at end of file diff --git a/docs/en/5.5/api/logcapture.xml b/docs/en/5.5/api/logcapture.xml new file mode 100644 index 00000000..b152cab2 --- /dev/null +++ b/docs/en/5.5/api/logcapture.xml @@ -0,0 +1,83 @@ + + + + + The LogCapture class is used for capturing logging events. + + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["logCapture"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + + +## Enabling the API +There are two methods of enabling the LogCapture API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the LogCapture API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.logcapture.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + Comma-separated list of excluded log categories. + + + + Maximum number of captured lines. + + + + + + Start capture log events. + + + Stop capture log events. + + + Clear captured events. + + + Return number of captured lines. + + + + Read captured items. + + + + + 4.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + \ No newline at end of file diff --git a/docs/en/5.5/api/mediaplayer.md b/docs/en/5.5/api/mediaplayer.md new file mode 100644 index 00000000..d24c709b --- /dev/null +++ b/docs/en/5.5/api/mediaplayer.md @@ -0,0 +1,75 @@ +#Mediaplayer +
                            +

                            The MediaPlayer extension is used to playback different types of audio files. It also allows the playback of Ringtones for the respective platform.

                            +

                            Enabling the API

                            + +

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

                            + +
                            :::ruby
                            +extensions: ["mediaplayer"]
                            +
                            + +

                            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

                            + +

                            getAllRingtones(CallBackHandler callback)

                            Getting all ringtones on the device – result is array of hashes , each HASH contains name, fullname pairs of info about ringtone.

                            +

                            Parameters

                            • callback : CallBackHandler Mandatory

                            Async Callback Returning Parameters: ARRAY

                              • Object : HASH

                                • name : STRING

                                • fullname : STRING

                            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.Mediaplayer.getAllRingtones(CallBackHandler callback)
                              • Ruby: Rho::Mediaplayer.getAllRingtones(CallBackHandler callback)

                            playRingTone(STRING name)

                            Play a ringtone with the name supplied being used to designate which one. You cannot supply a location for the ringtone. They are built in. To get a full list of all ringtones available on the system use the method getAllRintones.

                            +

                            Parameters

                            • name : STRING

                              Name of the ringtone to be played.

                              +

                            Synchronous Return:

                            • Void

                            Method Access:

                            • Class Method: This method can only be accessed via the API class object.
                              • JavaScript: Rho.Mediaplayer.playRingTone(STRING name)
                              • Ruby: Rho::Mediaplayer.playRingTone(STRING name)

                            start(STRING filename)

                            Play the audio file using the supplied filename. On WM/CE devices, the API supports only wav file format.

                            +

                            Parameters

                            • filename : STRING

                              File name of the audio media to be played – absolute filepath. On iOS when you post URL to remote server (except https), then we open a standard browser (another application) for playing it. On iOS we support: mp3, mp4, wav formats. On other platforms the formats supported depends on what support is built into the platform. Typically on WM/CE this will be wav and on Android mp3.

                              +

                            Synchronous Return:

                            • Void

                            Method Access:

                            • Class Method: This method can only be accessed via the API class object.
                              • JavaScript: Rho.Mediaplayer.start(STRING filename)
                              • Ruby: Rho::Mediaplayer.start(STRING filename)

                            startvideo(STRING filename)

                            Play the media file using the supplied filename. On WM/CE devices, it launches a media player process to play the supplied filename.

                            +

                            Parameters

                            • filename : STRING

                              File name of the video media to be played – full filepath. On iOS when you post URL to remote server (except https), then we open a standard browser (another application) for playing it. On iOS we support: mov, mp4, 3gp formats. On other platforms the formats supported depends on what support is built into the platform. Typically on WM/CE this will be wmv and on Android mp4.

                              +

                            Synchronous Return:

                            • Void

                            Method Access:

                            • Class Method: This method can only be accessed via the API class object.
                              • JavaScript: Rho.Mediaplayer.startvideo(STRING filename)
                              • Ruby: Rho::Mediaplayer.startvideo(STRING filename)

                            stop()

                            Stop playing the media file. Not applicable on iOS, because on iOS the special UI is opened for playback audio / video – user can stop / close player by UI.

                            +

                            Synchronous Return:

                            • Void

                            Method Access:

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

                            stopRingTone()

                            Stop the currently playing ringtone.

                            +

                            Synchronous Return:

                            • Void

                            Method Access:

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

                            stopvideo()

                            Stop the playback of a currently playing video file. Not applicable on iOS, because on iOS the special UI is opened for playback audio / video – user can stop / close player by UI.

                            +

                            Synchronous Return:

                            • Void

                            Method Access:

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

                            Examples

                            + +
                            Play the first available ringtone
                            +
                            :::javascript
                            +
                            +                  
                            +function list_ringtones() {
                            +  // Enumerate ringtones
                            +  Rho.Mediaplayer.getAllRingtones(list_ringtones_callback);
                            +}
                            +
                            +function list_ringtones_callback(params) {
                            +  // play the first ringtone
                            +  var first_ringtone = params[0]["name"];
                            +  Rho.Mediaplayer.playRingTone(first_ringtone);
                            +}
                            +                  
                            +                 
                            :::ruby
                            +
                            +                  
                            +def list_ringtones
                            +  # Enumerate ringtones
                            +  Rho::Mediaplayer.getAllRingtones(url_for(:action => :list_ringtones_callback))
                            +end
                            +
                            +def list_ringtones_callback
                            +  # Play the first ringtone
                            +  first_ringtone = @params[0]["name"]
                            +  Rho::Mediaplayer.playRingTone(first_ringtone)
                            +end
                            +                   
                            +                 
                            + +

                            Remarks

                            + +
                            Availbility of Operating System

                            Because the MediaPlayer extension uses the operating system’s built-in player for some media types, it may be possible for the user to access operating system features while media is playing.

                            +
                            Playback Controls

                            Because the MediaPlayer extension uses the operating system’s built-in player for some media types, the playback controls available to the user are outside the control of RhoElements. Some players may have no playback controls in which the user will have to wait for the media to finish playing.

                            +
                            Android Support

                            On Android devices, HTTPS is supported only on Android versions 4.0 (Ice Cream Sandwich) or newer.

                            +
                            Using File Transfer

                            When more flexible file transfer is required than is provided by MediaPlayer itself it is recommended to use the Network API to fetch the media file, and then to play the local file using MediaPlayer. For example, if playing a file from an FTP server, or an HTTP server requiring authentication. This can also be more efficient if the same file is to be played multiple times, especially on Windows Mobile/CE, where there is no streaming support and therefore the file is completely downloaded before being played. On Windows Mobile/CE devices, HTTPS file transfer is not supported.

                            +
                            \ No newline at end of file diff --git a/docs/en/5.5/api/mediaplayer.xml b/docs/en/5.5/api/mediaplayer.xml new file mode 100644 index 00000000..f348d07e --- /dev/null +++ b/docs/en/5.5/api/mediaplayer.xml @@ -0,0 +1,194 @@ + + + + + The MediaPlayer extension is used to playback different types of audio files. It also allows the playback of Ringtones for the respective platform. + + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["mediaplayer"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + +## Enabling the API +There are two methods of enabling the MediaPlayer API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the MediaPlayer API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.mediaplayer.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + WM, CE, Android, iOS + Android, WM, CE + + + + + + + + Play the audio file using the supplied filename. On WM/CE devices, the API supports only wav file format. + WM, CE, Android, iOS + Android, WM, CE + + + File name of the audio media to be played - absolute filepath. On iOS when you post URL to remote server (except https), then we open a standard browser (another application) for playing it. On iOS we support: mp3, mp4, wav formats. On other platforms the formats supported depends on what support is built into the platform. Typically on WM/CE this will be wav and on Android mp3. + File name of the audio media to be played - absolute filepath. The formats supported depends on what support is built into the platform. Typically on WM/CE this will be wav and on Android mp3. + + + + + + Stop playing the media file. Not applicable on iOS, because on iOS the special UI is opened for playback audio / video - user can stop / close player by UI. + Stop playing the media file. + WM, CE, Android + + + + + Play the media file using the supplied filename. On WM/CE devices, it launches a media player process to play the supplied filename. + + + File name of the video media to be played - full filepath. On iOS when you post URL to remote server (except https), then we open a standard browser (another application) for playing it. On iOS we support: mov, mp4, 3gp formats. On other platforms the formats supported depends on what support is built into the platform. Typically on WM/CE this will be wmv and on Android mp4. + File name of the video media to be played - full filepath. The formats supported depends on what support is built into the platform. Typically on WM/CE this will be wmv and on Android mp4. + + + + + + Stop the playback of a currently playing video file. Not applicable on iOS, because on iOS the special UI is opened for playback audio / video - user can stop / close player by UI. + Stop the playback of a currently playing video file. + WM, CE, Android + + + + + Getting all ringtones on the device - result is array of hashes , each HASH contains name, fullname pairs of info about ringtone. + Android + + + + + + + + + + + + + + + + Play a ringtone with the name supplied being used to designate which one. You cannot supply a location for the ringtone. They are built in. To get a full list of all ringtones available on the system use the method getAllRintones. + Android + + + Name of the ringtone to be played. + + + + + + Stop the currently playing ringtone. + Android + + + + + + + + 1.0.0 + + + + + + + + + + + + + + + + + + + + +
                            + + + :list_ringtones_callback)) +end + +def list_ringtones_callback + # Play the first ringtone + first_ringtone = @params[0]["name"] + Rho::Mediaplayer.playRingTone(first_ringtone) +end + ]]> + + + + + +
                            +
                            +
                            +
                            +
                            +
                            \ No newline at end of file diff --git a/docs/en/5.5/api/printing.md b/docs/en/5.5/api/printing.md new file mode 100644 index 00000000..4099dfe0 --- /dev/null +++ b/docs/en/5.5/api/printing.md @@ -0,0 +1,324 @@ +#Printer +
                            +

                            The Printer API module provides access to find, connect, and print over Bluetooth, Wi-Fi and USB from Android and Windows Mobie/CE devices.

                            +

                            This general API does not provide access to manufacturer-specific features such as those found in the PrintingZebra API. If you wish to have access to general and manufacturer-specific features, you must include this general API as as well as the printer-specific extension in your build.yml file.

                            + +

                            Notes

                            + +
                              +
                            1. Windows Mobile/CE platforms require the Printing Service application to be running. This is described in the Printing Guide.
                            2. +
                            3. Unless using the printer’s ‘line mode’ (for sending raw text strings), Zebra recommends sending ZPL only.
                            4. +
                            5. USB printing is supported on Android and Windows Mobile/CE platforms on RMS 5.3 and higher.
                            6. +
                            + + +

                            Enabling the API

                            + +

                            To use this API you must include the following extension in your build.yml:

                            + +
                            :::ruby
                            +extensions: ["printing"]
                            +
                            + +

                            Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown in the build-time settings guide.

                            + +

                            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

                            + +

                            connect(CallBackHandler callback)

                            Connect to a printer using default options. Works asynchronously; use callback to check the result. If connection is successful printer state and properties are automatically updated. **Note: Default options are defined by printer SDK and platform and may vary between different devices.

                            +

                            Parameters

                            • callback : CallBackHandler Optional

                            Async Callback Returning Parameters: STRING

                              Synchronous Return:

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

                              Method Access:

                              • Instance Method: This method can be accessed via an instance object of this class:
                                • myObject.connect(CallBackHandler callback)
                              • Default Instance: This method can be accessed via the default instance object of this class.
                                • JavaScript: Rho.Printer.connect(CallBackHandler callback)
                                • Ruby: Rho::Printer.connect(CallBackHandler callback)

                              connectWithOptions(HASH options, CallBackHandler callback)

                              Connect to a printer with user options. Works asynchronously; use callback to check the result. After this function call, the printer state is automatically updated.

                              +

                              Parameters

                              • options : HASH

                                Connect options.

                                +

                                • timeout : INTEGER Optional Default: 15000

                                  Connection timeout in milliseconds. Must be larger than 0.

                                  + Platforms:WM, CE, iOS, Android

                                • additionalStringOption : STRING Optional

                                  Any additional info; currently unused.

                                  +

                              • callback : CallBackHandler Optional

                              Async Callback Returning Parameters: STRING

                                Synchronous Return:

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

                                Method Access:

                                • Instance Method: This method can be accessed via an instance object of this class:
                                  • myObject.connectWithOptions(HASH options, CallBackHandler callback)
                                • Default Instance: This method can be accessed via the default instance object of this class.
                                  • JavaScript: Rho.Printer.connectWithOptions(HASH options, CallBackHandler callback)
                                  • Ruby: Rho::Printer.connectWithOptions(HASH options, CallBackHandler callback)

                                disconnect(CallBackHandler callback)

                                Disconnect from a printer and release OS resources. Works asynchronously; use callback to check the result.

                                +

                                Parameters

                                • callback : CallBackHandler Optional

                                Async Callback Returning Parameters: STRING

                                  Synchronous Return:

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

                                  Method Access:

                                  • Instance Method: This method can be accessed via an instance object of this class:
                                    • myObject.disconnect(CallBackHandler callback)
                                  • Default Instance: This method can be accessed via the default instance object of this class.
                                    • JavaScript: Rho.Printer.disconnect(CallBackHandler callback)
                                    • Ruby: Rho::Printer.disconnect(CallBackHandler callback)

                                  getAllProperties(CallBackHandler callback)

                                  This method will return all of object/value pairs for the propertyNames of the API class.

                                  +

                                  Parameters

                                  • callback : CallBackHandler Optional

                                  Async Callback Returning Parameters: HASH

                                    • : STRING

                                  Synchronous Return:

                                  • HASH :

                                    Map of all available properties

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

                                  Method Access:

                                  • Instance Method: This method can be accessed via an instance object of this class:
                                    • myObject.getAllProperties(CallBackHandler callback)
                                  • Default Instance: This method can be accessed via the default instance object of this class.
                                    • JavaScript: Rho.Printer.getAllProperties(CallBackHandler callback)
                                    • Ruby: Rho::Printer.getAllProperties(CallBackHandler callback)

                                  getDefault()

                                  This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

                                  +

                                  Synchronous Return:

                                  • SELF_INSTANCE :

                                    Default object of Module.

                                    +

                                  Method Access:

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

                                  getPrinterByID(STRING printerId)

                                  Returns printer instance specified by printerId. Returns null is no printers contains the ID. To get valid printerId, use searchPrinters function.

                                  +

                                  Parameters

                                  • printerId : STRING

                                  Synchronous Return:

                                  • SELF_INSTANCE

                                  Method Access:

                                  • Class Method: This method can only be accessed via the API class object.
                                    • JavaScript: Rho.Printer.getPrinterByID(STRING printerId)
                                    • Ruby: Rho::Printer.getPrinterByID(STRING printerId)

                                  getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                  This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                                  +

                                  Parameters

                                  • arrayofNames : ARRAY

                                    List of properties I want to know about

                                    +

                                    • Object : STRING

                                  • callback : CallBackHandler Optional

                                  Async Callback Returning Parameters: HASH

                                    • : STRING

                                  Synchronous Return:

                                  • HASH :

                                    Map of properties I want to know about

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

                                  Method Access:

                                  • Instance Method: This method can be accessed via an instance object of this class:
                                    • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                  • Default Instance: This method can be accessed via the default instance object of this class.
                                    • JavaScript: Rho.Printer.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                    • Ruby: Rho::Printer.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                  getProperty(STRING propertyName, CallBackHandler callback)

                                  This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                                  +

                                  Parameters

                                  • propertyName : STRING

                                    The property to return info about.

                                    +

                                  • callback : CallBackHandler Optional

                                  Async Callback Returning Parameters: STRING

                                    Synchronous Return:

                                    • STRING :

                                      The property to return info about.

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

                                    Method Access:

                                    • Instance Method: This method can be accessed via an instance object of this class:
                                      • myObject.getProperty(STRING propertyName, CallBackHandler callback)
                                    • Default Instance: This method can be accessed via the default instance object of this class.
                                      • JavaScript: Rho.Printer.getProperty(STRING propertyName, CallBackHandler callback)
                                      • Ruby: Rho::Printer.getProperty(STRING propertyName, CallBackHandler callback)

                                    printFile(STRING filePathOnDevice, HASH options, CallBackHandler callback)

                                    Prints file. Works asynchronously; use callback to check the result. File extension is used to determine its type. Supported image types: JPEG and PNG.

                                    +

                                    Parameters

                                    • filePathOnDevice : STRING

                                      Full path to local image file on the device.

                                      +

                                    • options : HASH Optional

                                      Providing no properties to this function will print with default settings. Reserved for future use.

                                      +

                                      • propertyWithStringValue : STRING Optional

                                        This is currently not being used.

                                        +

                                      • propertyWithIntValue : INTEGER Optional

                                        Currently unused.

                                        +

                                    • callback : CallBackHandler Optional

                                    Async Callback Returning Parameters: STRING

                                      Synchronous Return:

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

                                      Method Access:

                                      • Instance Method: This method can be accessed via an instance object of this class:
                                        • myObject.printFile(STRING filePathOnDevice, HASH options, CallBackHandler callback)
                                      • Default Instance: This method can be accessed via the default instance object of this class.
                                        • JavaScript: Rho.Printer.printFile(STRING filePathOnDevice, HASH options, CallBackHandler callback)
                                        • Ruby: Rho::Printer.printFile(STRING filePathOnDevice, HASH options, CallBackHandler callback)

                                      printImageFromFile(STRING filePathOnDevice, INTEGER x, INTEGER y, HASH options, CallBackHandler callback)

                                      Prints an image from a device’s file system to the connected printer as a monochrome image. Works asynchronously; use callback to check the result. Images larger than 1024x768 might take a long time or print incorrectly. Consult printer documentation for image printing parameters.

                                      +

                                      Parameters

                                      • filePathOnDevice : STRING

                                        Full path to local image file on the device. (The image must be either a PNG or JPG, all other types are platform depend).

                                        +

                                      • x : INTEGER

                                        Horizontal starting position in dots.

                                        +

                                      • y : INTEGER

                                        Vertical starting position in dots.

                                        +

                                      • options : HASH Optional

                                        Provide a set of optional parameters.

                                        +

                                        • width : INTEGER

                                          Desired width of the printed image. Passing -1 will preserve original width.

                                          +

                                        • height : INTEGER

                                          Desired height of the printed image. Passing -1 will preserve original height.

                                          +

                                        • isInsideFormat : BOOLEAN

                                          Boolean value indicating whether this image should be printed by itself (false), or is part of a format being written to the connection (true).

                                          +

                                      • callback : CallBackHandler Optional

                                      Async Callback Returning Parameters: STRING

                                        Synchronous Return:

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

                                        Method Access:

                                        • Instance Method: This method can be accessed via an instance object of this class:
                                          • myObject.printImageFromFile(STRING filePathOnDevice, INTEGER x, INTEGER y, HASH options, CallBackHandler callback)
                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.printImageFromFile(STRING filePathOnDevice, INTEGER x, INTEGER y, HASH options, CallBackHandler callback)
                                          • Ruby: Rho::Printer.printImageFromFile(STRING filePathOnDevice, INTEGER x, INTEGER y, HASH options, CallBackHandler callback)

                                        printRawString(STRING command, HASH options, CallBackHandler callback)

                                        Send raw string to printer. Works asynchronously, use callback to check the result. **Note: This method will not print ZPL commands from Windows Mobile/CE devices to Zebra printers; compatible with line mode or raw text only.

                                        +

                                        Parameters

                                        • command : STRING

                                          Raw string to print. Could be any valid command in printer supported programming language.

                                          +

                                        • options : HASH Optional

                                          Providing no properties to this function will print with default settings.

                                          +

                                          • propertyWithStringValue : STRING Optional

                                            This is currently not being used.

                                            +

                                          • propertyWithIntValue : INTEGER Optional

                                            Currently unused.

                                            +

                                        • callback : CallBackHandler Optional

                                        Async Callback Returning Parameters: HASH

                                          • status : STRING

                                            PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR.

                                            +

                                          • message : STRING Optional

                                            Error message, only if status = ERROR.

                                            +

                                          • stringResponce : STRING Optional

                                            Response from printer if received, converted to string from byteArray(original data)

                                            + Platforms:Android, WM

                                          • byteArrayResponce : ARRAY Optional

                                            Response from printer if received.

                                            + Platforms:Android

                                            • Object : INTEGER

                                        Synchronous Return:

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

                                        Method Access:

                                        • Instance Method: This method can be accessed via an instance object of this class:
                                          • myObject.printRawString(STRING command, HASH options, CallBackHandler callback)
                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.printRawString(STRING command, HASH options, CallBackHandler callback)
                                          • Ruby: Rho::Printer.printRawString(STRING command, HASH options, CallBackHandler callback)

                                        requestState(ARRAY listOfParameters, CallBackHandler callback)

                                        Requests printer state with a list of parameters. Works asynchronously and uses the callback to check the result. Returns hash with status and parameters as keys. **NOTE: On the Windows Mobile / Windows CE platform, this method does not work in the case of a Bluetooth and USB connection.

                                        +

                                        Parameters

                                        • listOfParameters : ARRAY

                                          List of parameters for request from printer device.

                                          +

                                          • Object : STRING

                                            Parameter name – see constants with PRINTER_STATE_…

                                            +

                                        • callback : CallBackHandler Mandatory

                                        Async Callback Returning Parameters: HASH

                                          • status : STRING

                                            PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR.

                                            +

                                          • message : STRING Optional

                                            Error message, only if status = ERROR.

                                            +

                                          • propertyWithIntValue : INTEGER Optional

                                            Currently unused.

                                            +

                                        Synchronous Return:

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

                                        Method Access:

                                        • Instance Method: This method can be accessed via an instance object of this class:
                                          • myObject.requestState(ARRAY listOfParameters, CallBackHandler callback)
                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.requestState(ARRAY listOfParameters, CallBackHandler callback)
                                          • Ruby: Rho::Printer.requestState(ARRAY listOfParameters, CallBackHandler callback)

                                        searchPrinters(HASH options, CallBackHandler callback)

                                        Searches for printers connected to the device via Bluetooth®, Wi-Fi or USB. To reduce search times, it is highly recommended that searches for wireless connections be done by specific MAC address (Bluetooth) or IP address (Wi-Fi). This method also can be used to retrieve the printerID for a known Bluetooth or network printer specifying the deviceAddress options parameter. Result is returned asynchronously using a callback called for each discovered printer. Search is finished if printerID is not set in callback hash. Note that discovery is not guaranteed to return all the available devices. It is therefore recommended that this method run 2-3 times for maximum accuracy.

                                        + +
                                                        **NOTE**: On certain Android devices, calling searchPrinters() over Bluetooth or TCP can cause the application to freeze momentarily or to display an alert that "The application has stopped responding." In such cases, it is recommended that the user tap the "Continue waiting" button. 
                                        +
                                        +

                                        Parameters

                                        • options : HASH Optional

                                          Options for discover.

                                          +

                                          • printerType : STRING Optional Default: PRINTER_TYPE_ANY

                                            Printer types to search. Make sure that Printer type is supported by calling enumerateSupportedTypes method.

                                            +

                                          • connectionType : STRING Optional Default: CONNECTION_TYPE_ANY

                                            Interfaces for search (Bluetooth/TCP/All).

                                            +

                                          • timeout : INTEGER Optional Default: 30000

                                            Maximum search interval in milliseconds, applies to network discovery. This is the maximum interval for wait during connection attempt. Note that if no printer was found, even with timeout property, status will be set to PRINTER_STATUS_SUCCESS, but without any printerId.

                                            +

                                          • deviceAddress : STRING Optional

                                            Printer address (MAC, device serial number or IP address) can be used for setting either subnet mask or full address of printer. For TCP if address is not specified /8 subnet will be used for search.

                                            +

                                          • devicePort : INTEGER Optional Default: 6101

                                            Override default printer port number. Applicable for network discovery only.

                                            +

                                        • callback : CallBackHandler Mandatory

                                        Async Callback Returning Parameters: HASH

                                          • status : STRING

                                            Status of network discovery, can be the following: +* PRINTER_STATUS_SUCCESS – when printer is discovered or operation is finished; +* PRINTER_STATUS_ERROR – general error +* PRINTER_STATUS_ERR_UNSUPPORTED – in case if printer type is not supported +* PRINTER_STATUS_ERR_NOT_CONNECTED – in case if deviceAddress was specified in options and device was unable to connect to printer.

                                            +

                                          • printerID : STRING Optional

                                            **Printer ID, valid only if status equals = ‘PRINTER_STATUS_SUCCESS’. If no more printers are available, printerID will be undefined.

                                            +

                                          • message : STRING Optional

                                            Error message if status = ERROR**.

                                            +

                                        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.Printer.searchPrinters(HASH options, CallBackHandler callback)
                                          • Ruby: Rho::Printer.searchPrinters(HASH options, CallBackHandler callback)

                                        setDefault(SELF_INSTANCE: Rho::Printer defaultInstance)

                                        This method allows you to set the attributes of the default object instance by passing in an object of the same class.

                                        +

                                        Parameters

                                        • defaultInstance : SELF_INSTANCE: Rho::Printer

                                          An instance object that is of the same class.

                                          +

                                        Synchronous Return:

                                        • Void

                                        Method Access:

                                        • Class Method: This method can only be accessed via the API class object.
                                          • JavaScript: Rho.Printer.setDefault(SELF_INSTANCE: Rho::Printer defaultInstance)
                                          • Ruby: Rho::Printer.setDefault(SELF_INSTANCE: Rho::Printer defaultInstance)

                                        setProperties(HASH propertyMap)

                                        This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                        +

                                        Parameters

                                        • propertyMap : HASH

                                          Map of properties I want to set

                                          +

                                          • Object : STRING

                                        Synchronous Return:

                                        • Void

                                        Method Access:

                                        • Instance Method: This method can be accessed via an instance object of this class:
                                          • myObject.setProperties(HASH propertyMap)
                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.setProperties(HASH propertyMap)
                                          • Ruby: Rho::Printer.setProperties(HASH propertyMap)

                                        setProperty(STRING propertyName, STRING propertyValue)

                                        This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                        +

                                        Parameters

                                        • propertyName : STRING

                                          The one property name that I want to set

                                          +

                                        • propertyValue : STRING

                                          The one property value that I want to set

                                          +

                                        Synchronous Return:

                                        • Void

                                        Method Access:

                                        • Instance Method: This method can be accessed via an instance object of this class:
                                          • myObject.setProperty(STRING propertyName, STRING propertyValue)
                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.setProperty(STRING propertyName, STRING propertyValue)
                                          • Ruby: Rho::Printer.setProperty(STRING propertyName, STRING propertyValue)

                                        stopSearch()

                                        Immediately stops all active search requests and cancels pending search requests. Does not return a result.

                                        +

                                        Synchronous Return:

                                        • Void

                                        Method Access:

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

                                        Properties

                                        + +

                                        ID : STRING Read Only 4.1.0

                                        Unique printer ID during application lifetime.

                                        +

                                        Property Access:

                                        • Instance: This property can be accessed via an instance object of this class:
                                          • myObject.ID
                                        • Default Instance: This property can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.ID
                                          • Ruby: Rho::Printer.ID

                                        connectionType : STRING Read Only 4.1.0

                                        Type of connection to printer.

                                        +

                                        Property Access:

                                        • Instance: This property can be accessed via an instance object of this class:
                                          • myObject.connectionType
                                        • Default Instance: This property can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.connectionType
                                          • Ruby: Rho::Printer.connectionType

                                        deviceAddress : STRING Read Only 4.1.0

                                        IP address for Wi-Fi connection, Bluetooth® MAC address or device serial number. Note: iOS uses device serial number instead of MAC address. If you need to get device MAC you can use CPCL command ! U1 getvar “bluetooth.address”

                                        +

                                        Property Access:

                                        • Instance: This property can be accessed via an instance object of this class:
                                          • myObject.deviceAddress
                                        • Default Instance: This property can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.deviceAddress
                                          • Ruby: Rho::Printer.deviceAddress

                                        deviceName : STRING Read Only 4.1.0

                                        Bluetooth/Network name of printer.

                                        +

                                        Property Access:

                                        • Instance: This property can be accessed via an instance object of this class:
                                          • myObject.deviceName
                                        • Default Instance: This property can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.deviceName
                                          • Ruby: Rho::Printer.deviceName

                                        devicePort : INTEGER 4.1.0

                                        Default port when connecting with TCP/IP.

                                        +

                                        Property Access:

                                        • Instance: This property can be accessed via an instance object of this class:
                                          • myObject.devicePort
                                        • Default Instance: This property can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.devicePort
                                          • Ruby: Rho::Printer.devicePort

                                        isConnected : BOOLEAN Read Only 4.1.0

                                        Connection status flag. All other properties are valid only if isConnect = true. Note: This property does not guarantee a real connection, because all real device functionality is processed in separate thread asynchronously. If you want a real physical connection, use requestState() method with receive result in the callback. This is the only guaranteed method of processing real requests to the device and analyzing answers from the device.

                                        +

                                        Property Access:

                                        • Instance: This property can be accessed via an instance object of this class:
                                          • myObject.isConnected
                                        • Default Instance: This property can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.isConnected
                                          • Ruby: Rho::Printer.isConnected

                                        printerType : STRING Read Only 4.1.0

                                        Type of printer – see PRINTER_TYPE_… constants.

                                        +

                                        Property Access:

                                        • Instance: This property can be accessed via an instance object of this class:
                                          • myObject.printerType
                                        • Default Instance: This property can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.Printer.printerType
                                          • Ruby: Rho::Printer.printerType
                                        + +

                                        Constants

                                        + +
                                        PRINTER_LANGUAGE_ZPL

                                        Printer control language ZPL

                                        +
                                        PRINTER_LANGUAGE_CPCL

                                        Printer control language CPCL

                                        +
                                        PRINTER_LANGUAGE_EPS

                                        Printer control language EPS. Not Supported in RMS 4.1

                                        +
                                        PRINTER_TYPE_ANY
                                        PRINTER_TYPE_NATIVE

                                        Not supported in RMS 4.1

                                        +
                                        PRINTER_TYPE_ZEBRA
                                        PRINTER_TYPE_EPSON

                                        Not supported in RMS 4.1

                                        +
                                        PRINTER_TYPE_APD

                                        Not supported in RMS 4.1

                                        +
                                        CONNECTION_TYPE_ANY
                                        CONNECTION_TYPE_ON_BOARD

                                        Not supported in RMS 4.1

                                        +
                                        CONNECTION_TYPE_USB

                                        Supported in RMS 5.1, EB 1.3

                                        +
                                        CONNECTION_TYPE_BLUETOOTH
                                        CONNECTION_TYPE_TCP
                                        PRINTER_STATUS_SUCCESS
                                        PRINTER_STATUS_ERROR
                                        PRINTER_STATUS_ERR_IO
                                        PRINTER_STATUS_ERR_MEMORY
                                        PRINTER_STATUS_ERR_NETWORK
                                        PRINTER_STATUS_ERR_NOT_CONNECTED
                                        PRINTER_STATUS_ERR_NOT_FOUND
                                        PRINTER_STATUS_ERR_PARAM
                                        PRINTER_STATUS_ERR_PROCESSING
                                        PRINTER_STATUS_ERR_RESPONSE
                                        PRINTER_STATUS_ERR_TIMEOUT
                                        PRINTER_STATUS_ERR_UNSUPPORTED
                                        PRINTER_STATE_IS_READY_TO_PRINT

                                        Use this name for requestState(), return true if printer ready to print.

                                        +
                                        PRINTER_STATE_IS_COVER_OPENED

                                        Use this name for requestState(), return true if cover is opened.

                                        +
                                        PRINTER_STATE_IS_DRAWER_OPENED

                                        Use this name for requestState(), return true if drawer is opened.

                                        +
                                        PRINTER_STATE_IS_PAPER_OUT

                                        Use this name for requestState(), return true if paper out.

                                        +
                                        PRINTER_STATE_IS_BATTERY_LOW

                                        Use this name for requestState(), return true if battery low.

                                        +
                                        + +

                                        Examples

                                        + +
                                        Printing via Bluetooth
                                        +

                                        To print to the Zebra printer, your app must first search for the device. In this example we are using the searchPrinters method and passing in options to limit the search to Bluetooth and also look for Zebra printers only. If we knew the printer Bluetooth address we could have added the ‘deviceAddress’ parameter. The callback function will be executed for each printer found. When a printer is found the callback object will contain a ‘printerID’ property. This ID is an internal RhoMobie ID used. If no printerID property is there for the successful callback object, then it means that the search has finished.

                                        +
                                        :::javascript
                                        +
                                        +var printers = [];
                                        +
                                        +Rho.Printer.searchPrinters({
                                        +    connectionType:Rho.Printer.CONNECTION_TYPE_BLUETOOTH,
                                        +    printerType: Rho.Printer.PRINTER_TYPE_ZEBRA
                                        +    }, function (cb){
                                        +        if(cb.status == 'PRINTER_STATUS_SUCCESS')
                                        +        {
                                        +            if (typeof cb.printerID != "undefined")
                                        +            {
                                        +                console.log('Found: ' + cb.printerID)
                                        +                printers.push(cb.printerID);
                                        +            }
                                        +            else
                                        +            {
                                        +                console.log('Done Searching');
                                        +            }
                                        +        }
                                        +        else
                                        +        {
                                        +            console.log(cb.status);
                                        +        }
                                        +    }
                                        +);
                                        +
                                        +                            
                                        :::ruby
                                        +
                                        +@printers = []
                                        +
                                        +Rho::Printer.searchPrinters({ connectionType  => Rho::Printer::CONNECTION_TYPE_BLUETOOTH,
                                        +                              printerType     => Rho::Printer::PRINTER_TYPE_ZEBRA },
                                        +                              url_for(:action => :printer_callback) )
                                        +
                                        +def find_printer_callback
                                        +  if @params['status'] == 'PRINTER_STATUS_SUCCESS'
                                        +    if defined? @params['printerID']
                                        +      puts "Found: #{@params['printerID']}"
                                        +      @printers.push @params['printerID']
                                        +    else
                                        +      puts "Done Searching"
                                        +    end
                                        +  else
                                        +    puts @params['status']
                                        +  end
                                        +end
                                        +
                                        +                            
                                        +

                                        Now that we have found a printer. The printers array will contain the printerID we need to create an instance object that we will use for all communications. Upon first connection to the printer via Bluetooth, you may see a prompt to enter the Bluetooth PIN. Check the manufacturers guide for details. Normally the default is ‘0000’ or ‘1111’ or ‘1234’. Once it is connected, you should see some indication in the printer (like a blue light).

                                        +
                                        :::javascript
                                        +
                                        +var myPrinter = Rho.Printer.getPrinterByID(printers[0]);
                                        +
                                        +// Let's try connecting
                                        +myPrinter.connect(function (cb){
                                        +    console.log(cb);
                                        +    // This will be the Zebra's `Friendly Name`
                                        +    // by default it is the serial number
                                        +    console.log(myPrinter.deviceName);
                                        +
                                        +    // This will be the BT MC Address
                                        +    since we are connecting via BlueTooth
                                        +    console.log(myPrinter.deviceAddress);
                                        +});
                                        +
                                        +                            
                                        :::ruby
                                        +
                                        +@my_printer = Rho::Printer.getPrinterByID printers[0]
                                        +
                                        +# Let's try connecting
                                        +@my_printer.connect url_for(:action => :printer_connect_callback)
                                        +
                                        +def printer_connect_callback
                                        +  puts @params.to_s
                                        +
                                        +  # This will be the Zebra's `Friendly Name`
                                        +  # by default it is the serial number
                                        +  puts @my_printer['deviceName']
                                        +
                                        +  # This will be the BT MAC Address
                                        +  # since we are connecting via BlueTooth
                                        +  puts @my_printer['deviceAddress']
                                        +end
                                        +
                                        +                            
                                        +

                                        Now we can just print a test string and read some properties of the printer to make sure the communications is working.

                                        +
                                        :::javascript
                                        +
                                        +// If my printer was in line mode I would see this text printed
                                        +myPrinter.printRawString('This is a test print');
                                        +
                                        +// Example of sending a Zebra CPCL Command
                                        +// changing from linemode to ZPL mode
                                        +myPrinter.printRawString('! U1 setvar "device.languages" "ZPL"\r\n');
                                        +
                                        +// Get state - this is real-time status of printer.
                                        +// reading a property of the myPrinter instance will
                                        +// show last known status
                                        +myPrinter.requestState(['PRINTER_STATE_IS_READY_TO_PRINT',
                                        +    'PRINTER_STATE_IS_PAPER_OUT'],function (cb){
                                        +        console.log(cb.status);
                                        +        console.log(cb.PRINTER_STATE_IS_PAPER_OUT);
                                        +        console.log(cb.PRINTER_STATE_IS_READY_TO_PRINT);
                                        +
                                        +    });
                                        +                   
                                        +                            
                                        :::ruby
                                        +
                                        +# If my printer was in line mode I would see this text printed
                                        +@my_printer.printRawString 'This is a test print'
                                        +
                                        +# Example of sending a Zebra CPCL Command
                                        +# changing from linemode to ZPL mode
                                        +@my_printer.printRawString '! U1 setvar "device.languages" "ZPL"\r\n'
                                        +
                                        +# Get state - this is real-time status of printer.
                                        +# reading a property of the @my_printer instance will
                                        +# show last known status
                                        +@my_printer.requestState([Rho::Printer::PRINTER_STATE_IS_READY_TO_PRINT,
                                        +                          Rho::Printer::PRINTER_STATE_IS_PAPER_OUT],
                                        +                          url_for(:action => :request_state_callback));
                                        +
                                        +def request_state_callback
                                        +  puts @params['status']
                                        +  puts @params['PRINTER_STATE_IS_PAPER_OUT']
                                        +  puts @params['PRINTER_STATE_IS_READY_TO_PRINT']
                                        +end
                                        +
                                        +                            
                                        + +

                                        Remarks

                                        + +
                                        iOS Notes

                                        To use a Bluetooth connection on iOS devices, take into account the following preconditions:

                                        + +
                                          +
                                        • Zebra printer must have ‘Made For iPod/iPhone’ certification.
                                        • +
                                        • Before using Bluetooth printer, pair it using the iOS system’s Bluetooth settings.
                                        • +
                                        • Your project must include the External Accessory framework (automatically added when iPhone projects are generated).
                                        • +
                                        • Project must include the Zebra printer protocol string “com.zebra.rawport” in the info.plist file ([project root]/project/iphone/Info.plist) under “Supported external accessory protocols”: + +
                                            <key>UISupportedExternalAccessoryProtocols</key>
                                          +  <array>
                                          +      <string>com.zebra.rawport</string>
                                          +  </array>
                                          +
                                        • +
                                        • You must set the key ‘Required Background modes’ to ‘App Communicates with an accessory’ in your app’s plist file. + +
                                            <key>UIBackgroundModes</key>
                                          +  <array>
                                          +      <string>external-accessory</string>
                                          +  </array>
                                          +
                                        • +
                                        + +
                                        Android Notes
                                          +
                                        • When calling searchPrinters() with Bluetooth search (CONNECTION_TYPE_ANY or CONNECTION_TYPE_BLUETOOTH), all local Bluetooth devices—including non-printers—will be discovered and send pairing requests. Just cancel or ignore them. This happens because the software cannot detect non-printers until after the device is paired. It is recommended that the BT or Wi-Fi MAC address also be used when searching for printers.

                                        • +
                                        • When calling searchPrinters() with USB search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_USB), all USB Printers connected to the device will be discovered. If USB printers are not supported by SDK or device, searchPrinters function should return PRINTER_STATUS_ERR_UNSUPPORTED.

                                        • +
                                        + +
                                        Windows Mobile/CE Notes
                                          +
                                        • Requires a Printing Service application to be running. This is described in the Printing Guide.

                                        • +
                                        • You should avoid navigating from the current page using the printer without disconnecting from the printer first. You can use the window.onunload event:

                                          + +
                                            :::javascript
                                          +  window.onunload = function(){
                                          +      printer.disconnect();
                                          +  }
                                          +
                                        • +
                                        • When calling searchPrinters() with Bluetooth search (CONNECTION_TYPE_ANY or CONNECTION_TYPE_BLUETOOTH), all local Bluetooth devices—including non-printers—will be discovered and send pairing requests. Just cancel or ignore them. This happens because the software cannot detect non-printers until after the device is paired. It is recommended that the BT or Wi-Fi MAC address also be used when searching for printers.

                                        • +
                                        • Before calling searchPrinters() with USB search (CONNECTION_TYPE_ANY or CONNECTION_TYPE_USB), you should configure the device’s USB controller for “USB Host mode” and reboot.

                                        • +
                                        • When calling searchPrinters() with USB search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_USB), all USB Printers connected to the device will be discovered. If USB printers are not supported by SDK or device, searchPrinters function should return PRINTER_STATUS_ERR_UNSUPPORTED.

                                        • +
                                        • USB connection is not supported on QLn320; printer.searchPrinters should return no non-printer devices. If USB printers are not supported by SDK or device, searchPrinters function should return PRINTER_STATUS_ERR_UNSUPPORTED; For example, executing searchPrinters on Android device with connectionType set to CONNECTION_TYPE_USB should return PRINTER_STATUS_ERR_UNSUPPORTED.

                                        • +
                                        + +
                                        \ No newline at end of file diff --git a/docs/en/5.5/api/printing.xml b/docs/en/5.5/api/printing.xml new file mode 100644 index 00000000..a95f65d1 --- /dev/null +++ b/docs/en/5.5/api/printing.xml @@ -0,0 +1,697 @@ + + + + + + +The Printer API module provides access to find, connect, and print over Bluetooth, Wi-Fi and USB from Android and Windows Mobie/CE devices. + + + +This general API does not provide access to manufacturer-specific features such as those found in the [PrintingZebra API](printingzebra). If you wish to have access to general *and* manufacturer-specific features, you must include this general API as as well as the printer-specific extension in your `build.yml` file. + +###Notes + +1. Windows Mobile/CE platforms require the Printing Service application to be running. This is described in the [Printing Guide](../guide/printing#platform-notes). +2. Unless using the printer's 'line mode' (for sending raw text strings), Zebra recommends sending ZPL only. +3. USB printing is supported on Android and Windows Mobile/CE platforms on RMS 5.3 and higher. + +## Enabling the API +To use this API you must include the following extension in your `build.yml`: + + :::ruby + extensions: ["printing"] + +> Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown in the [build-time settings guide](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + +## Enabling the API + +There are two methods of enabling the Printer API: + +* Include all 'ebapi' modules +* Include only the API modules you need + +Both methods are explained below. + +Either way, the included files will be from: +`/Enterprise Browser/JavaScript Files/Enterprise Browser`, +a directory on the computer that contains the Enterprise Browser installation. + +### Include all JS API modules +To include all JavaScript APIs, copy the `ebapi-modules.js` file to a location accessible by your app's files and include the JavaScript modules file in your app. For instance, to include the modules file in your `index.html`, copy the file to the same directory as your index.html and add the following line to the HEAD section of your index.html file: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> This will define the EB class within the page. **Note that the path for this file is relative to the current page** (index.html). Any page on which the modules are required will need to have the required .js file(s) included in this fashion. + +### Include only the modules you need +To include individual APIs, you must first include the `ebapi.js` in your HTML, and then the additional required API file(s). For instance, to use the Printer API, add the following code to the HTML file(s). Again, this assumes that relevant API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.printer.js"></script> + +> In the code lines above, notice that `ebapi.js` is included first, followed by `eb.printer.js`, which is the Printer API for Enterprise Browser. **This coding is required on each HTML page whenever an individual API will be called from that page**. + + + + + + + + + + + + + Printer control language ZPL + + + + Printer control language CPCL + + + + Printer control language EPS. Not Supported in RMS 4.1 + + + + + + Not supported in RMS 4.1 + + + + Not supported in RMS 4.1 + + + Not supported in RMS 4.1 + + + + + Not supported in RMS 4.1 + + + Supported in RMS 5.1, EB 1.3 + + + + + + + + + + + + + + + + + + + Use this name for requestState(), return true if printer ready to print. + + + Use this name for requestState(), return true if cover is opened. + + + Use this name for requestState(), return true if drawer is opened. + + + Use this name for requestState(), return true if paper out. + + + Use this name for requestState(), return true if battery low. + + + + + + General properties for Printer. + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + Unique printer ID during application lifetime. + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + Bluetooth/Network name of printer. + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + Type of printer - see PRINTER_TYPE_... constants. + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **IP address for Wi-Fi connection**, Bluetooth(R) MAC address or device serial number. Note: iOS uses device serial number instead of MAC address. If you need to get device MAC you can use CPCL command ! U1 getvar "bluetooth.address" + IP address for Wi-Fi connection, Bluetooth(R) MAC or device serial number. To get a device MAC, use CPCL command ! U1 getvar "bluetooth.address" + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + Default port when connecting with TCP/IP. + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + Type of connection to printer. + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Connection status flag**. All other properties are valid only if isConnect = true. Note: This property does not guarantee a real connection, because all real device functionality is processed in separate thread asynchronously. If you want a real physical connection, use `requestState()` method with receive result in the callback. This is the only guaranteed method of processing real requests to the device and analyzing answers from the device. + + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Immediately returns an array with supported printer types**. The result depends on your build configuration. Each extension is linked to application during build. To add or remove support for any printer type, update extension list in the `build.yml`. + + Array of currently supported printer types. Depends on build settings. May contain PRINTER_TYPE_ZEBRA, PRINTER_TYPE_EPSON, PRINTER_TYPE_APD, PRINTER_TYPE_NATIVE in any combination. + + Type of device. + + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Searches for printers connected to the device via Bluetooth(R), Wi-Fi or USB**. To reduce search times, it is highly recommended that searches for wireless connections be done by specific MAC address (Bluetooth) or IP address (Wi-Fi). This method also can be used to retrieve the printerID for a known Bluetooth or network printer specifying the `deviceAddress` options parameter. Result is returned asynchronously using a callback called for each discovered printer. Search is finished if printerID is not set in callback hash. Note that discovery is not guaranteed to return all the available devices. It is therefore recommended that this method run 2-3 times for maximum accuracy. + + **NOTE**: On certain Android devices, calling searchPrinters() over Bluetooth or TCP can cause the application to freeze momentarily or to display an alert that "The application has stopped responding." In such cases, it is recommended that the user tap the "Continue waiting" button. + + **Searches for printers connected to the device via Bluetooth(R), Wi-Fi or USB**. To reduce search times, it is highly recommended that searches for wireless connections be done by specific MAC address (Bluetooth) or IP address (Wi-Fi). This method also can be used to retrieve the printerID for a known Bluetooth or network printer specifying the `deviceAddress` options parameter. Result is returned asynchronously using a callback called for each discovered printer. Search is finished if printerID is not set in callback hash. Note that discovery is not guaranteed to return all the available devices. It is therefore recommended that this method run 2-3 times for maximum accuracy. + +**Note**: On certain Android devices, calling searchPrinters() over Bluetooth or TCP can cause the application to freeze momentarily or to display an alert that "The application has stopped responding." In such cases, it is recommended that the user tap the "Continue waiting" button. + + + + Options for discover. + + + + **Printer types to search**. Make sure that Printer type is supported by calling enumerateSupportedTypes method. + + + + Interfaces for search (Bluetooth/TCP/All). + + + + **Maximum search interval in milliseconds, applies to network discovery**. This is the maximum interval for wait during connection attempt. Note that if no printer was found, even with timeout property, status will be set to PRINTER_STATUS_SUCCESS, but without any printerId. + + + + **Printer address (MAC, device serial number or IP address)** can be used for setting either subnet mask or full address of printer. For TCP if address is not specified /8 subnet will be used for search. + + + + Override default printer port number. Applicable for network discovery only. + + + + + + + + + **Status of network discovery**, can be the following: +* PRINTER_STATUS_SUCCESS - when printer is discovered or operation is finished; +* PRINTER_STATUS_ERROR - general error +* PRINTER_STATUS_ERR_UNSUPPORTED - in case if printer type is not supported +* PRINTER_STATUS_ERR_NOT_CONNECTED - in case if deviceAddress was specified in options and device was unable to connect to printer. + + + **Printer ID, valid only if status equals = 'PRINTER_STATUS_SUCCESS'. If no more printers are available, printerID will be undefined. + + + + Error message if status = ERROR**. + + + + + + + + 4.1.0 + Android, iOS + Android + **Immediately stops all active search requests and cancels pending search requests**. Does not return a result. + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Returns printer instance specified by printerId**. Returns null is no printers contains the ID. To get valid printerId, use searchPrinters function. + + + + + + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Connect to a printer using default options**. Works asynchronously; use callback to check the result. If connection is successful printer state and properties are automatically updated. **Note: Default options are defined by printer SDK and platform and may vary between different devices. + + Returns result of a connection attempt to printer. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_TIMEOUT, PRINTER_STATUS_ERROR, PRINTER_STATUS_NOT_FOUND. + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Connect to a printer with user options**. Works asynchronously; use callback to check the result. After this function call, the printer state is automatically updated. + + + Connect options. + + + Connection timeout in milliseconds. Must be larger than 0. + WM, CE, iOS, Android + WM, CE, Android + + + + Any additional info; currently unused. + + + + + + + Returns result of a connection attempt to printer. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_TIMEOUT, PRINTER_STATUS_ERROR, PRINTER_STATUS_NOT_FOUND. + + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Requests printer state with a list of parameters**. Works asynchronously and uses the callback to check the result. Returns hash with status and parameters as keys. **NOTE: On the Windows Mobile / Windows CE platform, this method does not work in the case of a Bluetooth and USB connection. + + + List of parameters for request from printer device. + + Parameter name - see constants with PRINTER_STATE_... + + + + + If the printer does not support a parameter, it will not be included in result hash. + + + PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR. + + + Error message, only if status = ERROR. + + + + Currently unused. + + + + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + Disconnect from a printer and release OS resources. Works asynchronously; use callback to check the result. + + Returns the result of a disconnection. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR. + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Prints file**. Works asynchronously; use callback to check the result. File extension is used to determine its type. Supported image types: JPEG and PNG. + + + Full path to local image file on the device. + + + + Providing no properties to this function will print with default settings. Reserved for future use. + + + Provide a set of properties to configure file printing. + + This is currently not being used. + + + + Currently unused. + + + + + + + **Returns result of a printing attempt**. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR. + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Prints an image from a device's file system to the connected printer as a monochrome image**. Works asynchronously; use callback to check the result. Images larger than 1024x768 might take a long time or print incorrectly. Consult printer documentation for image printing parameters. + + + + Full path to local image file on the device. (The image must be either a PNG or JPG, all other types are platform depend). + + + Horizontal starting position in dots. + + + Vertical starting position in dots. + + + Provide a set of optional parameters. + + + + Desired width of the printed image. Passing -1 will preserve original width. + + + Desired height of the printed image. Passing -1 will preserve original height. + + + Boolean value indicating whether this image should be printed by itself (false), or is part of a format being written to the connection (true). + + + + + + **Returns result of a printing attempt**. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR. + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Send raw string to printer**. Works asynchronously, use callback to check the result. **Note: This method will not print ZPL commands from Windows Mobile/CE devices to Zebra printers; compatible with line mode or raw text only. + + + Raw string to print. Could be any valid command in printer supported programming language. + + + + Providing no properties to this function will print with default settings. + + + Provide a set of properties to configure the printer. + + This is currently not being used. + + + + Currently unused. + + + + + + + + + + PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR. + + + Error message, only if status = ERROR. + + + + Response from printer if received, converted to string from byteArray(original data) + + Android, WM + + + + Response from printer if received. + + Android + + + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + **Returns an array with languages supported by this printer**. + + Array of supported printer control languages. + + Language. See - PRINTER_LANGUAGE_... constants. + + + + + + + + 4.1.0 + WM, CE, Android, iOS + WM, CE, Android + + + +To use a Bluetooth connection on iOS devices, take into account the following preconditions: + +* Zebra printer must have 'Made For iPod/iPhone' certification. +* Before using Bluetooth printer, pair it using the iOS system's Bluetooth settings. +* Your project must include the External Accessory framework (automatically added when iPhone projects are generated). +* Project must include the Zebra printer protocol string "com.zebra.rawport" in the info.plist file ([project root]/project/iphone/Info.plist) under "Supported external accessory protocols": + <key>UISupportedExternalAccessoryProtocols</key> + <array> + <string>com.zebra.rawport</string> + </array> +* You must set the key 'Required Background modes' to 'App Communicates with an accessory' in your app's plist file. + <key>UIBackgroundModes</key> + <array> + <string>external-accessory</string> + </array> + + + + +* When calling searchPrinters() with Bluetooth search (CONNECTION_TYPE_ANY or CONNECTION_TYPE_BLUETOOTH), all local Bluetooth devices--including non-printers--will be discovered and send pairing requests. Just cancel or ignore them. This happens because the software cannot detect non-printers until after the device is paired. It is recommended that the BT or Wi-Fi MAC address also be used when searching for printers. + +* When calling searchPrinters() with USB search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_USB), all USB Printers connected to the device will be discovered. If USB printers are not supported by SDK or device, searchPrinters function should return PRINTER_STATUS_ERR_UNSUPPORTED. + + + + + +* Requires a Printing Service application to be running. This is described in the [Printing Guide](../guide/printing#platform-notes). + +* You should avoid navigating from the current page using the printer without disconnecting from the printer first. You can use the window.onunload event: + + :::javascript + window.onunload = function(){ + printer.disconnect(); + } + +* When calling searchPrinters() with Bluetooth search (CONNECTION_TYPE_ANY or CONNECTION_TYPE_BLUETOOTH), all local Bluetooth devices--including non-printers--will be discovered and send pairing requests. Just cancel or ignore them. This happens because the software cannot detect non-printers until after the device is paired. It is recommended that the BT or Wi-Fi MAC address also be used when searching for printers. + +* Before calling searchPrinters() with USB search (CONNECTION_TYPE_ANY or CONNECTION_TYPE_USB), you should configure the device's USB controller for "USB Host mode" and reboot. + +* When calling searchPrinters() with USB search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_USB), all USB Printers connected to the device will be discovered. If USB printers are not supported by SDK or device, searchPrinters function should return PRINTER_STATUS_ERR_UNSUPPORTED. + +* USB connection is not supported on QLn320; `printer.searchPrinters` should return no non-printer devices. If USB printers are not supported by SDK or device, searchPrinters function should return PRINTER_STATUS_ERR_UNSUPPORTED; For example, executing searchPrinters on Android device with connectionType set to CONNECTION_TYPE_USB should return PRINTER_STATUS_ERR_UNSUPPORTED. + + + + + + + +
                                        + To print to the Zebra printer, your app must first search for the device. In this example we are using the searchPrinters method and passing in options to limit the search to Bluetooth and also look for Zebra printers only. If we knew the printer Bluetooth address we could have added the 'deviceAddress' parameter. The callback function will be executed for each printer found. When a printer is found the callback object will contain a 'printerID' property. This ID is an internal RhoMobie ID used. If no printerID property is there for the successful callback object, then it means that the search has finished. + + + + Rho::Printer::CONNECTION_TYPE_BLUETOOTH, + printerType => Rho::Printer::PRINTER_TYPE_ZEBRA }, + url_for(:action => :printer_callback) ) + +def find_printer_callback + if @params['status'] == 'PRINTER_STATUS_SUCCESS' + if defined? @params['printerID'] + puts "Found: #{@params['printerID']}" + @printers.push @params['printerID'] + else + puts "Done Searching" + end + else + puts @params['status'] + end +end +]]> + + +
                                        +
                                        + Now that we have found a printer. The `printers` array will contain the `printerID` we need to create an instance object that we will use for all communications. Upon first connection to the printer via Bluetooth, you may see a prompt to enter the Bluetooth PIN. Check the manufacturers guide for details. Normally the default is '0000' or '1111' or '1234'. Once it is connected, you should see some indication in the printer (like a blue light). + + + + :printer_connect_callback) + +def printer_connect_callback + puts @params.to_s + + # This will be the Zebra's `Friendly Name` + # by default it is the serial number + puts @my_printer['deviceName'] + + # This will be the BT MAC Address + # since we are connecting via BlueTooth + puts @my_printer['deviceAddress'] +end +]]> + + +
                                        +
                                        + Now we can just print a test string and read some properties of the printer to make sure the communications is working. + + + + :request_state_callback)); + +def request_state_callback + puts @params['status'] + puts @params['PRINTER_STATE_IS_PAPER_OUT'] + puts @params['PRINTER_STATE_IS_READY_TO_PRINT'] +end +]]> + + +
                                        +
                                        +
                                        +
                                        +
                                        +
                                        diff --git a/docs/en/5.5/api/printingepson.md b/docs/en/5.5/api/printingepson.md new file mode 100644 index 00000000..5a0ae89a --- /dev/null +++ b/docs/en/5.5/api/printingepson.md @@ -0,0 +1,36 @@ +#PrintingEpson +
                                        +

                                        The PrinterEpson API provides Epson specific API access Epson Bluetooth and WiFi Network printers. This API inherits all methods,properties,constants from the Printer API

                                        +

                                        This is example of API. Implementation contain in extension.

                                        + + + +

                                        Methods

                                        + +

                                        calcSumm(INTEGER a, INTEGER b)

                                        Return sum of two params: a+b.

                                        +

                                        Parameters

                                        • a : INTEGER

                                        • b : INTEGER

                                        Synchronous Return:

                                        • INTEGER

                                        Method Access:

                                        • Instance Method: This method can be accessed via an instance object of this class:
                                          • myObject.calcSumm(INTEGER a, INTEGER b)
                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.PrintingEpson.calcSumm(INTEGER a, INTEGER b)
                                          • Ruby: Rho::PrintingEpson.calcSumm(INTEGER a, INTEGER b)

                                        getAllProperties(CallBackHandler callback)

                                        This method will return all of object/value pairs for the propertyNames of the API class.

                                        +

                                        Parameters

                                        • callback : CallBackHandler Optional

                                        Async Callback Returning Parameters: HASH

                                          • : STRING

                                        Synchronous Return:

                                        • HASH :

                                          Map of all available properties

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

                                        Method Access:

                                        • Instance Method: This method can be accessed via an instance object of this class:
                                          • myObject.getAllProperties(CallBackHandler callback)
                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.PrintingEpson.getAllProperties(CallBackHandler callback)
                                          • Ruby: Rho::PrintingEpson.getAllProperties(CallBackHandler callback)

                                        getDefault()

                                        This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

                                        +

                                        Synchronous Return:

                                        • SELF_INSTANCE :

                                          Default object of Module.

                                          +

                                        Method Access:

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

                                        getPlatformName()

                                        Return string with platform.

                                        +

                                        Synchronous Return:

                                        • STRING

                                        Method Access:

                                        • Instance Method: This method can be accessed via an instance object of this class:
                                          • myObject.getPlatformName()
                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.PrintingEpson.getPlatformName()
                                          • Ruby: Rho::PrintingEpson.getPlatformName()

                                        getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                        This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                                        +

                                        Parameters

                                        • arrayofNames : ARRAY

                                          List of properties I want to know about

                                          +

                                          • Object : STRING

                                        • callback : CallBackHandler Optional

                                        Async Callback Returning Parameters: HASH

                                          • : STRING

                                        Synchronous Return:

                                        • HASH :

                                          Map of properties I want to know about

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

                                        Method Access:

                                        • Instance Method: This method can be accessed via an instance object of this class:
                                          • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                          • JavaScript: Rho.PrintingEpson.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                          • Ruby: Rho::PrintingEpson.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                        getProperty(STRING propertyName, CallBackHandler callback)

                                        This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                                        +

                                        Parameters

                                        • propertyName : STRING

                                          The property to return info about.

                                          +

                                        • callback : CallBackHandler Optional

                                        Async Callback Returning Parameters: STRING

                                          Synchronous Return:

                                          • STRING :

                                            The property to return info about.

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

                                          Method Access:

                                          • Instance Method: This method can be accessed via an instance object of this class:
                                            • myObject.getProperty(STRING propertyName, CallBackHandler callback)
                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                            • JavaScript: Rho.PrintingEpson.getProperty(STRING propertyName, CallBackHandler callback)
                                            • Ruby: Rho::PrintingEpson.getProperty(STRING propertyName, CallBackHandler callback)

                                          joinStrings(STRING a, STRING b)

                                          Return join of two strings: a+b.

                                          +

                                          Parameters

                                          • a : STRING

                                          • b : STRING

                                          Synchronous Return:

                                          • STRING

                                          Method Access:

                                          • Instance Method: This method can be accessed via an instance object of this class:
                                            • myObject.joinStrings(STRING a, STRING b)
                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                            • JavaScript: Rho.PrintingEpson.joinStrings(STRING a, STRING b)
                                            • Ruby: Rho::PrintingEpson.joinStrings(STRING a, STRING b)

                                          setDefault(SELF_INSTANCE: Rho::PrintingEpson defaultInstance)

                                          This method allows you to set the attributes of the default object instance by passing in an object of the same class.

                                          +

                                          Parameters

                                          • defaultInstance : SELF_INSTANCE: Rho::PrintingEpson

                                            An instance object that is of the same class.

                                            +

                                          Synchronous Return:

                                          • Void

                                          Method Access:

                                          • Class Method: This method can only be accessed via the API class object.
                                            • JavaScript: Rho.PrintingEpson.setDefault(SELF_INSTANCE: Rho::PrintingEpson defaultInstance)
                                            • Ruby: Rho::PrintingEpson.setDefault(SELF_INSTANCE: Rho::PrintingEpson defaultInstance)

                                          setProperties(HASH propertyMap)

                                          This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                          +

                                          Parameters

                                          • propertyMap : HASH

                                            Map of properties I want to set

                                            +

                                            • Object : STRING

                                          Synchronous Return:

                                          • Void

                                          Method Access:

                                          • Instance Method: This method can be accessed via an instance object of this class:
                                            • myObject.setProperties(HASH propertyMap)
                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                            • JavaScript: Rho.PrintingEpson.setProperties(HASH propertyMap)
                                            • Ruby: Rho::PrintingEpson.setProperties(HASH propertyMap)

                                          setProperty(STRING propertyName, STRING propertyValue)

                                          This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                          +

                                          Parameters

                                          • propertyName : STRING

                                            The one property name that I want to set

                                            +

                                          • propertyValue : STRING

                                            The one property value that I want to set

                                            +

                                          Synchronous Return:

                                          • Void

                                          Method Access:

                                          • Instance Method: This method can be accessed via an instance object of this class:
                                            • myObject.setProperty(STRING propertyName, STRING propertyValue)
                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                            • JavaScript: Rho.PrintingEpson.setProperty(STRING propertyName, STRING propertyValue)
                                            • Ruby: Rho::PrintingEpson.setProperty(STRING propertyName, STRING propertyValue)
                                          + +

                                          Properties

                                          + +

                                          simpleStringProperty : STRING

                                          Simple string property.

                                          +

                                          Property Access:

                                          • Instance: This property can be accessed via an instance object of this class:
                                            • myObject.simpleStringProperty
                                          • Default Instance: This property can be accessed via the default instance object of this class.
                                            • JavaScript: Rho.PrintingEpson.simpleStringProperty
                                            • Ruby: Rho::PrintingEpson.simpleStringProperty
                                          \ No newline at end of file diff --git a/docs/en/5.5/api/printingepson.xml b/docs/en/5.5/api/printingepson.xml new file mode 100644 index 00000000..9a782857 --- /dev/null +++ b/docs/en/5.5/api/printingepson.xml @@ -0,0 +1,92 @@ + + + + + The PrinterEpson API provides Epson specific API access Epson Bluetooth and WiFi Network printers. This API inherits all methods,properties,constants from the [Printer API](printing) + This is example of API. Implementation contain in extension. + +## Enabling the API +There are two methods of enabling the PrintingEpson API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the PrintingEpson API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.printer.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.printerepson.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + List of properties supported by instance of object. + + Simple string property. + + + + + + + Array of PrintingEpson objects. + + + + + + Return string with platform. + + + + + Return sum of two params: a+b. + + + + + + + + + + + Return join of two strings: a+b. + + + + + + + + + + + + + + 1.0.0 + + + + \ No newline at end of file diff --git a/docs/en/5.5/api/printingzebra.md b/docs/en/5.5/api/printingzebra.md new file mode 100644 index 00000000..86abd5e6 --- /dev/null +++ b/docs/en/5.5/api/printingzebra.md @@ -0,0 +1,373 @@ +#PrinterZebra +
                                          Constants 71
                                          +

                                          The PrinterZebra API provides Zebra-specific API access to Zebra’s Bluetooth and Wi-Fi network printers, and to USB-capable printers for Android and Windows Mobile/CE. This API inherits all methods, properties and constants from the Printer API.

                                          +

                                          Notes

                                          + +
                                            +
                                          1. Unless using the printer’s ‘line mode’ (for sending raw text strings), Zebra recommends sending ZPL only.
                                          2. +
                                          3. USB printing is supported for Android and Windows Mobile/CE.
                                          4. +
                                          + + +

                                          Enabling the API

                                          + +

                                          To use this API you must include the following extensions in your build.yml:

                                          + +
                                          :::ruby
                                          +extensions: ["printing","printing_zebra"]
                                          +
                                          + +

                                          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

                                          + +

                                          connect(CallBackHandler callback)

                                          Connect to a printer using default options. Works asynchronously; use callback to check the result. If connection is successful printer state and properties are automatically updated. **Note: Default options are defined by printer SDK and platform and may vary between different devices.

                                          +

                                          Parameters

                                          • callback : CallBackHandler Optional

                                          Async Callback Returning Parameters: STRING

                                            Synchronous Return:

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

                                            Method Access:

                                            • Instance Method: This method can be accessed via an instance object of this class:
                                              • myObject.connect(CallBackHandler callback)
                                            • Default Instance: This method can be accessed via the default instance object of this class.
                                              • JavaScript: Rho.PrinterZebra.connect(CallBackHandler callback)
                                              • Ruby: Rho::PrinterZebra.connect(CallBackHandler callback)

                                            connectWithOptions(HASH options, CallBackHandler callback)

                                            Connect to a printer with user options. Works asynchronously; use callback to check the result. After this function call, the printer state is automatically updated.

                                            +

                                            Parameters

                                            • options : HASH

                                              Connect options.

                                              +

                                              • timeout : INTEGER Optional Default: 15000

                                                Connection timeout in milliseconds. Must be larger than 0.

                                                + Platforms:WM, CE, iOS, Android

                                              • additionalStringOption : STRING Optional

                                                Any additional info; currently unused.

                                                +

                                            • callback : CallBackHandler Optional

                                            Async Callback Returning Parameters: STRING

                                              Synchronous Return:

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

                                              Method Access:

                                              • Instance Method: This method can be accessed via an instance object of this class:
                                                • myObject.connectWithOptions(HASH options, CallBackHandler callback)
                                              • Default Instance: This method can be accessed via the default instance object of this class.
                                                • JavaScript: Rho.PrinterZebra.connectWithOptions(HASH options, CallBackHandler callback)
                                                • Ruby: Rho::PrinterZebra.connectWithOptions(HASH options, CallBackHandler callback)

                                              disconnect(CallBackHandler callback)

                                              Disconnect from a printer and release OS resources. Works asynchronously; use callback to check the result.

                                              +

                                              Parameters

                                              • callback : CallBackHandler Optional

                                              Async Callback Returning Parameters: STRING

                                                Synchronous Return:

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

                                                Method Access:

                                                • Instance Method: This method can be accessed via an instance object of this class:
                                                  • myObject.disconnect(CallBackHandler callback)
                                                • Default Instance: This method can be accessed via the default instance object of this class.
                                                  • JavaScript: Rho.PrinterZebra.disconnect(CallBackHandler callback)
                                                  • Ruby: Rho::PrinterZebra.disconnect(CallBackHandler callback)

                                                getAllProperties(CallBackHandler callback)

                                                This method will return all of object/value pairs for the propertyNames of the API class.

                                                +

                                                Parameters

                                                • callback : CallBackHandler Optional

                                                Async Callback Returning Parameters: HASH

                                                  • : STRING

                                                Synchronous Return:

                                                • HASH :

                                                  Map of all available properties

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

                                                Method Access:

                                                • Instance Method: This method can be accessed via an instance object of this class:
                                                  • myObject.getAllProperties(CallBackHandler callback)
                                                • Default Instance: This method can be accessed via the default instance object of this class.
                                                  • JavaScript: Rho.PrinterZebra.getAllProperties(CallBackHandler callback)
                                                  • Ruby: Rho::PrinterZebra.getAllProperties(CallBackHandler callback)

                                                getDefault()

                                                This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

                                                +

                                                Synchronous Return:

                                                • SELF_INSTANCE :

                                                  Default object of Module.

                                                  +

                                                Method Access:

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

                                                getPrinterByID(STRING printerId)

                                                Returns printer instance specified by printerId. Returns null is no printers contains the ID. To get valid printerId, use searchPrinters function.

                                                +

                                                Parameters

                                                • printerId : STRING

                                                Synchronous Return:

                                                • SELF_INSTANCE

                                                Method Access:

                                                • Class Method: This method can only be accessed via the API class object.
                                                  • JavaScript: Rho.PrinterZebra.getPrinterByID(STRING printerId)
                                                  • Ruby: Rho::PrinterZebra.getPrinterByID(STRING printerId)

                                                getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                                                +

                                                Parameters

                                                • arrayofNames : ARRAY

                                                  List of properties I want to know about

                                                  +

                                                  • Object : STRING

                                                • callback : CallBackHandler Optional

                                                Async Callback Returning Parameters: HASH

                                                  • : STRING

                                                Synchronous Return:

                                                • HASH :

                                                  Map of properties I want to know about

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

                                                Method Access:

                                                • Instance Method: This method can be accessed via an instance object of this class:
                                                  • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                                • Default Instance: This method can be accessed via the default instance object of this class.
                                                  • JavaScript: Rho.PrinterZebra.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                                  • Ruby: Rho::PrinterZebra.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                getProperty(STRING propertyName, CallBackHandler callback)

                                                This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                                                +

                                                Parameters

                                                • propertyName : STRING

                                                  The property to return info about.

                                                  +

                                                • callback : CallBackHandler Optional

                                                Async Callback Returning Parameters: STRING

                                                  Synchronous Return:

                                                  • STRING :

                                                    The property to return info about.

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

                                                  Method Access:

                                                  • Instance Method: This method can be accessed via an instance object of this class:
                                                    • myObject.getProperty(STRING propertyName, CallBackHandler callback)
                                                  • Default Instance: This method can be accessed via the default instance object of this class.
                                                    • JavaScript: Rho.PrinterZebra.getProperty(STRING propertyName, CallBackHandler callback)
                                                    • Ruby: Rho::PrinterZebra.getProperty(STRING propertyName, CallBackHandler callback)

                                                  printFile(STRING filePathOnDevice, HASH options, CallBackHandler callback)

                                                  Prints file. Works asynchronously; use callback to check the result. File extension is used to determine its type. Supported image types: JPEG and PNG.

                                                  +

                                                  Parameters

                                                  • filePathOnDevice : STRING

                                                    Full path to local image file on the device.

                                                    +

                                                  • options : HASH Optional

                                                    Providing no properties to this function will print with default settings. Reserved for future use.

                                                    +

                                                    • propertyWithStringValue : STRING Optional

                                                      This is currently not being used.

                                                      +

                                                    • propertyWithIntValue : INTEGER Optional

                                                      Currently unused.

                                                      +

                                                  • callback : CallBackHandler Optional

                                                  Async Callback Returning Parameters: STRING

                                                    Synchronous Return:

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

                                                    Method Access:

                                                    • Instance Method: This method can be accessed via an instance object of this class:
                                                      • myObject.printFile(STRING filePathOnDevice, HASH options, CallBackHandler callback)
                                                    • Default Instance: This method can be accessed via the default instance object of this class.
                                                      • JavaScript: Rho.PrinterZebra.printFile(STRING filePathOnDevice, HASH options, CallBackHandler callback)
                                                      • Ruby: Rho::PrinterZebra.printFile(STRING filePathOnDevice, HASH options, CallBackHandler callback)

                                                    printImageFromFile(STRING filePathOnDevice, INTEGER x, INTEGER y, HASH options, CallBackHandler callback)

                                                    Prints an image from a device’s file system to the connected printer as a monochrome image. Works asynchronously; use callback to check the result. Images larger than 1024x768 might take a long time or print incorrectly. Consult printer documentation for image printing parameters.

                                                    +

                                                    Parameters

                                                    • filePathOnDevice : STRING

                                                      Full path to local image file on the device. (The image must be either a PNG or JPG, all other types are platform depend).

                                                      +

                                                    • x : INTEGER

                                                      Horizontal starting position in dots.

                                                      +

                                                    • y : INTEGER

                                                      Vertical starting position in dots.

                                                      +

                                                    • options : HASH Optional

                                                      Provide a set of optional parameters.

                                                      +

                                                      • width : INTEGER

                                                        Desired width of the printed image. Passing -1 will preserve original width.

                                                        +

                                                      • height : INTEGER

                                                        Desired height of the printed image. Passing -1 will preserve original height.

                                                        +

                                                      • isInsideFormat : BOOLEAN

                                                        Boolean value indicating whether this image should be printed by itself (false), or is part of a format being written to the connection (true).

                                                        +

                                                    • callback : CallBackHandler Optional

                                                    Async Callback Returning Parameters: STRING

                                                      Synchronous Return:

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

                                                      Method Access:

                                                      • Instance Method: This method can be accessed via an instance object of this class:
                                                        • myObject.printImageFromFile(STRING filePathOnDevice, INTEGER x, INTEGER y, HASH options, CallBackHandler callback)
                                                      • Default Instance: This method can be accessed via the default instance object of this class.
                                                        • JavaScript: Rho.PrinterZebra.printImageFromFile(STRING filePathOnDevice, INTEGER x, INTEGER y, HASH options, CallBackHandler callback)
                                                        • Ruby: Rho::PrinterZebra.printImageFromFile(STRING filePathOnDevice, INTEGER x, INTEGER y, HASH options, CallBackHandler callback)

                                                      printRawString(STRING command, HASH options, CallBackHandler callback)

                                                      Send raw string to printer. Works asynchronously, use callback to check the result. **Note: This method will not print ZPL commands from Windows Mobile/CE devices to Zebra printers; compatible with line mode or raw text only.

                                                      +

                                                      Parameters

                                                      • command : STRING

                                                        Raw string to print. Could be any valid command in printer supported programming language.

                                                        +

                                                      • options : HASH Optional

                                                        Providing no properties to this function will print with default settings.

                                                        +

                                                        • propertyWithStringValue : STRING Optional

                                                          This is currently not being used.

                                                          +

                                                        • propertyWithIntValue : INTEGER Optional

                                                          Currently unused.

                                                          +

                                                      • callback : CallBackHandler Optional

                                                      Async Callback Returning Parameters: HASH

                                                        • status : STRING

                                                          PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR.

                                                          +

                                                        • message : STRING Optional

                                                          Error message, only if status = ERROR.

                                                          +

                                                        • stringResponce : STRING Optional

                                                          Response from printer if received, converted to string from byteArray(original data)

                                                          + Platforms:Android, WM

                                                        • byteArrayResponce : ARRAY Optional

                                                          Response from printer if received.

                                                          + Platforms:Android

                                                          • Object : INTEGER

                                                      Synchronous Return:

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

                                                      Method Access:

                                                      • Instance Method: This method can be accessed via an instance object of this class:
                                                        • myObject.printRawString(STRING command, HASH options, CallBackHandler callback)
                                                      • Default Instance: This method can be accessed via the default instance object of this class.
                                                        • JavaScript: Rho.PrinterZebra.printRawString(STRING command, HASH options, CallBackHandler callback)
                                                        • Ruby: Rho::PrinterZebra.printRawString(STRING command, HASH options, CallBackHandler callback)

                                                      printStoredFormatWithArray(STRING formatPathOnPrinter, Array vars, CallBackHandler callback)

                                                      Prints a stored format on the printer, filling in the fields specified by the array. Works asynchronously; use callback to check the result.

                                                      +

                                                      Parameters

                                                      • formatPathOnPrinter : STRING

                                                        The location of the file on the printer (e.g. “E:FORMAT.ZPL”).

                                                        +

                                                      • vars : Array

                                                        An array of strings representing the data to fill into the format. For ZPL formats, index 0 of the array corresponds to field number 2 (FN2). For CPCL, the variables are passed in the order that they are found in the format

                                                        +

                                                      • callback : CallBackHandler Optional

                                                      Async Callback Returning Parameters: STRING

                                                        Synchronous Return:

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

                                                        Method Access:

                                                        • Instance Method: This method can be accessed via an instance object of this class:
                                                          • myObject.printStoredFormatWithArray(STRING formatPathOnPrinter, Array vars, CallBackHandler callback)
                                                        • Default Instance: This method can be accessed via the default instance object of this class.
                                                          • JavaScript: Rho.PrinterZebra.printStoredFormatWithArray(STRING formatPathOnPrinter, Array vars, CallBackHandler callback)
                                                          • Ruby: Rho::PrinterZebra.printStoredFormatWithArray(STRING formatPathOnPrinter, Array vars, CallBackHandler callback)

                                                        printStoredFormatWithHash(STRING formatPathOnPrinter, HASH vars, CallBackHandler callback)

                                                        Prints a stored format on the printer, filling in the fields specified by the Hash. Works asynchronously; use callback to check the result.

                                                        +

                                                        Parameters

                                                        • formatPathOnPrinter : STRING

                                                          The location of the file on the printer (e.g. “E:FORMAT.ZPL”).

                                                          +

                                                        • vars : HASH

                                                          A Hash containing the key / value pairs for the stored format. For ZPL formats, the key number should correspond directly to the number of the field in the format. Number keys should be passed as Strings, i.e. ‘1’:‘field1’ etc. Only ZPL format is supported; CPCL format is not supported.

                                                          +

                                                        • callback : CallBackHandler Optional

                                                        Async Callback Returning Parameters: STRING

                                                          Synchronous Return:

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

                                                          Method Access:

                                                          • Instance Method: This method can be accessed via an instance object of this class:
                                                            • myObject.printStoredFormatWithHash(STRING formatPathOnPrinter, HASH vars, CallBackHandler callback)
                                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                                            • JavaScript: Rho.PrinterZebra.printStoredFormatWithHash(STRING formatPathOnPrinter, HASH vars, CallBackHandler callback)
                                                            • Ruby: Rho::PrinterZebra.printStoredFormatWithHash(STRING formatPathOnPrinter, HASH vars, CallBackHandler callback)

                                                          requestState(ARRAY listOfParameters, CallBackHandler callback)

                                                          Requests printer state with a list of parameters. Works asynchronously and uses the callback to check the result. Returns hash with status and parameters as keys. **NOTE: On the Windows Mobile / Windows CE platform, this method does not work in the case of a Bluetooth and USB connection.

                                                          +

                                                          Parameters

                                                          • listOfParameters : ARRAY

                                                            List of parameters for request from printer device.

                                                            +

                                                            • Object : STRING

                                                              Parameter name – see constants with PRINTER_STATE_…

                                                              +

                                                          • callback : CallBackHandler Mandatory

                                                          Async Callback Returning Parameters: HASH

                                                            • status : STRING

                                                              PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR.

                                                              +

                                                            • message : STRING Optional

                                                              Error message, only if status = ERROR.

                                                              +

                                                            • propertyWithIntValue : INTEGER Optional

                                                              Currently unused.

                                                              +

                                                          Synchronous Return:

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

                                                          Method Access:

                                                          • Instance Method: This method can be accessed via an instance object of this class:
                                                            • myObject.requestState(ARRAY listOfParameters, CallBackHandler callback)
                                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                                            • JavaScript: Rho.PrinterZebra.requestState(ARRAY listOfParameters, CallBackHandler callback)
                                                            • Ruby: Rho::PrinterZebra.requestState(ARRAY listOfParameters, CallBackHandler callback)

                                                          retrieveFileNames(CallBackHandler callback)

                                                          Retrieves the names of the files which are stored on the printer. Works asynchronously; use callback to check the result.

                                                          +

                                                          Parameters

                                                          • callback : CallBackHandler Mandatory

                                                          Async Callback Returning Parameters: HASH

                                                            • status : STRING

                                                              PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR

                                                              +

                                                            • fileNames : ARRAY

                                                              • Object : STRING

                                                          Synchronous Return:

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

                                                          Method Access:

                                                          • Instance Method: This method can be accessed via an instance object of this class:
                                                            • myObject.retrieveFileNames(CallBackHandler callback)
                                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                                            • JavaScript: Rho.PrinterZebra.retrieveFileNames(CallBackHandler callback)
                                                            • Ruby: Rho::PrinterZebra.retrieveFileNames(CallBackHandler callback)

                                                          retrieveFileNamesWithExtensions(ARRAY extensions, CallBackHandler callback)

                                                          This method only returns files which have the extensions in “extensions”. Works asynchronously; use callback to check the result.

                                                          +

                                                          Parameters

                                                          • extensions : ARRAY

                                                            The list of extensions that should be returned.

                                                            +

                                                            • Object : STRING

                                                          • callback : CallBackHandler Mandatory

                                                          Async Callback Returning Parameters: HASH

                                                            • status : STRING

                                                              PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR

                                                              +

                                                            • fileNames : ARRAY

                                                              • Object : STRING

                                                          Synchronous Return:

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

                                                          Method Access:

                                                          • Instance Method: This method can be accessed via an instance object of this class:
                                                            • myObject.retrieveFileNamesWithExtensions(ARRAY extensions, CallBackHandler callback)
                                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                                            • JavaScript: Rho.PrinterZebra.retrieveFileNamesWithExtensions(ARRAY extensions, CallBackHandler callback)
                                                            • Ruby: Rho::PrinterZebra.retrieveFileNamesWithExtensions(ARRAY extensions, CallBackHandler callback)

                                                          searchPrinters(HASH options, CallBackHandler callback)

                                                          Searches for printers connected to the device via Bluetooth®, Wi-Fi or USB. To reduce search times, it is highly recommended that searches for wireless connections be done by specific MAC address (Bluetooth) or IP address (Wi-Fi). This method also can be used to retrieve the printerID for a known Bluetooth or network printer specifying the deviceAddress options parameter. Result is returned asynchronously using a callback called for each discovered printer. Search is finished if printerID is not set in callback hash. Note that discovery is not guaranteed to return all the available devices. It is therefore recommended that this method run 2-3 times for maximum accuracy.

                                                          + +
                                                                          **NOTE**: On certain Android devices, calling searchPrinters() over Bluetooth or TCP can cause the application to freeze momentarily or to display an alert that "The application has stopped responding." In such cases, it is recommended that the user tap the "Continue waiting" button. 
                                                          +
                                                          +

                                                          Parameters

                                                          • options : HASH Optional

                                                            Options for discover.

                                                            +

                                                            • printerType : STRING Optional Default: PRINTER_TYPE_ANY

                                                              Printer types to search. Make sure that Printer type is supported by calling enumerateSupportedTypes method.

                                                              +

                                                            • connectionType : STRING Optional Default: CONNECTION_TYPE_ANY

                                                              Interfaces for search (Bluetooth/TCP/All).

                                                              +

                                                            • timeout : INTEGER Optional Default: 30000

                                                              Maximum search interval in milliseconds, applies to network discovery. This is the maximum interval for wait during connection attempt. Note that if no printer was found, even with timeout property, status will be set to PRINTER_STATUS_SUCCESS, but without any printerId.

                                                              +

                                                            • deviceAddress : STRING Optional

                                                              Printer address (MAC, device serial number or IP address) can be used for setting either subnet mask or full address of printer. For TCP if address is not specified /8 subnet will be used for search.

                                                              +

                                                            • devicePort : INTEGER Optional Default: 6101

                                                              Override default printer port number. Applicable for network discovery only.

                                                              +

                                                          • callback : CallBackHandler Mandatory

                                                          Async Callback Returning Parameters: HASH

                                                            • status : STRING

                                                              Status of network discovery, can be the following: +* PRINTER_STATUS_SUCCESS – when printer is discovered or operation is finished; +* PRINTER_STATUS_ERROR – general error +* PRINTER_STATUS_ERR_UNSUPPORTED – in case if printer type is not supported +* PRINTER_STATUS_ERR_NOT_CONNECTED – in case if deviceAddress was specified in options and device was unable to connect to printer.

                                                              +

                                                            • printerID : STRING Optional

                                                              **Printer ID, valid only if status equals = ‘PRINTER_STATUS_SUCCESS’. If no more printers are available, printerID will be undefined.

                                                              +

                                                            • message : STRING Optional

                                                              Error message if status = ERROR**.

                                                              +

                                                          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.PrinterZebra.searchPrinters(HASH options, CallBackHandler callback)
                                                            • Ruby: Rho::PrinterZebra.searchPrinters(HASH options, CallBackHandler callback)

                                                          sendFileContents(STRING path, CallBackHandler callback)

                                                          Sends the contents of a file on the device to the printer. Equals to printing raw string with content of specified file. Should be used to print ZPL and CPCL commands stored inside predefined filed. Works asynchronously; use callback to check the result.

                                                          +

                                                          Parameters

                                                          • path : STRING

                                                            Location of file to print. This path must be fully qualified path to local file on the device.

                                                            +

                                                          • callback : CallBackHandler Optional

                                                          Async Callback Returning Parameters: STRING

                                                            Synchronous Return:

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

                                                            Method Access:

                                                            • Instance Method: This method can be accessed via an instance object of this class:
                                                              • myObject.sendFileContents(STRING path, CallBackHandler callback)
                                                            • Default Instance: This method can be accessed via the default instance object of this class.
                                                              • JavaScript: Rho.PrinterZebra.sendFileContents(STRING path, CallBackHandler callback)
                                                              • Ruby: Rho::PrinterZebra.sendFileContents(STRING path, CallBackHandler callback)

                                                            setDefault(SELF_INSTANCE: Rho::PrinterZebra defaultInstance)

                                                            This method allows you to set the attributes of the default object instance by passing in an object of the same class.

                                                            +

                                                            Parameters

                                                            • defaultInstance : SELF_INSTANCE: Rho::PrinterZebra

                                                              An instance object that is of the same class.

                                                              +

                                                            Synchronous Return:

                                                            • Void

                                                            Method Access:

                                                            • Class Method: This method can only be accessed via the API class object.
                                                              • JavaScript: Rho.PrinterZebra.setDefault(SELF_INSTANCE: Rho::PrinterZebra defaultInstance)
                                                              • Ruby: Rho::PrinterZebra.setDefault(SELF_INSTANCE: Rho::PrinterZebra defaultInstance)

                                                            setProperties(HASH propertyMap)

                                                            This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                            +

                                                            Parameters

                                                            • propertyMap : HASH

                                                              Map of properties I want to set

                                                              +

                                                              • Object : STRING

                                                            Synchronous Return:

                                                            • Void

                                                            Method Access:

                                                            • Instance Method: This method can be accessed via an instance object of this class:
                                                              • myObject.setProperties(HASH propertyMap)
                                                            • Default Instance: This method can be accessed via the default instance object of this class.
                                                              • JavaScript: Rho.PrinterZebra.setProperties(HASH propertyMap)
                                                              • Ruby: Rho::PrinterZebra.setProperties(HASH propertyMap)

                                                            setProperty(STRING propertyName, STRING propertyValue)

                                                            This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                            +

                                                            Parameters

                                                            • propertyName : STRING

                                                              The one property name that I want to set

                                                              +

                                                            • propertyValue : STRING

                                                              The one property value that I want to set

                                                              +

                                                            Synchronous Return:

                                                            • Void

                                                            Method Access:

                                                            • Instance Method: This method can be accessed via an instance object of this class:
                                                              • myObject.setProperty(STRING propertyName, STRING propertyValue)
                                                            • Default Instance: This method can be accessed via the default instance object of this class.
                                                              • JavaScript: Rho.PrinterZebra.setProperty(STRING propertyName, STRING propertyValue)
                                                              • Ruby: Rho::PrinterZebra.setProperty(STRING propertyName, STRING propertyValue)

                                                            stopSearch()

                                                            Immediately stops all active search requests and cancels pending search requests. Does not return a result.

                                                            +

                                                            Synchronous Return:

                                                            • Void

                                                            Method Access:

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

                                                            storeImage(STRING printerDriveAndFileName, STRING imageFilePathOnDevice, INTEGER width, INTEGER height, CallBackHandler callback)

                                                            Stores the specified image to the connected printer as a monochrome image. Works asynchronously; use callback to check the result. The image will be stored on the printer at printerDriveAndFileName with the extension GRF. If a drive letter is not supplied, E will be used as the default (e.g. FILE becomes E:FILE.GRF). If an extension is supplied, it is ignored (E:FILE.BMP becomes E:FILE.GRF). Note that if the image resolution is large (e.g. 1024x768) this method may take a long time to execute. There are device OS limitations on supported file formats and image sizes. iOS, Android and WM are supporting only JPG and PNG files. WM can fail to handle large (>1024x1024 pixel) images.

                                                            +

                                                            Parameters

                                                            • printerDriveAndFileName : STRING

                                                              Path on the printer where the image will be stored.

                                                              +

                                                            • imageFilePathOnDevice : STRING

                                                              Path to the local image file containing the bitmap image to send.

                                                              +

                                                            • width : INTEGER

                                                              Desired width of the printed image, in dots. Passing -1 will preserve original width.

                                                              +

                                                            • height : INTEGER

                                                              Desired height of the printed image, in dots. Passing -1 will preserve original height.

                                                              +

                                                            • callback : CallBackHandler Optional

                                                            Async Callback Returning Parameters: STRING

                                                              Synchronous Return:

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

                                                              Method Access:

                                                              • Instance Method: This method can be accessed via an instance object of this class:
                                                                • myObject.storeImage(STRING printerDriveAndFileName, STRING imageFilePathOnDevice, INTEGER width, INTEGER height, CallBackHandler callback)
                                                              • Default Instance: This method can be accessed via the default instance object of this class.
                                                                • JavaScript: Rho.PrinterZebra.storeImage(STRING printerDriveAndFileName, STRING imageFilePathOnDevice, INTEGER width, INTEGER height, CallBackHandler callback)
                                                                • Ruby: Rho::PrinterZebra.storeImage(STRING printerDriveAndFileName, STRING imageFilePathOnDevice, INTEGER width, INTEGER height, CallBackHandler callback)
                                                              + +

                                                              Properties

                                                              + +

                                                              ID : STRING Read Only 4.1.0

                                                              Unique printer ID during application lifetime.

                                                              +

                                                              Property Access:

                                                              • Instance: This property can be accessed via an instance object of this class:
                                                                • myObject.ID
                                                              • Default Instance: This property can be accessed via the default instance object of this class.
                                                                • JavaScript: Rho.PrinterZebra.ID
                                                                • Ruby: Rho::PrinterZebra.ID

                                                              connectionType : STRING Read Only 4.1.0

                                                              Type of connection to printer.

                                                              +

                                                              Property Access:

                                                              • Instance: This property can be accessed via an instance object of this class:
                                                                • myObject.connectionType
                                                              • Default Instance: This property can be accessed via the default instance object of this class.
                                                                • JavaScript: Rho.PrinterZebra.connectionType
                                                                • Ruby: Rho::PrinterZebra.connectionType

                                                              deviceAddress : STRING Read Only 4.1.0

                                                              IP address for Wi-Fi connection, Bluetooth® MAC address or device serial number. Note: iOS uses device serial number instead of MAC address. If you need to get device MAC you can use CPCL command ! U1 getvar “bluetooth.address”

                                                              +

                                                              Property Access:

                                                              • Instance: This property can be accessed via an instance object of this class:
                                                                • myObject.deviceAddress
                                                              • Default Instance: This property can be accessed via the default instance object of this class.
                                                                • JavaScript: Rho.PrinterZebra.deviceAddress
                                                                • Ruby: Rho::PrinterZebra.deviceAddress

                                                              deviceName : STRING Read Only 4.1.0

                                                              Bluetooth/Network name of printer.

                                                              +

                                                              Property Access:

                                                              • Instance: This property can be accessed via an instance object of this class:
                                                                • myObject.deviceName
                                                              • Default Instance: This property can be accessed via the default instance object of this class.
                                                                • JavaScript: Rho.PrinterZebra.deviceName
                                                                • Ruby: Rho::PrinterZebra.deviceName

                                                              devicePort : INTEGER 4.1.0

                                                              Default port when connecting with TCP/IP.

                                                              +

                                                              Property Access:

                                                              • Instance: This property can be accessed via an instance object of this class:
                                                                • myObject.devicePort
                                                              • Default Instance: This property can be accessed via the default instance object of this class.
                                                                • JavaScript: Rho.PrinterZebra.devicePort
                                                                • Ruby: Rho::PrinterZebra.devicePort

                                                              isConnected : BOOLEAN Read Only 4.1.0

                                                              Connection status flag. All other properties are valid only if isConnect = true. Note: This property does not guarantee a real connection, because all real device functionality is processed in separate thread asynchronously. If you want a real physical connection, use requestState() method with receive result in the callback. This is the only guaranteed method of processing real requests to the device and analyzing answers from the device.

                                                              +

                                                              Property Access:

                                                              • Instance: This property can be accessed via an instance object of this class:
                                                                • myObject.isConnected
                                                              • Default Instance: This property can be accessed via the default instance object of this class.
                                                                • JavaScript: Rho.PrinterZebra.isConnected
                                                                • Ruby: Rho::PrinterZebra.isConnected

                                                              printerType : STRING Read Only 4.1.0

                                                              Type of printer – see PRINTER_TYPE_… constants.

                                                              +

                                                              Property Access:

                                                              • Instance: This property can be accessed via an instance object of this class:
                                                                • myObject.printerType
                                                              • Default Instance: This property can be accessed via the default instance object of this class.
                                                                • JavaScript: Rho.PrinterZebra.printerType
                                                                • Ruby: Rho::PrinterZebra.printerType
                                                              + +

                                                              Constants

                                                              + +
                                                              PRINT_MODE_APPLICATOR

                                                              Applicator print mode

                                                              +
                                                              PRINT_MODE_CUTTER

                                                              Cutter print mode

                                                              +
                                                              PRINT_MODE_DELAYED_CUT

                                                              Delayed cut print mode

                                                              +
                                                              PRINT_MODE_KIOSK

                                                              Kiosk print mode

                                                              +
                                                              PRINT_MODE_LINERLESS_PEEL

                                                              Linerless peel print mode

                                                              +
                                                              PRINT_MODE_LINERLESS_REWIND

                                                              Linerless rewind print mode

                                                              +
                                                              PRINT_MODE_PARTIAL_CUTTER

                                                              Partial cutter print mode

                                                              +
                                                              PRINT_MODE_PEEL_OFF

                                                              Peel-off print mode

                                                              +
                                                              PRINT_MODE_REWIND

                                                              Rewind print mode

                                                              +
                                                              PRINT_MODE_RFID

                                                              RFID print mode

                                                              +
                                                              PRINT_MODE_TEAR_OFF

                                                              Tear-off print mode (this also implies Linerless Tear print mode)

                                                              +
                                                              PRINT_MODE_UNKNOWN

                                                              Unknown print mode

                                                              +
                                                              DISCOVERY_MODE_MULTICAST
                                                              DISCOVERY_MODE_SUBNET_SEARCH
                                                              DISCOVERY_MODE_DIRECTED_BROADCAST
                                                              DISCOVERY_MODE_LOCAL_BROADCAST
                                                              ERROR_NO_CONNECTION

                                                              Unable to create a connection to a printer

                                                              +
                                                              ERROR_WRITE_FAILURE

                                                              Write to a connection failed

                                                              +
                                                              ERROR_READ_FAILURE

                                                              Read from a connection failed

                                                              +
                                                              ERROR_UNKNOWN_PRINTER_LANGUAGE

                                                              Unable to determine the control language of a printer

                                                              +
                                                              ERROR_MALFORMED_NETWORK_DISCOVERY_ADDRESS

                                                              Malformed discovery address

                                                              +
                                                              ERROR_NETWORK_ERROR_DURING_DISCOVERY

                                                              Network error during discovery

                                                              +
                                                              ERROR_INVALID_DISCOVERY_HOP_COUNT

                                                              Invalid multi-cast hop count

                                                              +
                                                              ERROR_MALFORMED_PRINTER_STATUS_RESPONSE

                                                              Malformed status response – unable to determine printer status

                                                              +
                                                              ERROR_INVALID_FORMAT_NAME

                                                              Invalid format name

                                                              +
                                                              ERROR_BAD_FILE_DIRECTORY_ENTRY

                                                              Bad file directory entry

                                                              +
                                                              ERROR_MALFORMED_FORMAT_FIELD_NUMBER

                                                              FN' integer must be between 1 and 999

                                                              +
                                                              ERROR_INVALID_PRINTER_LANGUAGE

                                                              Invalid printer language

                                                              +
                                                              ERROR_INVALID_FILE_NAME

                                                              Invalid file name

                                                              +
                                                              ERROR_INVALID_PRINTER_DRIVE_LETTER

                                                              Invalid drive specified

                                                              +
                                                              PRINTER_STATE_IS_HEAD_COLD

                                                              Use this name for requestState(), true if the head is cold

                                                              +
                                                              PRINTER_STATE_IS_HEAD_OPEN

                                                              Use this name for requestState(), true if the head is open

                                                              +
                                                              PRINTER_STATE_IS_HEAD_TOO_HOT

                                                              Use this name for requestState(), true if the head is too hot

                                                              +
                                                              PRINTER_STATE_IS_PARTIAL_FORMAT_IN_PROGRESS

                                                              Use this name for requestState(), true if there is a partial format in progress

                                                              +
                                                              PRINTER_STATE_IS_PAUSED

                                                              Use this name for requestState(), true if the printer is paused

                                                              +
                                                              PRINTER_STATE_IS_RECEIVE_BUFFER_FULL

                                                              Use this name for requestState(), true if the receive buffer is full

                                                              +
                                                              PRINTER_STATE_IS_RIBBON_OUT

                                                              Use this name for requestState(), true if the ribbon is out

                                                              +
                                                              PRINTER_STATE_LABEL_LENGTH_IN_DOTS

                                                              Use this name for requestState(), The length of the label in dots

                                                              +
                                                              PRINTER_STATE_LABELS_REMAINING_IN_BATCH

                                                              Use this name for requestState(), The number of labels remaining in the batch

                                                              +
                                                              PRINTER_STATE_NUMBER_OF_FORMATS_IN_RECEIVE_BUFFER

                                                              Use this name for requestState(), The number of formats currently in the receive buffer of the printer

                                                              +
                                                              PRINTER_STATE_PRINT_MODE

                                                              Use this name for requestState(), The print mode

                                                              +
                                                              PRINTER_LANGUAGE_ZPL

                                                              Printer control language ZPL

                                                              +
                                                              PRINTER_LANGUAGE_CPCL

                                                              Printer control language CPCL

                                                              +
                                                              PRINTER_LANGUAGE_EPS

                                                              Printer control language EPS. Not Supported in RMS 4.1

                                                              +
                                                              PRINTER_TYPE_ANY
                                                              PRINTER_TYPE_NATIVE

                                                              Not supported in RMS 4.1

                                                              +
                                                              PRINTER_TYPE_ZEBRA
                                                              PRINTER_TYPE_EPSON

                                                              Not supported in RMS 4.1

                                                              +
                                                              PRINTER_TYPE_APD

                                                              Not supported in RMS 4.1

                                                              +
                                                              CONNECTION_TYPE_ANY
                                                              CONNECTION_TYPE_ON_BOARD

                                                              Not supported in RMS 4.1

                                                              +
                                                              CONNECTION_TYPE_USB

                                                              Supported in RMS 5.1, EB 1.3

                                                              +
                                                              CONNECTION_TYPE_BLUETOOTH
                                                              CONNECTION_TYPE_TCP
                                                              PRINTER_STATUS_SUCCESS
                                                              PRINTER_STATUS_ERROR
                                                              PRINTER_STATUS_ERR_IO
                                                              PRINTER_STATUS_ERR_MEMORY
                                                              PRINTER_STATUS_ERR_NETWORK
                                                              PRINTER_STATUS_ERR_NOT_CONNECTED
                                                              PRINTER_STATUS_ERR_NOT_FOUND
                                                              PRINTER_STATUS_ERR_PARAM
                                                              PRINTER_STATUS_ERR_PROCESSING
                                                              PRINTER_STATUS_ERR_RESPONSE
                                                              PRINTER_STATUS_ERR_TIMEOUT
                                                              PRINTER_STATUS_ERR_UNSUPPORTED
                                                              PRINTER_STATE_IS_READY_TO_PRINT

                                                              Use this name for requestState(), return true if printer ready to print.

                                                              +
                                                              PRINTER_STATE_IS_COVER_OPENED

                                                              Use this name for requestState(), return true if cover is opened.

                                                              +
                                                              PRINTER_STATE_IS_DRAWER_OPENED

                                                              Use this name for requestState(), return true if drawer is opened.

                                                              +
                                                              PRINTER_STATE_IS_PAPER_OUT

                                                              Use this name for requestState(), return true if paper out.

                                                              +
                                                              PRINTER_STATE_IS_BATTERY_LOW

                                                              Use this name for requestState(), return true if battery low.

                                                              +
                                                              + +

                                                              Examples

                                                              + +
                                                              Printing via Bluetooth
                                                              +

                                                              To print to the Zebra printer we must first search for the device. In this example we are using the searchPrinters method and passing in options to limit the search to Bluetooth and also look for Zebra printers only. If we knew the printer Bluetooth address we could have added the ‘deviceAddress’ parameter. The callback function will be executed for each printer found. When a printer is found the callback object will contain a ‘printerID’ property. This ID is an internal RhoMobie ID used. If no printerID property is there for the successful callback object, then it means that the search has finished. We don’t have any API to identify whether it is zebra or non zebra printer, so we are checking as per the friendly name of the device, If friendly name contains “zebra” then we confirm printer type as PRINTER_TYPE_ZEBRA.

                                                              +
                                                              :::javascript
                                                              +
                                                              +var printers = [];
                                                              +
                                                              +Rho.Printer.searchPrinters({
                                                              +    connectionType:Rho.Printer.CONNECTION_TYPE_BLUETOOTH,
                                                              +    printerType: Rho.Printer.PRINTER_TYPE_ZEBRA
                                                              +    }, function (cb){
                                                              +        if(cb.status == 'PRINTER_STATUS_SUCCESS')
                                                              +        {
                                                              +            if (typeof cb.printerID != "undefined")
                                                              +            {
                                                              +                console.log('Found: ' + cb.printerID)
                                                              +                printers.push(cb.printerID);
                                                              +            }
                                                              +            else
                                                              +            {
                                                              +                console.log('Done Searching');
                                                              +            }
                                                              +        }
                                                              +        else
                                                              +        {
                                                              +            console.log(cb.status);
                                                              +        }
                                                              +    }
                                                              +);
                                                              +
                                                              +                            
                                                              :::ruby
                                                              +
                                                              +@printers = []
                                                              +
                                                              +Rho::Printer.searchPrinters({ connectionType  => Rho::Printer::CONNECTION_TYPE_BLUETOOTH,
                                                              +                              printerType     => Rho::Printer::PRINTER_TYPE_ZEBRA },
                                                              +                              url_for(:action => :printer_callback) )
                                                              +
                                                              +def find_printer_callback
                                                              +  if @params['status'] == 'PRINTER_STATUS_SUCCESS'
                                                              +    if defined? @params['printerID']
                                                              +      puts "Found: #{@params['printerID']}"
                                                              +      @printers.push @params['printerID']
                                                              +    else
                                                              +      puts "Done Searching"
                                                              +    end
                                                              +  else
                                                              +    puts @params['status']
                                                              +  end
                                                              +end
                                                              +
                                                              +                            
                                                              +

                                                              Now that we have found a printer. The printers array will contain the printerID we need to create an instance object that we will use for all communications. Upon first connection to the printer via Bluetooth, you may see a prompt to enter the Bluetooth PIN. Check the manufacturers guide for details. Normally the default is ‘0000’ or ‘1111’ or ‘1234’. Once it is connected, you should see some indication in the printer (like a blue light).

                                                              +
                                                              :::javascript
                                                              +
                                                              +var myPrinter = Rho.Printer.getPrinterByID(printers[0]);
                                                              +
                                                              +// Let's try connecting
                                                              +myPrinter.connect(function (cb){
                                                              +    console.log(cb);
                                                              +    // This will be the Zebra's `Friendly Name`
                                                              +    // by default it is the serial number
                                                              +    console.log(myPrinter.deviceName);
                                                              +
                                                              +    // This will be the BT MC Address
                                                              +    since we are connecting via BlueTooth
                                                              +    console.log(myPrinter.deviceAddress);
                                                              +});
                                                              +
                                                              +                            
                                                              :::ruby
                                                              +
                                                              +@my_printer = Rho::Printer.getPrinterByID printers[0]
                                                              +
                                                              +# Let's try connecting
                                                              +@my_printer.connect url_for(:action => :printer_connect_callback)
                                                              +
                                                              +def printer_connect_callback
                                                              +  puts @params.to_s
                                                              +
                                                              +  # This will be the Zebra's `Friendly Name`
                                                              +  # by default it is the serial number
                                                              +  puts @my_printer['deviceName']
                                                              +
                                                              +  # This will be the BT MAC Address
                                                              +  # since we are connecting via BlueTooth
                                                              +  puts @my_printer['deviceAddress']
                                                              +end
                                                              +
                                                              +                            
                                                              +

                                                              Now we can just print a test string and read some properties of the printer to make sure the communications is working.

                                                              +
                                                              :::javascript
                                                              +
                                                              +// If my printer was in line mode I would see this text printed
                                                              +myPrinter.printRawString('This is a test print');
                                                              +
                                                              +// Example of sending a Zebra CPCL Command
                                                              +// changing from linemode to ZPL mode
                                                              +myPrinter.printRawString('! U1 setvar "device.languages" "ZPL"\r\n');
                                                              +
                                                              +// Get state - this is real-time status of printer.
                                                              +// reading a property of the myPrinter instance will
                                                              +// show last known status
                                                              +myPrinter.requestState(['PRINTER_STATE_IS_READY_TO_PRINT',
                                                              +    'PRINTER_STATE_IS_PAPER_OUT'],function (cb){
                                                              +        console.log(cb.status);
                                                              +        console.log(cb.PRINTER_STATE_IS_PAPER_OUT);
                                                              +        console.log(cb.PRINTER_STATE_IS_READY_TO_PRINT);
                                                              +
                                                              +    });
                                                              +                   
                                                              +                            
                                                              :::ruby
                                                              +
                                                              +# If my printer was in line mode I would see this text printed
                                                              +@my_printer.printRawString 'This is a test print'
                                                              +
                                                              +# Example of sending a Zebra CPCL Command
                                                              +# changing from linemode to ZPL mode
                                                              +@my_printer.printRawString '! U1 setvar "device.languages" "ZPL"\r\n'
                                                              +
                                                              +# Get state - this is real-time status of printer.
                                                              +# reading a property of the @my_printer instance will
                                                              +# show last known status
                                                              +@my_printer.requestState([Rho::Printer::PRINTER_STATE_IS_READY_TO_PRINT,
                                                              +                          Rho::Printer::PRINTER_STATE_IS_PAPER_OUT],
                                                              +                          url_for(:action => :request_state_callback));
                                                              +
                                                              +def request_state_callback
                                                              +  puts @params['status']
                                                              +  puts @params['PRINTER_STATE_IS_PAPER_OUT']
                                                              +  puts @params['PRINTER_STATE_IS_READY_TO_PRINT']
                                                              +end
                                                              +
                                                              +                            
                                                              + +

                                                              Remarks

                                                              + +
                                                              iOS Notes

                                                              To use a Bluetooth connection on iOS devices you should take into account the following preconditions:

                                                              + +
                                                                +
                                                              • It will only work with Zebra printers which have the Made For iPod/iPhone certification.
                                                              • +
                                                              • Before using the printer you should pair it using the iOS system Bluetooth settings.
                                                              • +
                                                              • You need to include the External Accessory framework in your project (this is automatically added when you first generate the iPhone project file)
                                                              • +
                                                              • You need to include the Zebra printer protocol string “com.zebra.rawport” in your info.plist file ([project root]/project/iphone/Info.plist) under “Supported external accessory protocols”: + +
                                                                  <key>UISupportedExternalAccessoryProtocols</key>
                                                                +  <array>
                                                                +      <string>com.zebra.rawport</string>
                                                                +  </array>
                                                                +
                                                              • +
                                                              • You need to set the key Required Background modes to App Communicates with an accessory in your app’s plist file + +
                                                                  <key>UIBackgroundModes</key>
                                                                +  <array>
                                                                +      <string>external-accessory</string>
                                                                +  </array>
                                                                +
                                                              • +
                                                              + +
                                                              Android Notes
                                                                +
                                                              • To use a Bluetooth connection on Android devices you should take into account the following preconditions: Before using the printer you should pair it using the Android system Bluetooth settings.
                                                              • +
                                                              • When you call searchPrinters() with Bluetooth search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_BLUETOOTH) then all Bluetooth devices around you will be discovered. You may see a lot of pairing requests to non-printer devices and should just cancel or ignore them. This happens because we can not detect that the device is a printer until the device is paired. It is recommended that the BT Address or WiFi MAC Address is also used when searching for printers.
                                                              • +
                                                              • When you call searchPrinters() with USB search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_USB) then you should configure your device USB controller as “USB Host mode” and should reboot device after the configuration. USB connection is not supported on the Zebra QLn320 printer. The searchPrinters method should not return any non-printer devices. If USB printers are not supported by the SDK or device, the searchPrinters function should return PRINTER_STATUS_ERR_UNSUPPORTED. For example, executing searchPrinters on an Android device with connectionType set to CONNECTION_TYPE_USB should return PRINTER_STATUS_ERR_UNSUPPORTED.
                                                              • +
                                                              + +
                                                              Windows Mobile/CE Notes
                                                                +
                                                              • You must set your app_type as “rhoelements” in your build.yml as shown the build-time settings guide.

                                                              • +
                                                              • Requires a Printing Service application to be running. This is described in the Printing Guide

                                                              • +
                                                              • You should avoid navigating from the current page using the printer without disconnecting from the printer first. You can use the window.onunload event:

                                                                + +
                                                                  window.onunload = function(){
                                                                +      printer.disconnect();
                                                                +  }
                                                                +
                                                              • +
                                                              • When you call searchPrinters() with Bluetooth search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_BLUETOOTH) then all Bluetooth devices around you will be discovered. You may see a lot of pairing requests to non-printer devices and should just cancel or ignore them. This happens because we can not detect that the device is a printer until the device is paired. It is recommended that the BT Address or WiFi MAC Address is also used when searching for printers.

                                                              • +
                                                              + +
                                                              Supported Zebra Printers

                                                              Only printers listed in supported models in Zebra SDK description (click “Compatible Printers” link) are supported for use with this API. For example, the QL 320 (old model) is not supported but, QLn320 and QL320 plus are supported.

                                                              +
                                                              \ No newline at end of file diff --git a/docs/en/5.5/api/printingzebra.xml b/docs/en/5.5/api/printingzebra.xml new file mode 100644 index 00000000..7720138b --- /dev/null +++ b/docs/en/5.5/api/printingzebra.xml @@ -0,0 +1,531 @@ + + + + + The PrinterZebra API provides Zebra-specific API access to Zebra's Bluetooth and Wi-Fi network printers, and to USB-capable printers for Android and Windows Mobile/CE. This API inherits all methods, properties and constants from the [Printer API](#api-printing). + +###Notes + +1. Unless using the printer's 'line mode' (for sending raw text strings), Zebra recommends sending ZPL only. +2. USB printing is supported for Android and Windows Mobile/CE. + +## Enabling the API +To use this API you must include the following extensions in your `build.yml`: + + :::ruby + extensions: ["printing","printing_zebra"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the Printer API: + +* Include all 'ebapi' modules +* Include only the API modules you need + +Both methods are explained below. + +Either way, the included files will be from: +`/Enterprise Browser/JavaScript Files/Enterprise Browser`, +a directory on the computer that contains the Enterprise Browser installation. + +### Include all JS API modules +To include all JavaScript APIs, copy the `ebapi-modules.js` file to a location accessible by your app's files and include the JavaScript modules file in your app. For instance, to include the modules file in your `index.html`, copy the file to the same directory as your index.html and add the following line to the HEAD section of your index.html file: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> This will define the EB class within the page. **Note that the path for this file is relative to the current page** (index.html). Any page on which the modules are required will need to have the required .js file(s) included in this fashion. + +### Include only the modules you need +To include individual APIs, you must first include the `ebapi.js` in your HTML, and then the additional required API file(s). For instance, to use the Printer API, add the following code to the HTML file(s). Again, this assumes that relevant API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.printer.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.printerzebra.js"></script> + +> In the code lines above, notice that `ebapi.js` is included first, followed by `eb.printer.js` and `eb.printer.js`, which are the Printer APIs required for Enterprise Browser to output to Zebra printers. **This coding is required on each HTML page whenever an individual API will be called from that page**. + + + + + + + + + + + + Applicator print mode + + + Cutter print mode + + + Delayed cut print mode + + + Kiosk print mode + + + Linerless peel print mode + + + Linerless rewind print mode + + + Partial cutter print mode + + + Peel-off print mode + + + Rewind print mode + + + RFID print mode + + + Tear-off print mode (this also implies Linerless Tear print mode) + + + Unknown print mode + + + + + + + + + + Unable to create a connection to a printer + + + + Write to a connection failed + + + + Read from a connection failed + + + + Unable to determine the control language of a printer + + + + Malformed discovery address + + + + Network error during discovery + + + + Invalid multi-cast hop count + + + + Malformed status response - unable to determine printer status + + + + Invalid format name + + + + Bad file directory entry + + + + '^FN' integer must be between 1 and 999 + + + + Invalid printer language + + + + Invalid file name + + + + Invalid drive specified + + + + Use this name for requestState(), true if the head is cold + + + Use this name for requestState(), true if the head is open + + + Use this name for requestState(), true if the head is too hot + + + Use this name for requestState(), true if there is a partial format in progress + + + Use this name for requestState(), true if the printer is paused + + + Use this name for requestState(), true if the receive buffer is full + + + Use this name for requestState(), true if the ribbon is out + + + Use this name for requestState(), The length of the label in dots + + + Use this name for requestState(), The number of labels remaining in the batch + + + Use this name for requestState(), The number of formats currently in the receive buffer of the printer + + + Use this name for requestState(), The print mode + + + + + + 4.1.0 + WM, CE, Android, iOS + Android, WM, CE + Retrieves the names of the files which are stored on the printer. Works asynchronously; use callback to check the result. + + + + PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR + + + + + + + + + + + 4.1.0 + WM, CE, Android, iOS + Android, WM, CE + This method only returns files which have the extensions in "extensions". Works asynchronously; use callback to check the result. + + + + The list of extensions that should be returned. + + + + + + PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR + + + + + + + + + + + 4.1.0 + WM, CE, Android, iOS + Android, WM, CE + Sends the contents of a file on the device to the printer. Equals to printing raw string with content of specified file. Should be used to print ZPL and CPCL commands stored inside predefined filed. Works asynchronously; use callback to check the result. + + + Location of file to print. This path must be fully qualified path to local file on the device. + + + + Returns result of a printing attempt. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR + + + + + 4.1.0 + WM, CE, Android, iOS + Android, WM, CE + Prints a stored format on the printer, filling in the fields specified by the Hash. Works asynchronously; use callback to check the result. + + + The location of the file on the printer (e.g. "E:FORMAT.ZPL"). + + + A Hash containing the key / value pairs for the stored format. For ZPL formats, the key number should correspond directly to the number of the field in the format. Number keys should be passed as Strings, i.e. '1':'field1' etc. Only ZPL format is supported; CPCL format is not supported. + + + + Returns result of a printing attempt. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR. If you try to print formats containing invalid data, then only iOS return ERROR, on Android and WM Zebra SDK not provided that info due to Zebra SDK API limitations on Android and WM. So on Android and WM you can receive ERROR only if some connection problem occurred. + Returns result of a printing attempt. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR. If you try to print formats containing invalid data, on Android and WM Zebra SDK does not provide that info due to Zebra SDK API limitations on Android and WM. So on Android and WM you can receive ERROR only if some connection problem occurred. + + + + + 4.1.0 + WM, CE, Android, iOS + Android, WM, CE + Prints a stored format on the printer, filling in the fields specified by the array. Works asynchronously; use callback to check the result. + + + The location of the file on the printer (e.g. "E:FORMAT.ZPL"). + + + An array of strings representing the data to fill into the format. For ZPL formats, index 0 of the array corresponds to field number 2 (^FN2). For CPCL, the variables are passed in the order that they are found in the format + + + + Returns result of a printing attempt. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR. If you try to print format contains invalid data, then only iOS return ERROR, on Android and WM Zebra SDK not provided that info due to Zebra SDK API limitations on Android and WM. So on Android and WM you can receive ERROR only if some connection problem occurred. + Returns result of a printing attempt. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR. If you try to print formats containing invalid data, on Android and WM Zebra SDK does not provide that info due to Zebra SDK API limitations on Android and WM. So on Android and WM you can receive ERROR only if some connection problem occurred. + + + + + 4.1.0 + WM, CE, Android, iOS + Android, WM, CE + Stores the specified image to the connected printer as a monochrome image. Works asynchronously; use callback to check the result. The image will be stored on the printer at printerDriveAndFileName with the extension GRF. If a drive letter is not supplied, E will be used as the default (e.g. FILE becomes E:FILE.GRF). If an extension is supplied, it is ignored (E:FILE.BMP becomes E:FILE.GRF). Note that if the image resolution is large (e.g. 1024x768) this method may take a long time to execute. There are device OS limitations on supported file formats and image sizes. iOS, Android and WM are supporting only JPG and PNG files. WM can fail to handle large (>1024x1024 pixel) images. + Stores the specified image to the connected printer as a monochrome image. Works asynchronously; use callback to check the result. The image will be stored on the printer at printerDriveAndFileName with the extension GRF. If a drive letter is not supplied, E will be used as the default (e.g. FILE becomes E:FILE.GRF). If an extension is supplied, it is ignored (E:FILE.BMP becomes E:FILE.GRF). Note that if the image resolution is large (e.g. 1024x768) this method may take a long time to execute. There are device OS limitations on supported file formats and image sizes. Android and WM support only JPG and PNG files. WM can fail to handle large (>1024x1024 pixel) images. + + + Path on the printer where the image will be stored. + + + Path to the local image file containing the bitmap image to send. + + + Desired width of the printed image, in dots. Passing -1 will preserve original width. + + + Desired height of the printed image, in dots. Passing -1 will preserve original height. + + + + Returns result of a printing attempt. PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR, + + + + + + + + 4.1.0 + WM, CE, Android, iOS + Android, WM, CE + + + +To use a Bluetooth connection on iOS devices you should take into account the following preconditions: + +* It will only work with Zebra printers which have the `Made For iPod/iPhone` certification. +* Before using the printer you should pair it using the iOS system Bluetooth settings. +* You need to include the External Accessory framework in your project (this is automatically added when you first generate the iPhone project file) +* You need to include the Zebra printer protocol string "com.zebra.rawport" in your info.plist file ([project root]/project/iphone/Info.plist) under "Supported external accessory protocols": + <key>UISupportedExternalAccessoryProtocols</key> + <array> + <string>com.zebra.rawport</string> + </array> +* You need to set the key `Required Background modes` to `App Communicates with an accessory` in your app's plist file + <key>UIBackgroundModes</key> + <array> + <string>external-accessory</string> + </array> + + + +* To use a Bluetooth connection on Android devices you should take into account the following preconditions: Before using the printer you should pair it using the Android system Bluetooth settings. +* When you call searchPrinters() with Bluetooth search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_BLUETOOTH) then _all_ Bluetooth devices around you will be discovered. You may see a lot of pairing requests to non-printer devices and should just cancel or ignore them. This happens because we can not detect that the device is a printer until the device is paired. It is recommended that the BT Address or WiFi MAC Address is also used when searching for printers. +* When you call searchPrinters() with USB search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_USB) then you should configure your device USB controller as "USB Host mode" and should reboot device after the configuration. USB connection is not supported on the Zebra QLn320 printer. The searchPrinters method should not return any non-printer devices. If USB printers are not supported by the SDK or device, the searchPrinters function should return PRINTER_STATUS_ERR_UNSUPPORTED. For example, executing searchPrinters on an Android device with connectionType set to CONNECTION_TYPE_USB should return PRINTER_STATUS_ERR_UNSUPPORTED. + + + + + + +* You must set your app_type as "rhoelements" in your `build.yml` as shown the [build-time settings guide](../guide/build_config#other-build-time-settings). + +* Requires a Printing Service application to be running. This is described in the [Printing Guide](../guide/printing#platform-notes) + +* You should avoid navigating from the current page using the printer without disconnecting from the printer first. You can use the window.onunload event: + + window.onunload = function(){ + printer.disconnect(); + } + +* When you call searchPrinters() with Bluetooth search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_BLUETOOTH) then _all_ Bluetooth devices around you will be discovered. You may see a lot of pairing requests to non-printer devices and should just cancel or ignore them. This happens because we can not detect that the device is a printer until the device is paired. It is recommended that the BT Address or WiFi MAC Address is also used when searching for printers. + + +* Requires a Printing Service application to be running. + +* You should avoid navigating from the current page using the printer without disconnecting from the printer first. You can use the window.onunload event: + + :::javascript + window.onunload = function(){ + printer.disconnect(); + } + +* When you call searchPrinters() with Bluetooth search (with CONNECTION_TYPE_ANY or CONNECTION_TYPE_BLUETOOTH) then _all_ Bluetooth devices around you will be discovered. You may see a lot of pairing requests to non-printer devices and should just cancel or ignore them. This happens because we can not detect that the device is a printer until the device is paired. It is recommended that the BT Address or WiFi MAC Address is also used when searching for printers. + + + Only printers listed in supported models in Zebra [SDK description](https://www.zebra.com/us/en/products-services/software/zebralink/zebralink-multiplatform-sdk.html) (click "Compatible Printers" link) are supported for use with this API. For example, the QL 320 (old model) is __not__ supported but, QLn320 and QL320 plus __are__ supported. + + + + + +
                                                              + To print to the Zebra printer we must first search for the device. In this example we are using the searchPrinters method and passing in options to limit the search to Bluetooth and also look for Zebra printers only. If we knew the printer Bluetooth address we could have added the 'deviceAddress' parameter. The callback function will be executed for each printer found. When a printer is found the callback object will contain a 'printerID' property. This ID is an internal RhoMobie ID used. If no printerID property is there for the successful callback object, then it means that the search has finished. We don't have any API to identify whether it is zebra or non zebra printer, so we are checking as per the friendly name of the device, If friendly name contains "zebra" then we confirm printer type as PRINTER_TYPE_ZEBRA. + + + + Rho::Printer::CONNECTION_TYPE_BLUETOOTH, + printerType => Rho::Printer::PRINTER_TYPE_ZEBRA }, + url_for(:action => :printer_callback) ) + +def find_printer_callback + if @params['status'] == 'PRINTER_STATUS_SUCCESS' + if defined? @params['printerID'] + puts "Found: #{@params['printerID']}" + @printers.push @params['printerID'] + else + puts "Done Searching" + end + else + puts @params['status'] + end +end +]]> + + +
                                                              +
                                                              + Now that we have found a printer. The `printers` array will contain the `printerID` we need to create an instance object that we will use for all communications. Upon first connection to the printer via Bluetooth, you may see a prompt to enter the Bluetooth PIN. Check the manufacturers guide for details. Normally the default is '0000' or '1111' or '1234'. Once it is connected, you should see some indication in the printer (like a blue light). + + + + :printer_connect_callback) + +def printer_connect_callback + puts @params.to_s + + # This will be the Zebra's `Friendly Name` + # by default it is the serial number + puts @my_printer['deviceName'] + + # This will be the BT MAC Address + # since we are connecting via BlueTooth + puts @my_printer['deviceAddress'] +end +]]> + + +
                                                              +
                                                              + Now we can just print a test string and read some properties of the printer to make sure the communications is working. + + + + :request_state_callback)); + +def request_state_callback + puts @params['status'] + puts @params['PRINTER_STATE_IS_PAPER_OUT'] + puts @params['PRINTER_STATE_IS_READY_TO_PRINT'] +end +]]> + + +
                                                              +
                                                              +
                                                              +
                                                              +
                                                              +
                                                              diff --git a/docs/en/5.5/api/process.md b/docs/en/5.5/api/process.md new file mode 100644 index 00000000..ade57edf --- /dev/null +++ b/docs/en/5.5/api/process.md @@ -0,0 +1,34 @@ +#Process +
                                                              +

                                                              This API is used to either navigate to a URL or call a javascript function when an attached card reader decodes data. Only the foreground application is given access to the card reader hardware, when an application is sent to the background its state will be saved and it will automatically relinquish control of the card reader. When brought back to the foreground, an application previously using the card reader will have its previous configuration (eg. pinTimeout) reapplied to the card reader automatically.

                                                              +

                                                              Enabling the API

                                                              + +

                                                              This API is part of the coreapi extension that is included automatically.

                                                              + +
                                                              :::ruby
                                                              +extensions: ["coreapi"]
                                                              +
                                                              + +

                                                              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

                                                              + +

                                                              closeHandle()

                                                              Close process handle.

                                                              +

                                                              Synchronous Return:

                                                              • Void

                                                              Method Access:

                                                              • Instance Method: This method can be accessed via an instance object of this class:
                                                                • myObject.closeHandle()

                                                              getProcessExitCode()

                                                              GetProcessExitCode.

                                                              +

                                                              Synchronous Return:

                                                              • INTEGER :

                                                                Process exit code.

                                                                +

                                                              Method Access:

                                                              • Instance Method: This method can be accessed via an instance object of this class:
                                                                • myObject.getProcessExitCode()

                                                              runApplication(STRING appName, STRING params, BOOLEAN blockingCall)

                                                              Run an application.

                                                              +

                                                              Parameters

                                                              • appName : STRING

                                                                The name of the application on the device to run.

                                                                +

                                                              • params : STRING Optional

                                                                The name of the application on the device to run.

                                                                +

                                                              • blockingCall : BOOLEAN Optional

                                                                The name of the application on the device to run.

                                                                +

                                                                False by default.

                                                                +

                                                              Synchronous Return:

                                                              • SELF_INSTANCE :

                                                                Process object.

                                                                +

                                                              Method Access:

                                                              • Class Method: This method can only be accessed via the API class object.
                                                                • JavaScript: Rho.Process.runApplication(STRING appName, STRING params, BOOLEAN blockingCall)
                                                                • Ruby: Rho::Process.runApplication(STRING appName, STRING params, BOOLEAN blockingCall)

                                                              waitForApplication()

                                                              WaitForApplication.

                                                              +

                                                              Synchronous Return:

                                                              • Void

                                                              Method Access:

                                                              • Instance Method: This method can be accessed via an instance object of this class:
                                                                • myObject.waitForApplication()
                                                              \ No newline at end of file diff --git a/docs/en/5.5/api/process.xml b/docs/en/5.5/api/process.xml new file mode 100644 index 00000000..9404b411 --- /dev/null +++ b/docs/en/5.5/api/process.xml @@ -0,0 +1,132 @@ + + + + + This API is used to either navigate to a URL or call a javascript function when an attached card reader decodes data. Only the foreground application is given access to the card reader hardware, when an application is sent to the background its state will be saved and it will automatically relinquish control of the card reader. When brought back to the foreground, an application previously using the card reader will have its previous configuration (eg. pinTimeout) reapplied to the card reader automatically. + + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby + + +## Enabling the API +There are two methods of enabling the Process API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Process API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.process.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + Run an application. + + + The name of the application on the device to run. + + + The name of the application on the device to run. + + + + The name of the application on the device to run. + + False by default. + + + + + Process object. + + + + + WaitForApplication. + + + + Close process handle. + + + + GetProcessExitCode. + + Process exit code. + + + + + + + + + + + + + + + + + You must have the appropriate drivers installed on your device to use the CardReader. You will see which drivers are installed in the RhoElements log file after you attempt to use any of the card reader functions in RhoElements. All necessary drivers should be included as part of the platform for supported devices. + ]]> + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + \ No newline at end of file diff --git a/docs/en/5.5/api/property_bag.xml b/docs/en/5.5/api/property_bag.xml new file mode 100644 index 00000000..5589ff72 --- /dev/null +++ b/docs/en/5.5/api/property_bag.xml @@ -0,0 +1,75 @@ + + + + + + + This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class. + + + The property to return info about. + + + + The property to return info about. + + + + + + + This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class. + + + + List of properties I want to know about + + + + Map of properties I want to know about + + + + + + + + + + This method will return all of object/value pairs for the propertyNames of the API class. + + Map of all available properties + + + + + + + + + + This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only. + + + The one property name that I want to set + + + The one property value that I want to set + + + + + + + This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only. + + + Map of properties I want to set + + + + + + + + diff --git a/docs/en/5.5/api/push.md b/docs/en/5.5/api/push.md new file mode 100644 index 00000000..fe2925dc --- /dev/null +++ b/docs/en/5.5/api/push.md @@ -0,0 +1,119 @@ +#Push +
                                                              +

                                                              The Push API provides access to Push messaging functionality. Use this API to give your application the ability to receive server initiated messages.

                                                              +

                                                              Enabling the API

                                                              + +

                                                              To use this API, you must include the following extension in your build.yml:

                                                              + +

                                                              For APNS or GCM:

                                                              + +
                                                              :::ruby
                                                              +capabilities: ["push"]
                                                              +
                                                              + +

                                                              For RhoConnect Push Service:

                                                              + +
                                                              :::ruby
                                                              +extensions: ["rhoconnect-push", "rhoconnect-client"]
                                                              +
                                                              + +

                                                              NOTES

                                                              + +

                                                              For Win32(XPE), Microsoft Message Queue (MSMQ) and .Net Framework 3.5 also must be installed on the device.

                                                              + +

                                                              GCM is no longer supported as a standalone jar file since being moved to Google Play services. If you have trouble building an Android app with RhoElements 4.0.0 and Push capability, try these steps:

                                                              + +
                                                                +
                                                              1. Download the GCM r03 sip file from Google’s repository.
                                                              2. +
                                                              3. Copy it to sdk/extras and extract it.
                                                              4. +
                                                              5. Rename the folder to ‘gcm’
                                                              6. +
                                                              + + +

                                                              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

                                                              + +

                                                              getAllProperties(CallBackHandler callback)

                                                              This method will return all of object/value pairs for the propertyNames of the API class.

                                                              +

                                                              Parameters

                                                              • callback : CallBackHandler Optional

                                                              Async Callback Returning Parameters: HASH

                                                                • : STRING

                                                              Synchronous Return:

                                                              • HASH :

                                                                Map of all available properties

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

                                                              Method Access:

                                                              • Instance Method: This method can be accessed via an instance object of this class:
                                                                • myObject.getAllProperties(CallBackHandler callback)
                                                              • Default Instance: This method can be accessed via the default instance object of this class.
                                                                • JavaScript: Rho.Push.getAllProperties(CallBackHandler callback)
                                                                • Ruby: Rho::Push.getAllProperties(CallBackHandler callback)

                                                              getDefault()

                                                              This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

                                                              +

                                                              Synchronous Return:

                                                              • SELF_INSTANCE :

                                                                Default object of Module.

                                                                +

                                                              Method Access:

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

                                                              getDeviceId(CallBackHandler callback)

                                                              Returns push token used to identify particular device.

                                                              +

                                                              Parameters

                                                              • callback : CallBackHandler Optional

                                                              Async Callback Returning Parameters: STRING

                                                                Synchronous Return:

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

                                                                Method Access:

                                                                • Instance Method: This method can be accessed via an instance object of this class:
                                                                  • myObject.getDeviceId(CallBackHandler callback)
                                                                • Default Instance: This method can be accessed via the default instance object of this class.
                                                                  • JavaScript: Rho.Push.getDeviceId(CallBackHandler callback)
                                                                  • Ruby: Rho::Push.getDeviceId(CallBackHandler callback)

                                                                getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                                                                +

                                                                Parameters

                                                                • arrayofNames : ARRAY

                                                                  List of properties I want to know about

                                                                  +

                                                                  • Object : STRING

                                                                • callback : CallBackHandler Optional

                                                                Async Callback Returning Parameters: HASH

                                                                  • : STRING

                                                                Synchronous Return:

                                                                • HASH :

                                                                  Map of properties I want to know about

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

                                                                Method Access:

                                                                • Instance Method: This method can be accessed via an instance object of this class:
                                                                  • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                                                • Default Instance: This method can be accessed via the default instance object of this class.
                                                                  • JavaScript: Rho.Push.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                                                  • Ruby: Rho::Push.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                getProperty(STRING propertyName, CallBackHandler callback)

                                                                This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                                                                +

                                                                Parameters

                                                                • propertyName : STRING

                                                                  The property to return info about.

                                                                  +

                                                                • callback : CallBackHandler Optional

                                                                Async Callback Returning Parameters: STRING

                                                                  Synchronous Return:

                                                                  • STRING :

                                                                    The property to return info about.

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

                                                                  Method Access:

                                                                  • Instance Method: This method can be accessed via an instance object of this class:
                                                                    • myObject.getProperty(STRING propertyName, CallBackHandler callback)
                                                                  • Default Instance: This method can be accessed via the default instance object of this class.
                                                                    • JavaScript: Rho.Push.getProperty(STRING propertyName, CallBackHandler callback)
                                                                    • Ruby: Rho::Push.getProperty(STRING propertyName, CallBackHandler callback)

                                                                  setDefault(SELF_INSTANCE: Rho::Push defaultInstance)

                                                                  This method allows you to set the attributes of the default object instance by passing in an object of the same class.

                                                                  +

                                                                  Parameters

                                                                  • defaultInstance : SELF_INSTANCE: Rho::Push

                                                                    An instance object that is of the same class.

                                                                    +

                                                                  Synchronous Return:

                                                                  • Void

                                                                  Method Access:

                                                                  • Class Method: This method can only be accessed via the API class object.
                                                                    • JavaScript: Rho.Push.setDefault(SELF_INSTANCE: Rho::Push defaultInstance)
                                                                    • Ruby: Rho::Push.setDefault(SELF_INSTANCE: Rho::Push defaultInstance)

                                                                  setProperties(HASH propertyMap)

                                                                  This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                  +

                                                                  Parameters

                                                                  • propertyMap : HASH

                                                                    Map of properties I want to set

                                                                    +

                                                                    • Object : STRING

                                                                  Synchronous Return:

                                                                  • Void

                                                                  Method Access:

                                                                  • Instance Method: This method can be accessed via an instance object of this class:
                                                                    • myObject.setProperties(HASH propertyMap)
                                                                  • Default Instance: This method can be accessed via the default instance object of this class.
                                                                    • JavaScript: Rho.Push.setProperties(HASH propertyMap)
                                                                    • Ruby: Rho::Push.setProperties(HASH propertyMap)

                                                                  setProperty(STRING propertyName, STRING propertyValue)

                                                                  This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                  +

                                                                  Parameters

                                                                  • propertyName : STRING

                                                                    The one property name that I want to set

                                                                    +

                                                                  • propertyValue : STRING

                                                                    The one property value that I want to set

                                                                    +

                                                                  Synchronous Return:

                                                                  • Void

                                                                  Method Access:

                                                                  • Instance Method: This method can be accessed via an instance object of this class:
                                                                    • myObject.setProperty(STRING propertyName, STRING propertyValue)
                                                                  • Default Instance: This method can be accessed via the default instance object of this class.
                                                                    • JavaScript: Rho.Push.setProperty(STRING propertyName, STRING propertyValue)
                                                                    • Ruby: Rho::Push.setProperty(STRING propertyName, STRING propertyValue)

                                                                  startNotifications(CallBackHandler callback)

                                                                  Start listening for push messages, errors or other push related events.

                                                                  +

                                                                  Parameters

                                                                  • callback : CallBackHandler Mandatory

                                                                  Async Callback Returning Parameters: HASH

                                                                    • doSync : STRING

                                                                      List of sources to sync separated by comma or ‘all’.

                                                                      +

                                                                    • alertText : STRING

                                                                      Alert message to show to user.

                                                                      +

                                                                    • vibrateDuration : INTEGER

                                                                      Vibrate duration in milliseconds.

                                                                      +

                                                                    • alertSound : STRING

                                                                      Path to sound file to play when push message is received.

                                                                      +

                                                                  Synchronous Return:

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

                                                                  Method Access:

                                                                  • Instance Method: This method can be accessed via an instance object of this class:
                                                                    • myObject.startNotifications(CallBackHandler callback)
                                                                  • Default Instance: This method can be accessed via the default instance object of this class.
                                                                    • JavaScript: Rho.Push.startNotifications(CallBackHandler callback)
                                                                    • Ruby: Rho::Push.startNotifications(CallBackHandler callback)

                                                                  stopNotifications()

                                                                  Stop listening push events.

                                                                  +

                                                                  Synchronous Return:

                                                                  • Void

                                                                  Method Access:

                                                                  • Instance Method: This method can be accessed via an instance object of this class:
                                                                    • myObject.stopNotifications()
                                                                  • Default Instance: This method can be accessed via the default instance object of this class.
                                                                    • JavaScript: Rho.Push.stopNotifications()
                                                                    • Ruby: Rho::Push.stopNotifications()
                                                                  + +

                                                                  Properties

                                                                  + +

                                                                  pushAppName : STRING Read Only

                                                                  Application name used by RhoConnect Push server to identify application.

                                                                  +

                                                                  Property Access:

                                                                  • Instance: This property can be accessed via an instance object of this class:
                                                                    • myObject.pushAppName
                                                                  • Default Instance: This property can be accessed via the default instance object of this class.
                                                                    • JavaScript: Rho.Push.pushAppName
                                                                    • Ruby: Rho::Push.pushAppName

                                                                  pushServer : STRING Read Only

                                                                  URL of RhoConnect Push server.

                                                                  +

                                                                  Property Access:

                                                                  • Instance: This property can be accessed via an instance object of this class:
                                                                    • myObject.pushServer
                                                                  • Default Instance: This property can be accessed via the default instance object of this class.
                                                                    • JavaScript: Rho.Push.pushServer
                                                                    • Ruby: Rho::Push.pushServer

                                                                  type : STRING Read Only

                                                                  Push engine type.

                                                                  +

                                                                  Possible Values (STRING):

                                                                  Constant: Rho.Push.PUSH_TYPE_RHOCONNECT (For Ruby use "::" for all "." when referencing constants)
                                                                  String: rhoconnect-push

                                                                  RhoConnect push engine.

                                                                  +
                                                                  Constant: Rho.Push.PUSH_TYPE_NATIVE (For Ruby use "::" for all "." when referencing constants)
                                                                  String: native-push

                                                                  Native push engine (like GCM on Android).

                                                                  +

                                                                  Property Access:

                                                                  • Instance: This property can be accessed via an instance object of this class:
                                                                    • myObject.type
                                                                  • Default Instance: This property can be accessed via the default instance object of this class.
                                                                    • JavaScript: Rho.Push.type
                                                                    • Ruby: Rho::Push.type

                                                                  userNotifyMode : STRING

                                                                  Deprecated

                                                                  UI notification mode. Use Rho.Notification instead.

                                                                  +

                                                                  Default: backgroundNotifications

                                                                  Possible Values (STRING):

                                                                  Constant: Rho.Push.PUSH_NOTIFY_NONE (For Ruby use "::" for all "." when referencing constants)
                                                                  String: none

                                                                  Do not notify user about received push messages.

                                                                  +
                                                                  Constant: Rho.Push.PUSH_NOTIFY_ALERTS (For Ruby use "::" for all "." when referencing constants)
                                                                  String: alert

                                                                  Notify user with alerts inside of application UI only.

                                                                  +
                                                                  Constant: Rho.Push.PUSH_NOTIFY_NOTIFICATIONS (For Ruby use "::" for all "." when referencing constants)
                                                                  String: notification

                                                                  Notify user using notification bar.

                                                                  +
                                                                  Constant: Rho.Push.PUSH_NOTIFY_NOTIFICATIONS_AND_ALERTS (For Ruby use "::" for all "." when referencing constants)
                                                                  String: backgroundNotifications

                                                                  Notify user using notification bar if in background and with alerts in foreground.

                                                                  +

                                                                  Property Access:

                                                                  • Instance: This property can be accessed via an instance object of this class:
                                                                    • myObject.userNotifyMode
                                                                  • Default Instance: This property can be accessed via the default instance object of this class.
                                                                    • Ruby: Rho::Push.userNotifyMode
                                                                  + +

                                                                  Examples

                                                                  + +
                                                                  Handle push message
                                                                  +

                                                                  Start Push Notifications service and define alert popup window in push callback method.

                                                                  +
                                                                  :::javascript
                                                                  +
                                                                  +                                
                                                                  +function setupPush() {
                                                                  +  // Start listening for push messages. Parameter is an url to push_callback method
                                                                  +  Rho.Push.startNotifications(pushCallback);
                                                                  +}
                                                                  +
                                                                  +function pushCallback(params) {
                                                                  +  // Show 'alert' popup window with push message text
                                                                  +  var propertyMap = {message: params["alert"], buttons: [{id: 'OK', title: 'OK'}]};
                                                                  +  Rho.Notification.showPopup(propertyMap);
                                                                  +}
                                                                  +                                
                                                                  +                            
                                                                  :::ruby
                                                                  +
                                                                  +                                
                                                                  +def setup_push
                                                                  +  # Start listening for push messages. Parameter is an url to push_callback method
                                                                  +  Rho::Push.startNotifications(url_for(:action=>:push_callback))
                                                                  +end
                                                                  +
                                                                  +
                                                                  +def push_callback
                                                                  +  # Show 'alert' popup window with push message text
                                                                  +  Rho::Notification.showPopup({'message' => @params['alert'], 'buttons' =>['OK']})
                                                                  +end
                                                                  +                                
                                                                  +                            
                                                                  \ No newline at end of file diff --git a/docs/en/5.5/api/push.xml b/docs/en/5.5/api/push.xml new file mode 100644 index 00000000..3c34018c --- /dev/null +++ b/docs/en/5.5/api/push.xml @@ -0,0 +1,200 @@ + + + + + The Push API provides access to Push messaging functionality. Use this API to give your application the ability to receive server initiated messages. + +## Enabling the API +To use this API, you must include the following extension in your `build.yml`: + +For APNS or GCM: + :::ruby + capabilities: ["push"] + +For RhoConnect Push Service: + :::ruby + extensions: ["rhoconnect-push", "rhoconnect-client"] + +**NOTES** + +**For Win32(XPE)**, Microsoft Message Queue (MSMQ) and .Net Framework 3.5 also must be installed on the device. + +**GCM is no longer supported as a standalone jar file** since being moved to Google Play services. If you have trouble building an Android app with RhoElements 4.0.0 and Push capability, try these steps: + +1. [Download the GCM r03 sip file](http://dl-ssl.google.com/android/repository/gcm_r03.zip) from Google's repository. +2. Copy it to sdk/extras and extract it. +3. Rename the folder to 'gcm' + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the Push API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Push API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.push.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + WM, CE, Android, iOS + WM, CE, Android + 4.0.0 + + + + + + + These properties are used to configure the Push API. + + + Push engine type. + + + RhoConnect push engine. + + + Native push engine (like GCM on Android). + + + + + + UI notification mode. Use `Rho.Notification` instead. + UI notification mode. Use `EB.Notification` instead. + Android + + + + Do not notify user about received push messages. + + + Notify user with alerts inside of application UI only. + + + Notify user using notification bar. + + + Notify user using notification bar if in background and with alerts in foreground. + + + + + + URL of RhoConnect Push server. + + + + Application name used by RhoConnect Push server to identify application. + + + + + + Returns the push API objects configured within the application. + + Array of available push engines. + + + + + + Returns push token used to identify particular device. + + + + + Start listening for push messages, errors or other push related events. + + Hash map with push message payload. + + + List of sources to sync separated by comma or 'all'. + + + Alert message to show to user. + + + Vibrate duration in milliseconds. + + + Path to sound file to play when push message is received. + + + + + + + Stop listening push events. + + + + + + + + + + + +
                                                                  + Start Push Notifications service and define alert popup window in push callback method. + + + :push_callback)) +end + + +def push_callback + # Show 'alert' popup window with push message text + Rho::Notification.showPopup({'message' => @params['alert'], 'buttons' =>['OK']}) +end + ]]> + + + + + +
                                                                  +
                                                                  +
                                                                  +
                                                                  +
                                                                  +
                                                                  \ No newline at end of file diff --git a/docs/en/5.5/api/rhoerror.md b/docs/en/5.5/api/rhoerror.md new file mode 100644 index 00000000..476a34d3 --- /dev/null +++ b/docs/en/5.5/api/rhoerror.md @@ -0,0 +1,16 @@ +# RhoError + +## message + +Translate the Rho error codes to a text message. + + 0 = `ERR_NONE` + 1 = `ERR_NETWORK` + 2 = `ERR_REMOTESERVER` + 3 = `ERR_RUNTIME` + 4 = `ERR_UNEXPECTEDSERVERRESPONSE` + 5 = `ERR_DIFFDOMAINSINSYNCSRC` + 6 = `ERR_NOSERVERRESPONSE` + 7 = `ERR_CLIENTISNOTLOGGEDIN` + 8 = `ERR_CUSTOMSYNCSERVER` + 9 = `ERR_UNATHORIZED` \ No newline at end of file diff --git a/docs/en/5.5/api/rhom-api.md b/docs/en/5.5/api/rhom-api.md new file mode 100644 index 00000000..dd0dccec --- /dev/null +++ b/docs/en/5.5/api/rhom-api.md @@ -0,0 +1,679 @@ +# Rhom Ruby API +Allows Ruby access to the Rhodes mini database object mapper, performing database operation on Rhodes model objects. + +**NOTE: For JavaScript access to the Rhom, see the [ORM JavaScript API](Orm).** + + +## can_modify +Returns true if the Rhodes model object is not currently being synced (if it is being synced, you should disable editing of the object). + +Before displaying an edit page for an object, your application can check if the object is currently being accessed by the sync process. If it is, you should disable editing of the object. `can_modify` could return true, for example, on a new local record that was created and sent to the RhoConnect application, but no response has been received yet. + + :::ruby + modelname.can_modify + +### Example +Before displaying an edit page for an object, your application can check if the object is currently being accessed by the sync process. If it is, you should disable editing of the object. `can_modify` could return true, for example, on a new local record that was created and sent to the RhoConnect application, but no response has been received yet. + + :::ruby + def edit + @product = Product.find(@params['id']) + if @product && !@product.can_modify + render :action => :show_edit_error + else + render :action => :edit + end + end + + +## changed? +Returns true if a Rhodes model object has local database changes that need to be synchronized, false otherwise. + + :::ruby + modelname.changed? + +### Example +Determine if a rhom model has local database changes that need to be synchronized. + + :::ruby + def should_sync_product_object + if Product.changed? + #... do stuff ... + end + end + + +## client_id +Returns the current sync client id. + + :::ruby + modelname.client_id + + +## clear_notification +Clear notification for the object. + + :::ruby + modelname.clear_notification + + +## count +Returns the number of objects in the named model. This is equivalent to using the `modelname.find()` method with the `:count` argument. + + :::ruby + modelname.count + + +## create +Create a new Rhodes model object and save it to the database. + +**NOTE: This is the fastest way to insert a single item into the database.** + + :::ruby + modelname.create(attributes) + + + + + + +
                                                                  attributesList of attributes assigned to the new model object, such as {"name" => "ABC Inc.","address" => "555 5th St."}.
                                                                  + +### Example +Create a new rhom object and save to the database. + + :::ruby + @account = Account.create( + {"name" => "some new record", "industry" => "electronics"} + ) + + +## database_export +Creates a zip archive of a local database partition with all its blob objects, and returns a path to that zip archive. + + :::ruby + Rhom::Rhom.database_export(partition) + + + + + + +
                                                                  partitiona local database partition.
                                                                  + + +## database_fullclient_reset_and_logout +Reset the Rhodes model database and logout. Equivalent to `Rhom::Rhom.database_full_reset(true)` followed by `SyncEngine.logout`. + +**NOTE: If you receive a sync error "Unknown client" message in your sync callback, this means that the RhoConnect server no longer knows about the client and a `Rhom::Rhom.database_fullclient_reset_and_logout` is recommended. This error requires proper intervention in your app so you can handle the state before resetting the client. For example, your sync notification could contain the following:** + + :::ruby + if @params['error_message'].downcase == 'unknown client' + puts "Received unknown client, resetting!" + Rhom::Rhom.database_fullclient_reset_and_logout + end + + +## database_full_reset +Deletes all records from the property bag and model tables. + + :::ruby + Rhom::Rhom.database_full_reset(reset_client_info, reset_local_models) + + + + + + + + + + +
                                                                  reset_client_infotrue to clean the client_info table, false otherwise.
                                                                  reset_local_modelstrue to clean local (non-synced) models, false otherwise.
                                                                  + + +## database_full_reset_and_logout +Perform a full reset, then logout the RhoConnect client. + + :::ruby + Rhom::Rhom.database_full_reset_and_logout + + +## database_import +Imports the database and blob objects from a zip archive created with `database_export`. If the imported archive is inconsistent, or other failure occurs during the import process, the original database will be restored. + + :::ruby + Rhom::Rhom.database_import(partition, path_to_zip) + + + + + + + + + + +
                                                                  partitionthe local database partition to be replaced by the zip.
                                                                  path_to_zippath to the zip archive created with database_export.
                                                                  + + +## database_local_reset +Reset only local (non-sync-enabled) models. + + :::ruby + Rhom::Rhom.database_local_reset + + +## delete_all +Delete all Rhodes model objects for a source, filtering by conditions. + + :::ruby + modelname.delete_all(:conditions, :op) + + + + + + + + + + +
                                                                  :conditions(optional) hash of attribute/values; delete only objects matching these criteria, such as :conditions => {'industry'=>'electronics'}.
                                                                  :op(optional) operator, such as "OR" or "IN". Allows you to have more than one set of conditions.
                                                                  + + +## destroy +Destroy a Rhodes model object. + + :::ruby + modelname.destroy + +### Examples +Deletes all rhom objects for a source, optionally filtering by conditions: + + :::ruby + # :conditions Delete only objects matching these criteria. + # Supports find() conditions. + # :op See advanced find syntax + Account.delete_all(:conditions => {'industry'=>'electronics'}) + +Delete a rhom object. + + :::ruby + @account = Account.find(:all).first + @account.destroy + + + +## find +Find Rhodes model objects. + + :::ruby + modelname.find(argument list) + +The argument list can consist of the following arguments. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                  :allreturns all objects; can use optional :conditions.
                                                                  :firstreturns first object matching :conditions.
                                                                  :countreturns the number of objects matching these :conditions.
                                                                  :conditions(optional) hash of attribute/values. Also supports sql fragments (i.e. "name like 'rhomobile'") or sql fragment with binding (you have to define :select with sql queries) (i.e. ["name like ?", "'#{company#}'"]) Use a comma around string values.
                                                                  :order(optional) attribute(s) to order the list.
                                                                  :orderdir(optional) Order direction: 'ASC' ascending, 'DESC' descending. Default = 'ASC'.)
                                                                  :select(optional) array of string attributes to return with the object. Useful if your model has many attributes and your query only needs a few of them.
                                                                  :per_page(optional) maximum number of items to return.
                                                                  :offset(optional) offset from beginning of the list.
                                                                  :op(optional) operator, such as "OR" or "IN". Allows you to have more than one set of conditions.
                                                                  + +### Examples +Find Rhom objects.. Also see [Advanced queries](#advanced-queries) + + :::ruby + acct = Account.find "3560c0a0-ef58-2f40-68a5-48f39f63741b" + + acct.name + #=> "A.G. Parr PLC 37862" + + accts = Account.find(:all, :select => ['name','address']) + + accts[0].name + #=> "A.G. Parr PLC 37862" + + accts[0].telephone + #=> nil + +**NOTE: Use SQL fragments with caution. They are considerably slower than advanced queries [described below](#advanced-queries). You also have to specify :select parameter.** + +#### Order Examples +The `:order` argument for `find` accepts several forms. + +`:order` by one attribute. + + :::ruby + @accts = Account.find( + :all, + :order => 'name', + :orderdir => 'DESC' + ) + +`:order` by one attribute with a block. + + :::ruby + @accts = Account.find(:all, :order => 'name') do |x,y| + y <=> x + end + +`:order` with a block. + + :::ruby + @accts = Account.find(:all) do |item1,item2| + item2.name <=> item1.name + end + +`:order` by multiple attributes. + + :::ruby + @accts = Account.find( + :all, + :order => ['name', 'industry'], + :orderdir => ['ASC', 'DESC'] + ) + +`find_by_sql(sql_query)` returns rhom object(s) based on sql_query. This method works only for schema models. + + :::ruby + @accts = Account.find_by_sql("SELECT * FROM Account") + + + +## find_all +Alias for modelname.find(:all, argument list). + + +## find_by_sql +Returns Rhodes model object(s) based on sql_query. This method works only for schema models. + + :::ruby + modelname.find_by_sql(sql_query) + + + + + + +
                                                                  sql_queryAn sql query, such as "SELECT * FROM Account".
                                                                  + + +## get_source_id +Returns the source id number for this Rhodes model object. + + :::ruby + modelname.get_source_id + + +## get_source_name +Returns the source name for this Rhodes model object. + + :::ruby + modelname.get_source_name + + +## metadata +Returns the [metadata definition](../rhoconnect/metadata#metadata-definition) for a given model as a hash. + + :::ruby + Product.metadata + #=> {'foo' => 'bar'} + +### Example +Returns the [metadata](../rhoconnect/metadata) for a given model. + + :::ruby + Product.metadata + #=> {'foo' => 'bar'} + +Assigns the [metadata](../rhoconnect/metadata) for a given model. + + :::ruby + Product.metadata = { 'foo' => 'bar' }.to_json + + +## metadata=(metadata_def) +Assigns the JSON [metadata definition](../rhoconnect/metadata#metadata-definition) for a given model. + + :::ruby + Product.metadata = { 'foo' => 'bar' }.to_json + + + + + + +
                                                                  metadata_defJSON string of the metadata definition
                                                                  + + +## new +Create a new Rhodes model object. + :::ruby + modelname.new(attributes) + + + + + + +
                                                                  attributesList of attributes assigned to the new model object, such as {"name" => "ABC Inc.","address" => "555 5th St."}.
                                                                  + +### Example +Create a new rhom object and assign given attributes. + + :::ruby + @account = Account.new( + {"name" => "ABC Inc.","address" => "555 5th St."} + ) + @account.name + #=> "ABC Inc." + + +## paginate +Call `find` with a limit on the number of records. Default page size is 10. + + :::ruby + modelname.paginate(*arguments) + +The *arguments you can use are: + + + + + + + + + + + + + + + + + + + + + +
                                                                  :pagewhich page to return.
                                                                  :per_pagewith :page (used as offset), the number of records to return, such as :page => 1, :per_page => 20 +
                                                                  :conditionssame as find with :conditions
                                                                  :ordersame as find with :order
                                                                  :selectsame as find with :select
                                                                  + +### Example +Paginate calls `find` with a limit on the # of records. This emulates rails' classic pagination syntax. Default page size is 10. + + Account.paginate(:page => 0) + #=> returns first 10 records + Account.paginate(:page => 1, :per_page => 20) + #=> returns records 21-40 + Account.paginate( + :page => 5, + :conditions => {'industry' => 'Technology'}, + :order => 'name' + ) #=> you can have :conditions and :order as well + + +## push_changes +Force the sending of local changes to the RhoConnect server. + +NOTE: This method is available in Ruby only. + + :::ruby + modelname.push_changes() + +This method can be used even when there are no pending changes, to artificially put the client into a state where it sends a POST request to the server on the next sync (even if it is an empty sync). An empty POST method is useful because if there is something left in the CRUD queue in the server, it will be forced to be processed. For example: + +1. Five records are created on the client. +2. 1st sync, five records are sent to RhoConnect, all of those records are marked as sent on the client. +3. RhoConnect starts processing the records on the server and 3rd record is thrown out (for some reason) by the back-end. +4. RhoConnect sends 1st & 2nd record as processed and also sends `create-error` with 3rd record and PUSHES remaining records, 4th & 5th, back into the server queue. +5. After that, if you choose to use the `:delete` action, there are no more pending changes on the client. The 4th & 5th records were sent and no error was received, so the client assumes it will receive the records later, maybe as a postponed job. +6. So, if you just trigger Sync now on the client, the 4th & 5th records won't be processed on server still because, in order to process the queue there should be a POST method and Sync will send POST method **only** if there are new changes and, as it stands, there are none. +7. So, to force the server to process the remainder of the queue, you can use the `push_changes` method. This will force a POST method to be sent in the next sync (even if there are no changes) and will, in turn, force queue to be processed on the server. + + +## sync +Start the sync process for a Rhodes model. + + :::ruby + modelname.sync(callback_url, callback_data, show_status_popup, query_params) + + + + + + + + + + + + + + + + + + +
                                                                  callback_urlthe url for the sync callback method. If this is used, SyncEngine.set_notification is called before SyncEngine.dosync.
                                                                  callback_dataData for the callback method.
                                                                  show_status_popuptrue if you want to show a popup window upon sync, false otherwise.
                                                                  query_paramsOptional. a query to pass to the sync server. The query_params value must be URL encoded.
                                                                  + +### Example +Start the sync process for a model. In this example, the value for @params["sku"] -- the value of the sku -- must be URL encoded. + + :::ruby + Product.sync( url_for(:action => :sync_callback), "", false, "query=#{@params["sku"]}" ) + +Set a notification to be called when the sync is complete for this model. This is useful for example if you want to refresh the current list page or display an alert when new data is synchronized. See the [sync notification docs](../guide/using_rhoconnect#setting-up-notifications) for more information. + + :::ruby + Account.set_notification( url_for(:action => :sync_notify), "") + + +## save +Saves the current Rhodes model object to the database. + :::ruby + modelname.save + + +## set_notification +Set a notification to be called when the sync is complete for this model. + + :::ruby + modelname.set_notification(callback_url, params) + + + + + + + + + + +
                                                                  callback_urlthe url for your sync is finished notification callback method.
                                                                  paramsparameters for the callback method.
                                                                  + + +## update_attributes +Updates the current Rho model object attributes and saves it to the database. This is the fastest way to add or update model attributes. + + :::ruby + modelname.update_attributes(attributes) + + + + + + +
                                                                  attributesList of attributes and their updated values, such as {"name" => "ABC Inc.","address" => "555 5th St."}.
                                                                  + +### Example +Update the current rhom object's attributes and saves it to the database. + +**NOTE: This is the fastest way to add or update item attributes.** + + :::ruby + @account = Account.find( + :all, + :conditions => {'name' => 'ABC Inc.'} + ) + @account.update_attributes( + {"name" => "ABC Inc.", "industry" => "Technology"} + ) + @account.industry + #=> "Technology" + +Saves the current rhom object to the database. + + :::ruby + @account = Account.new( + {"name" => "some new record", "industry" => "electronics"} + ) + @account.save + + +## Advanced Queries +### `find(*args)` (advanced conditions) +Rhom also supports advanced find `:conditions`. Using advanced `:conditions`, rhom can optimize the query for the property bag table. + +Let's say we have the following SQL fragment condition: + + :::ruby + Product.find( + :all, + :conditions => [ + "LOWER(description) like ? or LOWER(title) like ?", + query, + query + ], + :select => ['title','description'] + ) + +Using advanced `:conditions`, this becomes: + + :::ruby + Product.find( + :all, + :conditions => { + { + :func => 'LOWER', + :name => 'description', + :op => 'LIKE' + } => query, + { + :func => 'LOWER', + :name => 'title', + :op => 'LIKE' + } => query + }, + :op => 'OR', + :select => ['title','description'] + ) + +You can also use the 'IN' operator: + + :::ruby + Product.find( + :all, + :conditions => { + { + :name => "image_uri", + :op => "IN" + } => "'15704','15386'" + } + ) + + # or use array notation + Product.find( + :all, + :conditions => { + { + :name => "image_uri", + :op => "IN" + } => ["15704","15386"] + } + ) + +You can also group `:conditions`: + + :::ruby + cond1 = { + :conditions => { + { + :func => 'UPPER', + :name => 'name', + :op => 'LIKE' + } => query, + { + :func => 'UPPER', + :name => 'industry', + :op => 'LIKE' + } => query + }, + :op => 'OR' + } + + cond2 = { + :conditions => { + { + :name => 'description', + :op => 'LIKE' + } => 'Hello%' + } + } + + @accts = Account.find( + :all, + :conditions => [cond1, cond2], + :op => 'AND', + :select => ['name','industry','description'] + ) + + +## Find by numeric field +To use number comparison conditions in find use CAST : + + :::ruby + @accts = Account.find(:all, + :conditions => { {:func=> 'CAST', :name=>'rating as INTEGER', :op=>'<'} => 3 } ) + #or using sql query: + size = 3 + @accts = Account.find(:all, + :conditions => ["CAST(rating as INTEGER)< ?", "#{size}"], :select => ['rating'] ) \ No newline at end of file diff --git a/docs/en/5.5/api/screenorientation.md b/docs/en/5.5/api/screenorientation.md new file mode 100644 index 00000000..99126e78 --- /dev/null +++ b/docs/en/5.5/api/screenorientation.md @@ -0,0 +1,120 @@ +#ScreenOrientation +
                                                                  +

                                                                  The ScreenOrientation Module is used to control the screen orientation / layout and register to receive an event when it changes.

                                                                  +

                                                                  Enabling the API

                                                                  + +

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

                                                                  + +
                                                                  :::ruby
                                                                  +extensions: ["screenorientation"]
                                                                  +
                                                                  + +

                                                                  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.

                                                                  + +

                                                                  Persistence

                                                                  + +

                                                                  With the old PocketBrowser / RhoElements 1 APIs, any events, such as screenOrientationEvent were canceled when a full navigate was performed. The original reason for this was a limitation of the IE engine on WM5 devices. When moving to the common API this was changed so that callbacks are not canceled.

                                                                  + + + +

                                                                  Methods

                                                                  + +

                                                                  leftHanded()

                                                                  Sets the screen orientation to left-handed orientation. Note the webpage will not reformat in line with the new screen size automatically.

                                                                  +

                                                                  Synchronous Return:

                                                                  • Void

                                                                  Method Access:

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

                                                                  normal()

                                                                  Sets the screen orientation to default device orientation.

                                                                  +

                                                                  Synchronous Return:

                                                                  • Void

                                                                  Method Access:

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

                                                                  rightHanded()

                                                                  Sets the screen orientation to right-handed orientation. Note the webpage will not reformat in line with the new screen size automatically.

                                                                  +

                                                                  Synchronous Return:

                                                                  • Void

                                                                  Method Access:

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

                                                                  setScreenOrientationEvent(CallBackHandler callback)

                                                                  Sets the callback to be called when a screen orientation event occurs.

                                                                  +

                                                                  Parameters

                                                                  • callback : CallBackHandler Mandatory

                                                                  Async Callback Returning Parameters: STRING

                                                                    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.ScreenOrientation.setScreenOrientationEvent(CallBackHandler callback)
                                                                      • Ruby: Rho::ScreenOrientation.setScreenOrientationEvent(CallBackHandler callback)

                                                                    upsideDown()

                                                                    Sets the screen orientation to upside down, useful if presenting the device to a customer to obtain a signature.

                                                                    +

                                                                    Synchronous Return:

                                                                    • Void

                                                                    Method Access:

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

                                                                    Properties

                                                                    + +

                                                                    autoRotate : BOOLEAN

                                                                    Enables or Disables auto-rotation of the screen orientation when the device is rotated. For Windows Mobile/CE devices, support is limited to only Symbol Technologies devices with IST Sensor support.

                                                                    +

                                                                    Default: true

                                                                    Property Access:

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

                                                                    Examples

                                                                    + +
                                                                    Detect screen orientation changes
                                                                    +

                                                                    Detect when the device changes orientation.

                                                                    +
                                                                    :::javascript
                                                                    +
                                                                    +function start_detecting_orientation_changes(){
                                                                    +  ScreenOrientation.setScreenOrientationEvent(orientation_callback)
                                                                    +}
                                                                    +
                                                                    +function orientation_callback(){
                                                                    +
                                                                    +  Alert.show_popup("The screen changed orientation")
                                                                    +}
                                                                    +                   
                                                                    +                            
                                                                    :::ruby
                                                                    +
                                                                    +def start_detecting_orientation_changes
                                                                    +  Rho::ScreenOrientation.setScreenOrientationEvent(url_for(:action => :orientation_callback))
                                                                    +end
                                                                    +
                                                                    +def orientation_callback
                                                                    +  Alert.show_popup("The screen changed orientation")
                                                                    +end
                                                                    +
                                                                    +                            
                                                                    Change screen orientation
                                                                    +

                                                                    Set the screen orientation programmatically. Particularly useful in a tablet: before capturing a signature, set the orientation to upside-down so that the interface will look right from the signer’s point of view without having to physically rotate the device.

                                                                    +
                                                                    :::javascript
                                                                    +
                                                                    +function capture_signature_with_attention_to_details() {
                                                                    +    // Set screen orientation to upside down
                                                                    +    Rho.ScreenOrientation.upsideDown();
                                                                    +
                                                                    +    // At this point, offer the device to the user. You just saved the user the hassle of rotating the tablet
                                                                    +    // and there's less potential for the device to be dropped along the way
                                                                    +    Rho.Signature.takeFullScreen({}, signature_callback);
                                                                    +}
                                                                    +
                                                                    +function signature_callback(params) {
                                                                    +    // do whatever we need to do with the signature
                                                                    +    ...
                                                                    +    // restore screen orientation to default
                                                                    +    Rho.ScreenOrientation.normal();
                                                                    +}
                                                                    +                   
                                                                    +                            
                                                                    :::ruby
                                                                    +
                                                                    +def capture_signature_with_attention_to_details
                                                                    +    # Set screen orientation to upside down
                                                                    +    Rho::ScreenOrientation.upsideDown
                                                                    +    # At this point, offer the device to the user. You just saved the user the hassle of rotating the tablet
                                                                    +    # and there's less potential for the device to be dropped along the way
                                                                    +    Rho::Signature.takeFullScreen({}, url_for(:action => :signature_callback))
                                                                    +end
                                                                    +
                                                                    +def signature_callback
                                                                    +    # do whatever we need to do with the signature
                                                                    +    ...
                                                                    +    # restore screen orientation to default
                                                                    +    Rho::ScreenOrientation.normal
                                                                    +end
                                                                    +                   
                                                                    +                            
                                                                    Enable / disable auto rotate
                                                                    +

                                                                    Enable / disable automatic rotation of the screen according to device orientation.

                                                                    +
                                                                    :::javascript
                                                                    +
                                                                    +// Enable autorotate
                                                                    +Rho.ScreenOrientation.autoRotate=true;
                                                                    +
                                                                    +// Disable autorotate
                                                                    +Rho.ScreenOrientation.autoRotate=false;
                                                                    +                   
                                                                    +                            
                                                                    :::ruby
                                                                    +
                                                                    +# Enable autorotate
                                                                    +Rho::ScreenOrientation.autoRotate=true
                                                                    +
                                                                    +# Disable autorotate
                                                                    +Rho::ScreenOrientation.autoRotate=false
                                                                    +                   
                                                                    +                            
                                                                    \ No newline at end of file diff --git a/docs/en/5.5/api/screenorientation.xml b/docs/en/5.5/api/screenorientation.xml new file mode 100644 index 00000000..a854efb0 --- /dev/null +++ b/docs/en/5.5/api/screenorientation.xml @@ -0,0 +1,281 @@ + + + + + The ScreenOrientation Module is used to control the screen orientation / layout and register to receive an event when it changes. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + :::ruby + extensions: ["screenorientation"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + +## Persistence +With the old PocketBrowser / RhoElements 1 APIs, any events, such as `screenOrientationEvent` were canceled when a full navigate was performed. The original reason for this was a limitation of the IE engine on WM5 devices. When moving to the common API this was changed so that callbacks are not canceled. + + +## Enabling the API +There are two methods of enabling the ScreenOrientation API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the ScreenOrientation API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.screenorientation.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + +## Persistence +With the old PocketBrowser APIs, any events, such as `screenOrientationEvent` were canceled when a full navigate was performed. The original reason for this was a limitation of the IE engine on WM5 devices. When moving to the common API this was changed so that callbacks are not canceled. + + + Properties used to configure Screen Orientation module. + + Enables or Disables auto-rotation of the screen orientation when the device is rotated. For Windows Mobile/CE devices, support is limited to only Symbol Technologies devices with IST Sensor support. + iOS, Android, WM + Android, WM + + + + + + Sets the screen orientation to default device orientation. + Android, WM + + + + Sets the screen orientation to right-handed orientation. Note the webpage will not reformat in line with the new screen size automatically. + Android, WM + + + + Sets the screen orientation to left-handed orientation. Note the webpage will not reformat in line with the new screen size automatically. + Android, WM + + + + Sets the screen orientation to upside down, useful if presenting the device to a customer to obtain a signature. + Android, WM + + + + Sets the callback to be called when a screen orientation event occurs. + iOS, Android, WM + Android, WM + + Current orientation of the screen. The orientation is reported as normal, leftHanded, rightHanded or upsideDown. If auto rotation is disabled in the device - real rotating of device do not produce an event. The event occurs only for real changing of screen orientation, also "upsideDown" Method shall behave like "normal" Method. + + + + + + + + + + 4.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + +
                                                                    + Detect when the device changes orientation. + + :orientation_callback)) +end + +def orientation_callback + Alert.show_popup("The screen changed orientation") +end +]]> + + + + +
                                                                    +
                                                                    +
                                                                    + + + +
                                                                    + Set the screen orientation programmatically. Particularly useful in a tablet: before capturing a signature, set the orientation to upside-down so that the interface will look right from the signer's point of view without having to physically rotate the device. + + :signature_callback)) +end + +def signature_callback + # do whatever we need to do with the signature + ... + # restore screen orientation to default + Rho::ScreenOrientation.normal +end + ]]> + + + + +
                                                                    +
                                                                    +
                                                                    + + + +
                                                                    + Enable / disable automatic rotation of the screen according to device orientation. + + + + + + +
                                                                    +
                                                                    +
                                                                    +
                                                                    + + + + +
                                                                    + In this example you'll see how to manipulate the screen orientation and how to receive events when the orientation changes. This example assumes that the ebapi-modules.js file resides in the same folder as the HTML file invoking it. + + + + + ScreenOrientation API Test + + + + + +

                                                                    ScreenOrientation API Test

                                                                    +
                                                                    + Orientation: +
                                                                    +
                                                                    + Auto Rotate: Enabled +
                                                                    +
                                                                    + +

                                                                    +
                                                                    + +
                                                                    +
                                                                    +
                                                                    + + ]]> +
                                                                    +
                                                                    +
                                                                    +
                                                                    +
                                                                    +
                                                                    + +
                                                                    +
                                                                    diff --git a/docs/en/5.5/api/sensor.md b/docs/en/5.5/api/sensor.md new file mode 100644 index 00000000..6d9e56c0 --- /dev/null +++ b/docs/en/5.5/api/sensor.md @@ -0,0 +1,149 @@ +#Sensor +
                                                                    +

                                                                    The Sensors extension is used to retrieve the raw data values of the specified sensors (accelerometer, tilt angle, device orientation, motion, eCompass, magnetometer, gyroscope, ambient light, proximity, proximity long range, pressure, temperature, humidity, gravity, linear acceleration, rotation, orientation etc.) from the device. To use this, you have to first call makeSensorByType to get an instance of that sensor. Then you can use the start and stop methods on that instance.

                                                                    +

                                                                    Enabling the API

                                                                    + +

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

                                                                    + +
                                                                    :::ruby
                                                                    +extensions: ["sensor"]
                                                                    +
                                                                    + +

                                                                    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

                                                                    + +

                                                                    getAllProperties(CallBackHandler callback)

                                                                    This method will return all of object/value pairs for the propertyNames of the API class.

                                                                    +

                                                                    Parameters

                                                                    • callback : CallBackHandler Optional

                                                                    Async Callback Returning Parameters: HASH

                                                                      • : STRING

                                                                    Synchronous Return:

                                                                    • HASH :

                                                                      Map of all available properties

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

                                                                    Method Access:

                                                                    • Instance Method: This method can be accessed via an instance object of this class:
                                                                      • myObject.getAllProperties(CallBackHandler callback)

                                                                    getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                    This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                                                                    +

                                                                    Parameters

                                                                    • arrayofNames : ARRAY

                                                                      List of properties I want to know about

                                                                      +

                                                                      • Object : STRING

                                                                    • callback : CallBackHandler Optional

                                                                    Async Callback Returning Parameters: HASH

                                                                      • : STRING

                                                                    Synchronous Return:

                                                                    • HASH :

                                                                      Map of properties I want to know about

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

                                                                    Method Access:

                                                                    • Instance Method: This method can be accessed via an instance object of this class:
                                                                      • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                    getProperty(STRING propertyName, CallBackHandler callback)

                                                                    This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                                                                    +

                                                                    Parameters

                                                                    • propertyName : STRING

                                                                      The property to return info about.

                                                                      +

                                                                    • callback : CallBackHandler Optional

                                                                    Async Callback Returning Parameters: STRING

                                                                      Synchronous Return:

                                                                      • STRING :

                                                                        The property to return info about.

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

                                                                      Method Access:

                                                                      • Instance Method: This method can be accessed via an instance object of this class:
                                                                        • myObject.getProperty(STRING propertyName, CallBackHandler callback)

                                                                      makeSensorByType(STRING type)

                                                                      Return the new sensor object by type.

                                                                      +

                                                                      Parameters

                                                                      • type : STRING

                                                                        Sensor type. Use the appropriate constants to get the sensor type. In the case of accelerometer use SENSOR_TYPE_ACCELEROMETER.

                                                                        +

                                                                      Synchronous Return:

                                                                      • SELF_INSTANCE :

                                                                        Returns a sensor object for the sensor type passed as parameter. You can use the type field along with the Rho.Sensor Constants to see what type of sensor is returned.

                                                                        +

                                                                      Method Access:

                                                                      • Class Method: This method can only be accessed via the API class object.
                                                                        • JavaScript: Rho.Sensor.makeSensorByType(STRING type)
                                                                        • Ruby: Rho::Sensor.makeSensorByType(STRING type)

                                                                      readData()

                                                                      Read current sensor data from the sensor object retrieved by using makeSensorByType.

                                                                      +

                                                                      Synchronous Return:

                                                                      • HASH :

                                                                        Current sensor data – format is the same with callback specified for start method.

                                                                        +

                                                                      Method Access:

                                                                      • Instance Method: This method can be accessed via an instance object of this class:
                                                                        • myObject.readData()

                                                                      setProperties(HASH propertyMap)

                                                                      This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                      +

                                                                      Parameters

                                                                      • propertyMap : HASH

                                                                        Map of properties I want to set

                                                                        +

                                                                        • Object : STRING

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

                                                                      • Instance Method: This method can be accessed via an instance object of this class:
                                                                        • myObject.setProperties(HASH propertyMap)

                                                                      setProperty(STRING propertyName, STRING propertyValue)

                                                                      This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                      +

                                                                      Parameters

                                                                      • propertyName : STRING

                                                                        The one property name that I want to set

                                                                        +

                                                                      • propertyValue : STRING

                                                                        The one property value that I want to set

                                                                        +

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

                                                                      • Instance Method: This method can be accessed via an instance object of this class:
                                                                        • myObject.setProperty(STRING propertyName, STRING propertyValue)

                                                                      start(CallBackHandler callback)

                                                                      This enables the sensor data retrieval. Call start on the instance returned from the makeSensorByType.

                                                                      +

                                                                      Parameters

                                                                      • callback : CallBackHandler Optional

                                                                      Async Callback Returning Parameters: HASH

                                                                        • status : STRING

                                                                          Status: ok, error.

                                                                          +

                                                                        • message : STRING

                                                                          Only if status=error, contain error message.

                                                                          +

                                                                        • accelerometer_x : FLOAT

                                                                          X co-ordinate value of the Accelerometer sensor in SI units (m/s2)

                                                                          +

                                                                        • accelerometer_y : FLOAT

                                                                          Y co-ordinate value of the Accelerometer sensor in SI units (m/s2)

                                                                          +

                                                                        • accelerometer_z : FLOAT

                                                                          Z co-ordinate value of the Accelerometer sensor in SI units (m/s2)

                                                                          +

                                                                        • tiltangle_x : FLOAT

                                                                          X co-ordinate value of the tiltangle sensor in degrees units.

                                                                          +

                                                                        • tiltangle_y : FLOAT

                                                                          Y co-ordinate value of the tiltangle sensor in degrees units.

                                                                          +

                                                                        • tiltangle_z : FLOAT

                                                                          Z co-ordinate value of the tiltangle sensor in degrees units.

                                                                          +

                                                                        • deviceorientation_value : STRING

                                                                          The values of the Orientation sensor. Possible values include Portrait Down, Portrait Up, Landscape Left, Landscape Right, Face Up, Face Down. Applicable only for Symbol Windows Mobile/CE devices with Sensor support.

                                                                          +

                                                                        • motion_value : STRING

                                                                          Value from the Motion sensor.

                                                                          +

                                                                        • ecompass_value : STRING

                                                                          Value from the E-Compass sensor.

                                                                          +

                                                                        • magnetometer_x : FLOAT

                                                                          X value of the magnetometer sensor in micro-Tesla (uT) units.

                                                                          +

                                                                        • magnetometer_y : FLOAT

                                                                          Y value of the magnetometer sensor in micro-Tesla (uT) units.

                                                                          +

                                                                        • magnetometer_z : FLOAT

                                                                          Z value of the magnetometer sensor in micro-Tesla (uT) units.

                                                                          +

                                                                        • gyroscope_x : FLOAT

                                                                          X co-ordinate value of the gyroscope sensor in radians/second.

                                                                          +

                                                                        • gyroscope_y : FLOAT

                                                                          X co-ordinate value of the gyroscope sensor in radians/second.

                                                                          +

                                                                        • gyroscope_z : FLOAT

                                                                          X co-ordinate value of the gyroscope sensor in radians/second.

                                                                          +

                                                                        • ambientlight_value : STRING

                                                                          Value of the ambient Light sensor in SI lux units.

                                                                          +

                                                                        • proximity_value : STRING

                                                                          Value of the proximity sensor in centimeters.

                                                                          +

                                                                        • proximitylongrange_value : STRING

                                                                          Value of the proximitylongrange sensor.

                                                                          +

                                                                        • pressure_value : STRING

                                                                          Value of the pressure sensor in hPa (millibar) units.

                                                                          +

                                                                        • temperature_value : STRING

                                                                          Value of the temperature sensor in degree Celsius units.

                                                                          +

                                                                        • humidity_value : STRING

                                                                          Value of the humidity sensor as a percentage.

                                                                          +

                                                                        • gravity_x : FLOAT

                                                                          X co-ordinate value of the gravity sensor in SI units (m/s2)

                                                                          +

                                                                        • gravity_y : FLOAT

                                                                          Y co-ordinate value of the gravity sensor in SI units (m/s2)

                                                                          +

                                                                        • gravity_z : FLOAT

                                                                          Z co-ordinate value of the gravity sensor in SI units (m/s2)

                                                                          +

                                                                        • linearacceleration_x : FLOAT

                                                                          X co-ordinate value of the linear acceleration sensor in SI units (m/s2)

                                                                          +

                                                                        • linearacceleration_y : FLOAT

                                                                          Y co-ordinate value of the linear acceleration sensor in SI units (m/s2)

                                                                          +

                                                                        • linearacceleration_z : FLOAT

                                                                          Z co-ordinate value of the linear acceleration sensor in SI units (m/s2)

                                                                          +

                                                                        • rotation_x : FLOAT

                                                                          X co-ordinate value of the rotation sensor as a combination of an angle and an axis.

                                                                          +

                                                                        • rotation_y : FLOAT

                                                                          Y co-ordinate value of the rotation sensor as a combination of an angle and an axis.

                                                                          +

                                                                        • rotation_z : FLOAT

                                                                          Z co-ordinate value of the rotation sensor as a combination of an angle and an axis.

                                                                          +

                                                                        • orientation_x : FLOAT

                                                                          X co-ordinate value of the orientation sensor in degrees units.

                                                                          +

                                                                        • orientation_y : FLOAT

                                                                          Y co-ordinate value of the orientation sensor in degrees units.

                                                                          +

                                                                        • orientation_z : FLOAT

                                                                          Z co-ordinate value of the orientation sensor in degrees units.

                                                                          +

                                                                      Synchronous Return:

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

                                                                      Method Access:

                                                                      • Instance Method: This method can be accessed via an instance object of this class:
                                                                        • myObject.start(CallBackHandler callback)

                                                                      stop()

                                                                      Stops listening to the sensor retrieved by using makeSensorType. On Windows Mobile/CE its recommended to call stop on all retrieved sensor objects before exiting a page.

                                                                      +

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

                                                                      • Instance Method: This method can be accessed via an instance object of this class:
                                                                        • myObject.stop()
                                                                      + +

                                                                      Properties

                                                                      + +

                                                                      minimumGap : INTEGER

                                                                      The minimum amount of time gap between two sensor update events, specified in milliseconds. The interval cannot be set to less than 200 milliseconds, if a value of less than 200 milliseconds is specified, the interval will be defaulted to 200 milliseconds.

                                                                      +

                                                                      Default: 200

                                                                      Property Access:

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

                                                                      status : STRING Read Only

                                                                      Current status: not_ready, ready, started, error etc.

                                                                      +

                                                                      Property Access:

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

                                                                      type : STRING Read Only

                                                                      Type of current sensor: Accelerometer, Magnetometer, etc.

                                                                      +

                                                                      Property Access:

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

                                                                      Constants

                                                                      + +
                                                                      SENSOR_TYPE_ACCELEROMETER

                                                                      Accelerometer sensor type.

                                                                      +
                                                                      SENSOR_TYPE_TILT_ANGLE

                                                                      TiltAngle sensor type.

                                                                      +
                                                                      SENSOR_TYPE_DEVICE_ORIENTATION

                                                                      DeviceOrientation sensor type.

                                                                      +
                                                                      SENSOR_TYPE_MOTION

                                                                      Motion sensor type.

                                                                      +
                                                                      SENSOR_TYPE_ECOMPASS

                                                                      ECompass sensor type.

                                                                      +
                                                                      SENSOR_TYPE_MAGNETOMETER

                                                                      Magnetometer sensor type.

                                                                      +
                                                                      SENSOR_TYPE_GYROSCOPE

                                                                      Gyroscope sensor type.

                                                                      +
                                                                      SENSOR_TYPE_AMBIENT_LIGHT

                                                                      AmbientLight sensor type.

                                                                      +
                                                                      SENSOR_TYPE_PROXIMITY

                                                                      Proximity sensor type.

                                                                      +
                                                                      SENSOR_TYPE_PROXIMITY_LONG_RANGE

                                                                      ProximityLongRange sensor type.

                                                                      +
                                                                      SENSOR_TYPE_PRESSURE

                                                                      Pressure sensor type.

                                                                      +
                                                                      SENSOR_TYPE_TEMPERATURE

                                                                      Temperature sensor type.

                                                                      +
                                                                      SENSOR_TYPE_HUMIDITY

                                                                      Humidity sensor type.

                                                                      +
                                                                      SENSOR_TYPE_GRAVITY

                                                                      Gravity sensor type.

                                                                      +
                                                                      SENSOR_TYPE_LINEAR_ACCELERATION

                                                                      LinearAcceleration sensor type.

                                                                      +
                                                                      SENSOR_TYPE_ROTATION

                                                                      Rotation sensor type.

                                                                      +
                                                                      SENSOR_TYPE_ORIENTATION

                                                                      Orientation sensor type.

                                                                      +
                                                                      SENSOR_STATUS_NOT_READY

                                                                      Sensor is not ready for start – may be some type of sensor require time for initializing / calibrating of HW etc.

                                                                      +
                                                                      SENSOR_STATUS_READY

                                                                      Sensor is ready to start listening.

                                                                      +
                                                                      SENSOR_STATUS_STARTED

                                                                      Sensor already started to listening.

                                                                      +
                                                                      SENSOR_STATUS_ERROR

                                                                      Sensor in error state.

                                                                      +
                                                                      + +

                                                                      Examples

                                                                      + +
                                                                      Basic Example
                                                                      +

                                                                      The below example gets the Accelerometer values for every 500 milliseconds.

                                                                      +
                                                                      :::ruby
                                                                      +
                                                                      +#/app/Model
                                                                      +def index
                                                                      +    @accelerometer_sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_ACCELEROMETER)
                                                                      +    if @accelerometer_sensor != nil
                                                                      +        @accelerometer_sensor.minimumGap = 500
                                                                      +        @accelerometer_sensor.start(url_for(:action => :myevent))
                                                                      +    else
                                                                      +       puts "Warning: This device has not Accelerometer sensor !"
                                                                      +    end
                                                                      +end
                                                                      +
                                                                      +def stop_listening_accelerator
                                                                      +    if @accelerometer_sensor != nil
                                                                      +        @accelerometer_sensor.stop
                                                                      +    end
                                                                      +end
                                                                      +
                                                                      +def myevent
                                                                      +    puts "Accelerometer params: #{@params}"
                                                                      +    puts "X is #{@params['accelerometer_x']}"
                                                                      +    puts "Y is #{@params['accelerometer_y']}"
                                                                      +    puts "Z is #{@params['accelerometer_z']}"
                                                                      +end
                                                                      +                    
                                                                      +                            
                                                                      + +

                                                                      Remarks

                                                                      + +
                                                                      General

                                                                      As this extension returns the raw sensor values reported by the operating system the values might differ between platforms. Also as some of the sensor values change rapidly the minimum gap between two updates should be specified as a reasonable value, otherwise there can be a performance impact.

                                                                      +
                                                                      Supporting Sensors

                                                                      In Android, as supported sensors could vary from product to product so please refer to Device’s PRD/TRD for the list of supported sensors in that particular device.

                                                                      +
                                                                      \ No newline at end of file diff --git a/docs/en/5.5/api/sensor.xml b/docs/en/5.5/api/sensor.xml new file mode 100644 index 00000000..2ae273b3 --- /dev/null +++ b/docs/en/5.5/api/sensor.xml @@ -0,0 +1,389 @@ + + + + + The Sensors extension is used to retrieve the raw data values of the specified sensors (accelerometer, tilt angle, device orientation, motion, eCompass, magnetometer, gyroscope, ambient light, proximity, proximity long range, pressure, temperature, humidity, gravity, linear acceleration, rotation, orientation etc.) from the device. To use this, you have to first call makeSensorByType to get an instance of that sensor. Then you can use the start and stop methods on that instance. + + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + :::ruby + extensions: ["sensor"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + +## Enabling the API +There are two methods of enabling the Sensor API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Sensor API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.sensor.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + WM, CE, Android, iOS + Android, WM, CE + + + + + + + + + Accelerometer sensor type. + + + TiltAngle sensor type. + + + DeviceOrientation sensor type. + + + Motion sensor type. + + + ECompass sensor type. + + + Magnetometer sensor type. + + + Gyroscope sensor type. + + + AmbientLight sensor type. + + + Proximity sensor type. + + + ProximityLongRange sensor type. + + + Pressure sensor type. + + + Temperature sensor type. + + + Humidity sensor type. + + + Gravity sensor type. + + + LinearAcceleration sensor type. + + + Rotation sensor type. + + + Orientation sensor type. + + + + Sensor is not ready for start - may be some type of sensor require time for initializing / calibrating of HW etc. + + + Sensor is ready to start listening. + + + Sensor already started to listening. + + + Sensor in error state. + + + + + These properties are used to configure the Camera. + + + The minimum amount of time gap between two sensor update events, specified in milliseconds. The interval cannot be set to less than 200 milliseconds, if a value of less than 200 milliseconds is specified, the interval will be defaulted to 200 milliseconds. + + + + Type of current sensor: Accelerometer, Magnetometer, etc. + + + + Current status: not_ready, ready, started, error etc. + + + + + + Return the new sensor object by type. + + + Sensor type. Use the appropriate constants to get the sensor type. In the case of accelerometer use SENSOR_TYPE_ACCELEROMETER. + + + + Returns a sensor object for the sensor type passed as parameter. You can use the type field along with the Rho.Sensor Constants to see what type of sensor is returned. + + WM, CE, Android, iOS + Android, WM, CE + + + + This enables the sensor data retrieval. Call start on the instance returned from the makeSensorByType. + WM, CE, Android, iOS + Android, WM, CE + + The callback is triggered with the sensors values according to sensor type when a parameter of the sensor is changed. Each sensor sends to the callback different object types - see sensor prefix of value name. All sensors will contain a status and message parameter in the callback. + + + + Status: ok, error. + + + + Only if status=error, contain error message. + + + + + X co-ordinate value of the Accelerometer sensor in SI units (m/s^2) + + + + Y co-ordinate value of the Accelerometer sensor in SI units (m/s^2) + + + + Z co-ordinate value of the Accelerometer sensor in SI units (m/s^2) + + + + + X co-ordinate value of the tiltangle sensor in degrees units. + + + + Y co-ordinate value of the tiltangle sensor in degrees units. + + + + Z co-ordinate value of the tiltangle sensor in degrees units. + + + + + The values of the Orientation sensor. Possible values include Portrait Down, Portrait Up, Landscape Left, Landscape Right, Face Up, Face Down. Applicable only for Symbol Windows Mobile/CE devices with Sensor support. + + + + + Value from the Motion sensor. + + + + + Value from the E-Compass sensor. + + + + + X value of the magnetometer sensor in micro-Tesla (uT) units. + + + + Y value of the magnetometer sensor in micro-Tesla (uT) units. + + + + Z value of the magnetometer sensor in micro-Tesla (uT) units. + + + + + X co-ordinate value of the gyroscope sensor in radians/second. + + + + X co-ordinate value of the gyroscope sensor in radians/second. + + + + X co-ordinate value of the gyroscope sensor in radians/second. + + + + + Value of the ambient Light sensor in SI lux units. + + + + + Value of the proximity sensor in centimeters. + + + + + Value of the proximitylongrange sensor. + + + + + Value of the pressure sensor in hPa (millibar) units. + + + + + Value of the temperature sensor in degree Celsius units. + + + + + Value of the humidity sensor as a percentage. + + + + + X co-ordinate value of the gravity sensor in SI units (m/s^2) + + + + Y co-ordinate value of the gravity sensor in SI units (m/s^2) + + + + Z co-ordinate value of the gravity sensor in SI units (m/s^2) + + + + + X co-ordinate value of the linear acceleration sensor in SI units (m/s^2) + + + + Y co-ordinate value of the linear acceleration sensor in SI units (m/s^2) + + + + Z co-ordinate value of the linear acceleration sensor in SI units (m/s^2) + + + + + X co-ordinate value of the rotation sensor as a combination of an angle and an axis. + + + + Y co-ordinate value of the rotation sensor as a combination of an angle and an axis. + + + + Z co-ordinate value of the rotation sensor as a combination of an angle and an axis. + + + + + X co-ordinate value of the orientation sensor in degrees units. + + + + Y co-ordinate value of the orientation sensor in degrees units. + + + + Z co-ordinate value of the orientation sensor in degrees units. + + + + + + + Read current sensor data from the sensor object retrieved by using makeSensorByType. + + Current sensor data - format is the same with callback specified for start method. + > + WM, CE, Android, iOS + Android, WM, CE + + + + Stops listening to the sensor retrieved by using makeSensorType. On Windows Mobile/CE its recommended to call stop on all retrieved sensor objects before exiting a page. + WM, CE, Android, iOS + Android, WM, CE + + + + 2.0.0 + Android, WM, iOS + Android, WM + + + + As this extension returns the raw sensor values reported by the operating system the values might differ between platforms. Also as some of the sensor values change rapidly the minimum gap between two updates should be specified as a reasonable value, otherwise there can be a performance impact. + + + In Android, as supported sensors could vary from product to product so please refer to Device's PRD/TRD for the list of supported sensors in that particular device. + + + + + + +
                                                                      + The below example gets the Accelerometer values for every 500 milliseconds. + + :myevent)) + else + puts "Warning: This device has not Accelerometer sensor !" + end +end + +def stop_listening_accelerator + if @accelerometer_sensor != nil + @accelerometer_sensor.stop + end +end + +def myevent + puts "Accelerometer params: #{@params}" + puts "X is #{@params['accelerometer_x']}" + puts "Y is #{@params['accelerometer_y']}" + puts "Z is #{@params['accelerometer_z']}" +end + ]]> + + +
                                                                      +
                                                                      +
                                                                      +
                                                                      +
                                                                      +
                                                                      \ No newline at end of file diff --git a/docs/en/5.5/api/signalindicators.md b/docs/en/5.5/api/signalindicators.md new file mode 100644 index 00000000..d0fac079 --- /dev/null +++ b/docs/en/5.5/api/signalindicators.md @@ -0,0 +1,170 @@ +#SignalIndicators +
                                                                      +

                                                                      The Signal API is used to notify the user of the strength of the WLAN signal. For Windows Mobile / CE, only Symbol devices are supported and it is also possible to display a small indicator showing the available signal. The WLAN signal strength is not available on Windows Phone 8 and therefore this API is not supported on that platform.

                                                                      +

                                                                      Enabling the API

                                                                      + +

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

                                                                      + +
                                                                      :::ruby
                                                                      +extensions: ["indicators"]
                                                                      +
                                                                      + +

                                                                      The indicators extension is also included automatically if you specify the following in your build.yml.

                                                                      + +
                                                                      :::ruby
                                                                      +app_type: "rhoelements"
                                                                      +
                                                                      + +

                                                                      Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

                                                                      + +

                                                                      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

                                                                      + +

                                                                      hideIcon()

                                                                      Hide the icon if it has been previously set by the ‘showIcon’ call.

                                                                      +

                                                                      (All platforms support wlanStatus which can be used to draw your own level indicator or display an appropriate graphic.)

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

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

                                                                      showIcon(HASH propertyMap)

                                                                      Overlays a small signal icon on top of the view indicating the remaining signal strength. This is particularly useful in full screen applications which cover the system signal level indicator.

                                                                      +

                                                                      (All platforms support wlanStatus which can be used to draw your own level indicator or display an appropriate graphic.)

                                                                      Parameters

                                                                      • propertyMap : HASH

                                                                        The properties associated with the indicator, its position and colour.

                                                                        +

                                                                        • left : INTEGER Default: [Top right of the screen]

                                                                          The absolute horizontal position of the indicator in pixels. This value is relative to the screen and not the view, so non-fullscreen applications should take care not to display the indicator off screen.

                                                                          +

                                                                        • top : INTEGER Default: [Top right of the screen]

                                                                          The absolute vertical position of the indicator in pixels. Positive numbers push the icon towards the bottom of the screen. The value is relative to the screen and not the view, so non-fullscreen applications should take care not to display the indicator off screen.

                                                                          +

                                                                        • layout : STRING Default: [Right]

                                                                          Sets the orientation of the icon, see the remarks section for illustrations.

                                                                          +

                                                                          Possible Values :

                                                                          Constant: Rho::SignalIndicators.SIGNAL_LAYOUT_LEFT (For Ruby use "::" for all "." when referencing constants)
                                                                          String:left

                                                                          See the remarks section for illustrations of icon layout

                                                                          +
                                                                          Constant: Rho::SignalIndicators.SIGNAL_LAYOUT_RIGHT (For Ruby use "::" for all "." when referencing constants)
                                                                          String:right

                                                                          See the remarks section for illustrations of icon layout

                                                                          +
                                                                          Constant: Rho::SignalIndicators.SIGNAL_LAYOUT_UP (For Ruby use "::" for all "." when referencing constants)
                                                                          String:up

                                                                          See the remarks section for illustrations of icon layout

                                                                          +
                                                                          Constant: Rho::SignalIndicators.SIGNAL_LAYOUT_DOWN (For Ruby use "::" for all "." when referencing constants)
                                                                          String:down

                                                                          See the remarks section for illustrations of icon layout

                                                                          +
                                                                        • color : STRING Default: #000000

                                                                          The color of the icon. This value must be specified as a Hex value in the format #000000 to #FFFFFF. Alpha values are not supported, i.e. you can only use the component parts RRGGBB.

                                                                          +

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

                                                                      • Class Method: This method can only be accessed via the API class object.
                                                                        • JavaScript: Rho.SignalIndicators.showIcon(HASH propertyMap)
                                                                        • Ruby: Rho::SignalIndicators.showIcon(HASH propertyMap)

                                                                      stopWlanStatus()

                                                                      If the signal is being retrieved via callback, by a previously invoked call to wlanStatus, this method will stop the callback from firing.

                                                                      +

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

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

                                                                      wlanStatus(CallBackHandler callback)

                                                                      Retrieve the current signal status. If a callback is provided to retrieve the signal then it will be called periodically at the specified refreshInterval. On Android, instead of being called periodically, the callback will be called when one of the below values changes.

                                                                      +

                                                                      Parameters

                                                                      • callback : CallBackHandler Optional

                                                                      Async Callback Returning Parameters: HASH

                                                                        • signalStrength : INTEGER

                                                                          The signal strength as a value between 0 and 100. Not supported on iOS

                                                                          + Platforms:WM, CE, Android

                                                                        • essid : STRING

                                                                          The current ESSID

                                                                          +

                                                                        • macAddress : STRING

                                                                          The Device’s MAC address

                                                                          +

                                                                        • adapterName : STRING

                                                                          The Device’s adapter name

                                                                          +

                                                                        • dhcpServer : STRING

                                                                          The current DHCP server’s address. Always populated on Android, even on static IP configurations. Not supported on iOS

                                                                          + Platforms:WM, CE, Android

                                                                        • dhcpStatic : STRING

                                                                          Whether the unit has a static or DHCP address. Not available on Android and iOS.

                                                                          + Platforms:WM

                                                                        • gateway : STRING

                                                                          The current gateway IP address

                                                                          +

                                                                        • ipAddress : STRING

                                                                          The device’s IP address

                                                                          +

                                                                        • rssi : STRING

                                                                          Signal strength in RSSI terms. Not supported on iOS.

                                                                          + Platforms:WM, CE, Android

                                                                        • subnetMask : STRING

                                                                          The current subnet mask

                                                                          +

                                                                        • wins : STRING

                                                                          The current WINs server IP address. Not available on Android and iOS.

                                                                          + Platforms:WM

                                                                      Synchronous Return:

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

                                                                          The signal strength as a value between 0 and 100. Not supported on iOS

                                                                          + Platforms:WM, CE, Android

                                                                        • essid : STRING

                                                                          The current ESSID

                                                                          +

                                                                        • macAddress : STRING

                                                                          The Device’s MAC address

                                                                          +

                                                                        • adapterName : STRING

                                                                          The Device’s adapter name

                                                                          +

                                                                        • dhcpServer : STRING

                                                                          The current DHCP server’s address. Always populated on Android, even on static IP configurations. Not supported on iOS

                                                                          + Platforms:WM, CE, Android

                                                                        • dhcpStatic : STRING

                                                                          Whether the unit has a static or DHCP address. Not available on Android and iOS.

                                                                          + Platforms:WM

                                                                        • gateway : STRING

                                                                          The current gateway IP address

                                                                          +

                                                                        • ipAddress : STRING

                                                                          The device’s IP address

                                                                          +

                                                                        • rssi : STRING

                                                                          Signal strength in RSSI terms. Not supported on iOS.

                                                                          + Platforms:WM, CE, Android

                                                                        • subnetMask : STRING

                                                                          The current subnet mask

                                                                          +

                                                                        • wins : STRING

                                                                          The current WINs server IP address. Not available on Android and iOS.

                                                                          + Platforms:WM

                                                                      Method Access:

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

                                                                      Properties

                                                                      + +

                                                                      refreshInterval : INTEGER 1.0.0

                                                                      A callback to retrieve the signal strength can be specified to occur periodically with the wlanStatus method. This value specifies the periodicity of the callback as well as the update frequency of the indicator icon, if shown. On Android this value is not used as the signal icon will be updated as soon as the signal strength changes.

                                                                      +

                                                                      Default: 5000

                                                                      Property Access:

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

                                                                      Examples

                                                                      + +
                                                                      Retrieve the WLAN status
                                                                      +

                                                                      Synchronously: If you are only interested in the current signal state, for example to decide whether to perform some online operation then you can immediately determine the WLAN status as follows

                                                                      +
                                                                      :::javascript
                                                                      +
                                                                      +  function signal_status_sync(){
                                                                      +
                                                                      +    signalValue = Rho.SignalIndicators.wlanStatus;
                                                                      +    console.log(signalValue);
                                                                      +    console.log("Signal Strength is: " + signalValue['signalStrength']);
                                                                      +  }
                                                                      +                    
                                                                      +                            
                                                                      :::ruby
                                                                      +
                                                                      +  def signal_status_sync
                                                                      +    signalValue = Rho::SignalIndicators.wlanStatus
                                                                      +    puts signalValue
                                                                      +    puts "Signal Strength is: " + signalValue['signalStrength']
                                                                      +  end
                                                                      +                    
                                                                      +                            
                                                                      +

                                                                      Asynchronously: If you want to be notified of changes to the WLAN signal then you can register to receive values through a callback

                                                                      +
                                                                      :::javascript
                                                                      +
                                                                      +  function signal_status_async(){
                                                                      +    console.log("Registering Signal Callback");
                                                                      +    Rho.SignalIndicators.wlanStatus(signalEvent);
                                                                      +  }
                                                                      +
                                                                      +  function signalEvent(params){
                                                                      +    console.log("Signal Event: (Asynchronous).  Strength: " + params["signalStrength"] + ", ESS ID: " + params["essid"] + ", MacAddress: " + params["macAddress"] + ", AdapterName: " + params["adapterName"] + ", DHCP Server: " + params["dhcpServer"] + ", DHCP Static: " + params["dhcpStatic"] + ", Gateway: " + params["gateway"] + ", IP Address: " + params["ipAddress"] + ", RSSI: " + params["rssi"] + ", Subnet Mask: " + params["subnetMask"] + ", Wins: " + params["wins"]);
                                                                      +  }
                                                                      +  
                                                                      +                            
                                                                      :::ruby
                                                                      +
                                                                      +  def signal_status_async
                                                                      +    puts "Registering Signal Callback"
                                                                      +    Rho::SignalIndicators.wlanStatus(url_for(:action => :signalEvent))
                                                                      +  end
                                                                      +
                                                                      +   def signalEvent
                                                                      +    puts "Signal Event: (Asynchronous).  Strength: #{@params["signalStrength"]}, ESS ID: #{@params["essid"]}, MacAddress: #{@params["macAddress"]}, AdapterName: #{@params["adapterName"]}, DHCP Server: #{@params["dhcpServer"]}, DHCP Static: #{@params["dhcpStatic"]}, Gateway: #{@params["gateway"]}, IP Address: #{@params["ipAddress"]}, RSSI: #{@params["rssi"]}, Subnet Mask: #{@params["subnetMask"]}, Wins: #{@params["wins"]}"
                                                                      +  end
                                                                      +  
                                                                      +                            
                                                                      Working with the Signal indicator
                                                                      +

                                                                      If you just want to display the signal indicator in the default position and default colour then call as follows

                                                                      +
                                                                      :::javascript
                                                                      +
                                                                      +  function show_signal_icon(){
                                                                      +    Rho.SignalIndicators.showIcon({});
                                                                      +  }
                                                                      +                    
                                                                      +                            
                                                                      :::ruby
                                                                      +
                                                                      +  def show_signal_icon
                                                                      +    Rho::SignalIndicators.showIcon({})
                                                                      +  end
                                                                      +                    
                                                                      +                            
                                                                      +

                                                                      To display the signal icon at the default position but blue and vertical specify as follows

                                                                      +
                                                                      :::javascript
                                                                      +
                                                                      +  function show_signal_icon(){
                                                                      +    Rho.SignalIndicators.showIcon({color:'#0000FF',layout: Rho.SignalIndicators.SIGNAL_LAYOUT_UP});
                                                                      +  }
                                                                      +  
                                                                      +                            
                                                                      :::ruby
                                                                      +
                                                                      +  def show_signal_icon
                                                                      +    Rho::SignalIndicators.showIcon({color:'#0000FF',layout: Rho::SignalIndicators.SIGNAL_LAYOUT_UP})
                                                                      +  end
                                                                      +  
                                                                      +                            
                                                                      + +

                                                                      Remarks

                                                                      + +
                                                                      Icon Layout

                                                                      Windows Mobile / CE and Handheld devices support the display of a small signal icon, this section explains the layout parameter which can be provided to showIcon(…).

                                                                      + +

                                                                      Layout:Left

                                                                      + +

                                                                      Left Layout Signal Indicator

                                                                      + +

                                                                      Layout:Right

                                                                      + +

                                                                      Right Layout Signal Indicator

                                                                      + +

                                                                      Layout:Up

                                                                      + +

                                                                      Up Layout Signal Indicator

                                                                      + +

                                                                      Layout:Down

                                                                      + +

                                                                      Down Layout Signal Indicator

                                                                      +
                                                                      Overlapping Indicators

                                                                      The position of the signal and battery indicators should not be set to overlap

                                                                      +
                                                                      Screen Orientation

                                                                      The indicator positions are absolute and so when rotating the screen you should also move the indicator positions accordingly to accommodate the new screen layout.

                                                                      +
                                                                      \ No newline at end of file diff --git a/docs/en/5.5/api/signalindicators.xml b/docs/en/5.5/api/signalindicators.xml new file mode 100644 index 00000000..57efcb36 --- /dev/null +++ b/docs/en/5.5/api/signalindicators.xml @@ -0,0 +1,321 @@ + + + + + + + + + The Signal API is used to notify the user of the strength of the WLAN signal. For Windows Mobile / CE, only Symbol devices are supported and it is also possible to display a small indicator showing the available signal. The WLAN signal strength is not available on Windows Phone 8 and therefore this API is not supported on that platform. + The Signal API is used to notify the user of the strength of the WLAN signal. For Windows Mobile / CE, only Symbol devices are supported and it is also possible to display a small indicator showing the available signal. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml`. + :::ruby + extensions: ["indicators"] + +The `indicators` extension is also included automatically if you specify the following in your `build.yml`. + :::ruby + app_type: "rhoelements" + +> Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +### Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + + +## Enabling the API +There are two methods of enabling the SignalIndicators API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the SignalIndicators API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.signalindicators.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + iOS, WM + WM + 1.0.0 + A callback to retrieve the signal strength can be specified to occur periodically with the wlanStatus method. This value specifies the periodicity of the callback as well as the update frequency of the indicator icon, if shown. On Android this value is not used as the signal icon will be updated as soon as the signal strength changes. + + + + + + iOS, WM, Android + Android, WM + 1.0.0 + Retrieve the current signal status. If a callback is provided to retrieve the signal then it will be called periodically at the specified refreshInterval. On Android, instead of being called periodically, the callback will be called when one of the below values changes. + + + + WM, CE, Android + The signal strength as a value between 0 and 100. Not supported on iOS + The signal strength as a value between 0 and 100. + + + The current ESSID + + + The Device's MAC address + + + The Device's adapter name + + + WM, CE, Android + The current DHCP server's address. Always populated on Android, even on static IP configurations. Not supported on iOS + The current DHCP server's address. Always populated on Android, even on static IP configurations. + + + WM + Whether the unit has a static or DHCP address. Not available on Android and iOS. + Whether the unit has a static or DHCP address. Not available on Android. + + + The current gateway IP address + + + The device's IP address + + + WM, CE, Android + Signal strength in RSSI terms. Not supported on iOS. + Signal strength in RSSI terms. + + + The current subnet mask + + + WM + The current WINs server IP address. Not available on Android and iOS. + The current WINs server IP address. Not available on Android + + + + + + + iOS, WM, Android + Android, WM + 4.0.0 + If the signal is being retrieved via callback, by a previously invoked call to wlanStatus, this method will stop the callback from firing. + + + + WM, CE, Android + 1.0.0 + Overlays a small signal icon on top of the view indicating the remaining signal strength. This is particularly useful in full screen applications which cover the system signal level indicator. + All platforms support wlanStatus which can be used to draw your own level indicator or display an appropriate graphic. + + + The properties associated with the indicator, its position and colour. + + + The absolute horizontal position of the indicator in pixels. This value is relative to the screen and not the view, so non-fullscreen applications should take care not to display the indicator off screen. + + + The absolute vertical position of the indicator in pixels. Positive numbers push the icon towards the bottom of the screen. The value is relative to the screen and not the view, so non-fullscreen applications should take care not to display the indicator off screen. + + + Sets the orientation of the icon, see the remarks section for illustrations. + + + See the remarks section for illustrations of icon layout + + + See the remarks section for illustrations of icon layout + + + See the remarks section for illustrations of icon layout + + + See the remarks section for illustrations of icon layout + + + + + The color of the icon. This value must be specified as a Hex value in the format #000000 to #FFFFFF. Alpha values are not supported, i.e. you can only use the component parts RRGGBB. + + + + + + + + WM, CE, Android + 4.0.0 + Hide the icon if it has been previously set by the 'showIcon' call. + All platforms support wlanStatus which can be used to draw your own level indicator or display an appropriate graphic. + + + + 1.0.0 + WM, CE, Android, iOS + Android, WM, CE + + + + +
                                                                      + Synchronously: If you are only interested in the current signal state, for example to decide whether to perform some online operation then you can immediately determine the WLAN status as follows + + + + + + +
                                                                      +
                                                                      + Asynchronously: If you want to be notified of changes to the WLAN signal then you can register to receive values through a callback + + :signalEvent)) + end + + def signalEvent + puts "Signal Event: (Asynchronous). Strength: #{@params["signalStrength"]}, ESS ID: #{@params["essid"]}, MacAddress: #{@params["macAddress"]}, AdapterName: #{@params["adapterName"]}, DHCP Server: #{@params["dhcpServer"]}, DHCP Static: #{@params["dhcpStatic"]}, Gateway: #{@params["gateway"]}, IP Address: #{@params["ipAddress"]}, RSSI: #{@params["rssi"]}, Subnet Mask: #{@params["subnetMask"]}, Wins: #{@params["wins"]}" + end + ]]> + + + + +
                                                                      +
                                                                      +
                                                                      + + + +
                                                                      + If you just want to display the signal indicator in the default position and default colour then call as follows + + + + + + +
                                                                      +
                                                                      + To display the signal icon at the default position but blue and vertical specify as follows + + + + + + +
                                                                      +
                                                                      +
                                                                      +
                                                                      + + + + Windows Mobile / CE and Handheld devices support the display of a small signal icon, this section explains the layout parameter which can be provided to showIcon(...). + +Layout:Left +----------- +![Left Layout Signal Indicator](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAI4AAABjCAIAAADCRa8DAAAAAXNSR0IArs4c6QAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIBQsDMysrIIsAAAOXSURBVHja7ZztceIwEEDFDb8ZV5BJBQkdABUkVJDQAVTgpALTQZwKSAcmHXhSAelAQwPcDzIgryzjT87KvTf+E4/ONvvYXVn2MTgcDurKfH+r3U5BRYb/4JxxrF5eCH1V/hACVAGqUAWogrZmgGmqlsumh1mv1XhMNDtWpbX6/Gx6GK0JJQXwiqxWar/PbLe3/TkFqjwqgIIwLPtPX187vK75XL2/Z/ZEkfPaVit5MWGoosh52atVZs/NTYUCvt/X+Th3d83X0ixV5Zd8OlWVJEprFQTnPbOZU5U9oymY48xmmT/T1JdG29cCqLVKEhl909yJIFDz+QUf5mBhcbNhWtGYNC0lIHenrcQ12PxCRJEajTJb608AGpyix6pEVrnKmqvW5SoUg7XO+UJU4u1Nhj53a0N5v7NKfMLyWXWcmFwcbH8bKIA1EY3EbleuQldy8HYrRYqbntZpcIp+q7rYrhYLWY4KBtv558+coveqLrYr80+tpSoxeDr1dJrugyp7yl6QKJuNjL4YLLqXV41KebCwJNqJ2YFENzqONAUUDLaPXI/FQvYesX19+aAqTdV2e97qTYvt7/4pV3Kncx8fpQbb+dp7unxjabnMPF6ZTutE51jTzIQYj3+mA2ZBO5U+cYrHx5/Bom/55kn5sbIu5mnH/BAz71PoxV2tK6sa3vn+tqxqsV2Zk/Jj1ykIfZKcLZ6MikbVVlYliXp4IKsK25WYppuZZ9/Y2l49zCofVNkrdeNxJvrC5fEBijnY/0alvHkKLNrVfJ6Jvp0ipozcrELVlWqgeB/BzhJTRhB01ahQ5ZyylyyPqnBxb7Px9P0qf16DcaVCrpXdzlnl/Kx+XqlyrQO59rvU+ln9vFLlqmmu0OdmT/PHvqiqM2Uv7mG5Cr16QOWtqtzoF1QzcV9cXC1R1Xm7Kq5mxfdbvjH0LKtGowrjo8j5jm3t41e6gOYfwdes+r9BFaoAVagCVNmEoToc2KpuZBX3Vbk3pK7/CuDi/l6t1zn7qx7H5ulJPT+jyoHWldd1XL+q1nx9aDKhVwGqUEUIUAWoQhWgClCFKkAVoApV0CuGhOBMHKs4bnqQzl41RJXBbtfCz/hSAAFVqAJUoQpQBahCFaAKUIUqQBXUguXaq9D816eDAFVXQfw2bA0mEwogvQpQhSpAFaAKVYAqQBWqAFWAKlQBqgBVqAJUAapQBagCN9ZrMIMBQSGrAFWogl7xF92qR0MwnLlVAAAAAElFTkSuQmCC "Signal Indicator") + +Layout:Right +------------ +![Right Layout Signal Indicator](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAI4AAABjCAIAAADCRa8DAAAAAXNSR0IArs4c6QAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIBQsDEIlMUfkAAAOXSURBVHja7Z3dbeowFIDdKx4jlAl6O0HFBvRO0LIBbAATABOkG7SdgG4QukHaCTJChHjnPlBR5zg2+XNo2u+TXxpZCfjLOcd2gF6lafo3TRVUZTzu+oqH1eqgFK1y65w/hEdfQBWqAFWogu/OgCHwzT5Jgvm86UkeH1HlnSDL1Ntb85N84wS4WKjdLtdubvp3CWoVtcrCZKJeXnJHokgtl9Zbdb3OHVkuVRQVd16v1WKRO3J9rbKs7Mvf7eq86dtbdcG9NNu4FQ5OZVVxrLJMheHXkX//rJccjc4f0c+jkyQVPPWU1aqeqnIJMMtUHMvR182dCEM1mZzxoXcWFjcbEl3jWpUkpQQUHjSV2DrrN0QUqeEw11rPWh1c4gKqRFTZ0pot1xUqFJ2zrOCGqMTTkxz6wtbPhz5Vokq8w/JRdZyYnO1s3g1Qc7IuColZrmyJrmTn7VaKFIue1ungEpdRdbZczWYyHTk6m/HHnKI1VWfLlf5nlklVovPd3a+bpnenypyyOwJls5GjLzqL6kWhalOVWU70CiSq0bGnLsDR2TxzPWYzWXtE+/j4NarMe/8UK4XTudfXUp3NeO0J+yRR2+2p7RsuNpxUfAhyzGl6QIxGn9MBPaGdUp8Q8PDw2VnUrd5mv2Cx0PNBMB63kx5aiCpznnaMDzHzPg29WNXaosrnzfhjqP5ocbvNTcqPVccx9HH8ZfFkVBSqtqIqjtX9PdMKZ7kS03Q98syFremVqPKiytypG41yoy9cHh+g6J1/SqH69qrMcjWZ5EbfDBFdRmFUgS9VIg7E5xHMKNFlhKGvQoUq65S9ZHpUzs29zYb9JJ+qHKFQaCVNrVmO7OddlW2hZztuU0v2867KltNsQ18YPc0f+6KqzpTdXcMKFfKAqgtVhaPvyGZiXezOltCyKnOg3dnMvd6CcwwaRdVwWKF/FFk/Y1v7/JVeQPO30NeoAlQBqlAFqIK8quVSHQ60yo2oAg/rqkvx/Cy/QtnKVotSaj5X7+/VztPhHmYPVaWprx2pJGn+VXgSIKAKVYAqVAGqAFWoAlQBqlAFqIJ6+NyuFb9MUYPpVE2nSPKvqvkudXPZJEBAFaAKVYAqQBWqAFWAKlQBqlAFPWGwT5Kg2U/n7MMwcPyDFmhLVTCfN9wC9/oroEACRBWgClCFKkAVqgBVgCpUAaoAVagCVAGqUAWoAlShClAFJRgwBF1zdUVUkQABVVCJ/62iI55gpej+AAAAAElFTkSuQmCC "Signal Indicator") + +Layout:Up +--------- +![Up Layout Signal Indicator](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGMAAACOCAIAAACqgyGeAAAAAXNSR0IArs4c6QAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIBQsCFnk0xY0AAANcSURBVHja7Z3bbatAEIaXozxHlEAFCR2AG4hCB04FkStIUkHSgUsgqcCkA5fgElAaIA9Y+IZhl90c9vL9QpZMJJt8mpmdmR1D1Gw2Ah0rjkWa9pxvOM6OLGv69A8bkhSkIPW3pJom0OPlBZvC+yAFKUhBCkEKUpCCFKQgBSkkpZuTd1EEEWwKUpCyL06xi3WmOO49HTVNAxy8D1KQghSkQlLUZJn//+XHR//4ilo+9f3tP6m6xvuIU5Byue6zvwrTDsbXSjm/SKWpJTU83ueNTXV6e5vz25dL6yd583w/uzvvZVQV3kecghSkIAUpSCFIQQpSkLJNcSyKwqMK2bjSVCwW+9c4FmU5RsryvZn7e8Pm09IpCpEkil2XqgrFfPJcLBaTP8Nf72vNJ89FUYTRHZ5mPkVhoPvuIal28Wqda4L5bLcyrXqXSXWhZ4L5tHTaV7kdZpdJfX39NZ2Q8ik9OqekLJ/Wz3Pl/b7dTpSlETq+21SSHPImc7A89b40PYT57VaU5d4HNRTZPmPded9llGiTJvm1r673vNZrZUOrKpdJ6aTjqpHeE1IDHQIZteH//T0wUpPd8/Y2YFJK7jlGKoyeZ12LshTPz+LhQazXZAmDBvX4OLF+9p+UTv3sP6kkOURxSfPpkiz/SXWtcSXzUU/cXSa1Wu33Dui6jEhm8rN1rs9PE10XL3OCznb0quJjsYccQi/h5+f/2Zfb1YwMqctMvaqmxCy3SensfYbbdenyKfmk4Yza8A11PewlTEtEpbouEjcnnrlAWS4ndl2UunrjpFy5W4nmbttowQypHvfsHWKA1Lh7tu0HSMka2nCuwK/WDkkpdZ8p3YjX1znXfs3lbLK6qZDV6uT89V2/mTLPLFOexNWv+3pzgrMPuRbXiVPyghSkIDXf2ueuhrNqSd3dBUDKiHY7vI84BSlIsfbNLp1qRn0lxabwPkhBioj+d5L5jdZxt+9yavjpSf7bXO7kqa6Pl6vb8F+PRSePOAUpSLmw9vG8GWwKUpCCFNWMC5LeUAielPQmlQSpPDd2WSYegGMtR6NP5jF3ExULfZOIHkKccnjSbLMxGfXOr5RJMzJPSEEKebv2MWlmZ/KJ9xGnIAUpSEEKUghSkIIUpFytkA0+mcfEw0qs1S9R7tiZjYt9FQAAAABJRU5ErkJggg== "Signal Indicator") + +Layout:Down +----------- +![Down Layout Signal Indicator](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGMAAACOCAIAAACqgyGeAAAAAXNSR0IArs4c6QAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIBQsED0sFyssAAAOESURBVHja7Z3RcYJAEIaXDM8ZSqCCDB2AHeQ60BKoIEkF2oElkFQgSQWWYAmMDVweIChE5DgW4e7+fxgf1DDyze7e7t4GPBnHxKXdjqKIJtLHB82o9dqTjKc7HChJpvqtnjcnqTx/IkhNIAVSIAVSIAVSIAWBFEiB1KMUBCRE77d8dwFFEa1W1WsQUJaBVNN8SjpCUBgO+lPfIfNJElqttM/hW24+SUJCUBCMP59vp/kIwd5T9C0xHyEq59Iwn+ORDgerSdWhR8N8Sjrla1HYblNfX1PTcWntG0enSYpxb4ZjiWHQ6URZxkKnSSrPbbOjMLzkTXywPCmlGdf/fxfrfFZ1wCyrfFBbeW4yqTJpUl/7iqLitd8PNjSzSY1Jx4dGektI3ekQqKgM/9utY6S03fP52WFSg9yzn9Qslx3Hg7MTlgmOKKLNhjYbDVIO9KdKg3p91ayf7a9mxtTP9pMKw0sUVzSfOsmyn1TdGh9kPsMTd5NJpWm1d4CuS49UJj9L5/r85Oi62Kc69IysipvCHrJ618XczFOl68JlX2bn6Ir9qWtqWUZ5rhOzzCY1Zu9Tp+tiR91X51PqSUOL2tubYxWyXiLqei9hUFfP6V7C8XhZ70YXzI71p6h7iKHPpkjSHEccy6Ga4mdEkUxT+fMjz+eeb7pOqj6CoJcUqpm/pBR1H5cMn5/SVj1alqaN97t3/Tx5PzedSGFI6/Wj676b2VPrJF0roNn7fY8lhTiFTh5IYe0bEWvG6OXFAVIsOp2USb2/L/pKNPKJiSQXfiTJI+q+3gNZAtY+rH1cOfrwlRQ2Be8DKZBCRJ9OCv/o2ej27fftT28OEXfIW3p3KkkqInq7WNfr4//V7f6n10LmiTgFUiAFUiAFUhBIgRSqGR4pbyg4T0p5k8p5UnwcfTJlgmNu30REd8H7Hj1phvmpm++3hP4U4hRIzRnRp3tCDIuiiHa7ZZD6/jYskPdG32mST0yaqSafiFOI6CAFUiAFUiAFgRRIgRRIgZTdMqdCnruLDZtS1eInYoOA4Sav2+34kyze+4qC4UkTHI9ygPeBFEjNlyUwPplnycsCw9rn8qwLvA+kQAqkQMrNLMG+p9JNVGlKHGp30IT3IU6B1DJISenooXCrTtgUvA+kQAqkQAqkIJACKZACKZACKYioPevC9UQl2BRIQSDFGadU7h/qlDoGY34BQ9/qdocP8aYAAAAASUVORK5CYII= "Signal Indicator") + + + + The position of the signal and battery indicators should not be set to overlap + + + + The indicator positions are absolute and so when rotating the screen you should also move the indicator positions accordingly to accommodate the new screen layout. + + + When using the this feature on a CE device using the IE engine, screen distortion may be noticed when scrolling. This is due to a limitation of the IE engine and can be worked around by any of the following options: + +* Not using debug buttons - If your app must use the IE engine, do not use debug buttons in the app. +* If you need to use the signal or battery indicators either: + * Don't scroll the page. + * Don't use the signal / battery indicators + * Use the Webkit engine. + + +
                                                                      +
                                                                      \ No newline at end of file diff --git a/docs/en/5.5/api/signature.md b/docs/en/5.5/api/signature.md new file mode 100644 index 00000000..3eba31d4 --- /dev/null +++ b/docs/en/5.5/api/signature.md @@ -0,0 +1,171 @@ +#Signature +
                                                                      +

                                                                      creates a rectangular box within which the user can draw by using a finger or the device’s stylus to record handwritten data. Common usages for this tag include the capture of client/customer signatures and the input of handwritten text/notations. It is recommended to not to rotate the device when Signature window is shown.

                                                                      +

                                                                      Enabling the API

                                                                      + +

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

                                                                      + +
                                                                      :::ruby
                                                                      +extensions: ["signature"]
                                                                      +
                                                                      + +

                                                                      The signature extension is also included automatically if you specify the following in your build.yml

                                                                      + +
                                                                      :::ruby
                                                                      +app_type: "rhoelements"
                                                                      +
                                                                      + +

                                                                      Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as “rhoelements” in your build.yml as shown here.

                                                                      + +

                                                                      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.

                                                                      + +

                                                                      Persistence

                                                                      + +

                                                                      With the old PocketBrowser / RhoElements 1 APIs, any events, such as signatureCaptureEvent were canceled when a full navigate was performed. The original reason for this was a limitation of the IE engine on WM5 devices. When moving to the common API this was changed so that callbacks are not canceled.

                                                                      + + + +

                                                                      Methods

                                                                      + +

                                                                      capture(CallBackHandler callback)

                                                                      Captures the in-line signature area as an image. This function works with a non-modal signature capture area shown inside browser window. All in-line signature capture functions (like this) do not has affect the capture area shown in takeFullScreen (modal full screen capture area).

                                                                      +

                                                                      Parameters

                                                                      • callback : CallBackHandler Mandatory

                                                                      Async Callback Returning Parameters: HASH

                                                                        • status : STRING

                                                                          Whether a signature was captured or the signature capture area was dismissed (Fullscreen version only). Possible values:‘ok’ or ‘cancel’

                                                                          +

                                                                        • imageUri : STRING

                                                                          If the outputFormat is “image”, this will be the URI of the captured signature image. If the outputFormat is “dataUri”, this will be the DataURI representation of the captured signature image.

                                                                          +

                                                                        • signature_uri : STRING

                                                                          If the outputFormat is “image”, this will be the URI of the captured signature image. If the outputFormat is “dataUri”, this will be the DataURI representation of the captured signature image.

                                                                          +

                                                                      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.Signature.capture(CallBackHandler callback)
                                                                        • Ruby: Rho::Signature.capture(CallBackHandler callback)

                                                                      clear()

                                                                      Clears an in-line capture area. This function works with a non-modal signature capture area shown inside browser window. All in-line signature capture functions (like this) do not has affect to capture area shown in takeFullScreen (modal full screen capture area)

                                                                      +

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

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

                                                                      hide()

                                                                      Hides an in-line capture area from view. It clears the inputed signature for in-line signature areas. In a hidden state, a user cannot interact with the signature capture area. This function work with non-modal signature capture area showed inside browser window. All in-line signature capture functions (like this) do not has affect to capture area showed in takeFullScreen (modal full screen capture area)

                                                                      +

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

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

                                                                      setVectorCallback(CallBackHandler callback)

                                                                      Signature data is formatted into a series of vectors and returned to the application via this callback function. The received data may not represent the entire signature as the vectors will be sent in batches if the signature is large. A single vector (array entry) contains an X, Y coordinate and the beginning / end of the signature is defined by (65535, 65535). This callback is independent of the callback of the capture method, when specified the callback will be called whenever a ‘pen up’ occurs in the signature box.

                                                                      +

                                                                      Parameters

                                                                      • callback : CallBackHandler Mandatory

                                                                      Async Callback Returning Parameters: HASH

                                                                        • vectorArray : ARRAY

                                                                          JavaScript array of vectors which represent the signature.

                                                                          +

                                                                      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.Signature.setVectorCallback(CallBackHandler callback)
                                                                        • Ruby: Rho::Signature.setVectorCallback(CallBackHandler callback)

                                                                      show(HASH propertyMap)

                                                                      Show in-line signature window. This function works with a non-modal signature capture area shown inside browser window. All in-line signature capture functions (like this) do not has affect the capture area shown in takeFullScreen (modal full screen capture area).

                                                                      +

                                                                      Parameters

                                                                      • propertyMap : HASH Optional

                                                                        Map of signature properties to be set.

                                                                        + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

                                                                        Use existing properties from this API.

                                                                        +

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

                                                                      • Class Method: This method can only be accessed via the API class object.
                                                                        • JavaScript: Rho.Signature.show(HASH propertyMap)
                                                                        • Ruby: Rho::Signature.show(HASH propertyMap)

                                                                      takeFullScreen(HASH propertyMap, CallBackHandler callback)

                                                                      Shows a modal window with signature capture area and UI (toolbar with buttons) for cancel / capture and return to main application window. The callback is fired when the signature window is closed (when in full-screen) or when capture is called. On WM/CE, the signature area has visible buttons for ‘clear’, ‘capture’ and ‘cancel’. In Android / iOS, the signature area has images which will behave as buttons for ‘clear’, ‘capture’ and ‘cancel’. This function open modal full screen window therefore, other functions related to in-line signature capture (work with inside browser window area) do not affect the capture window shown by this function.

                                                                      +

                                                                      Parameters

                                                                      • propertyMap : HASH Optional

                                                                        Map of signature properties to be set

                                                                        + Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section

                                                                        Use already set properties

                                                                        +

                                                                      • callback : CallBackHandler Mandatory

                                                                      Async Callback Returning Parameters: HASH

                                                                        • status : STRING

                                                                          Whether a signature was captured or the signature capture area was dismissed (Fullscreen version only). Possible values:‘ok’ or ‘cancel’

                                                                          +

                                                                        • imageUri : STRING

                                                                          If the outputFormat is “image”, this will be the URI of the captured signature image. If the outputFormat is “dataUri”, this will be the DataURI representation of the captured signature image.

                                                                          +

                                                                        • signature_uri : STRING

                                                                          If the outputFormat is “image”, this will be the URI of the captured signature image. If the outputFormat is “dataUri”, this will be the DataURI representation of the captured signature image.

                                                                          +

                                                                      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.Signature.takeFullScreen(HASH propertyMap, CallBackHandler callback)
                                                                        • Ruby: Rho::Signature.takeFullScreen(HASH propertyMap, CallBackHandler callback)
                                                                      + +

                                                                      Properties

                                                                      + +

                                                                      bgColor : STRING 1.0.0

                                                                      RGB or ARGB value that sets the background color of the signature capture area.

                                                                      +

                                                                      Default: #FFFFFFFF

                                                                      Property Access:

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

                                                                      border : BOOLEAN 1.0.0

                                                                      Shows or hides a border for the rectangular capture area. Not applicable to full-screen signature capture area.

                                                                      +

                                                                      Default: true

                                                                      Property Access:

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

                                                                      compressionFormat : STRING 4.0.0

                                                                      Replaces:imageFormat

                                                                      Compression format of the image file for the captured signature. On WM/CE, irrespective of setting any format, the output format will be of bitmap type. On WM/CE, when compressionFormat is queried, it will be of bitmap type always.

                                                                      +

                                                                      Possible Values (STRING):

                                                                      Constant: Rho.Signature.COMPRESSION_FORMAT_JPG (For Ruby use "::" for all "." when referencing constants)
                                                                      String: jpg

                                                                      JPEG file format (Not available on WM/CE).

                                                                      +
                                                                      Constant: Rho.Signature.COMPRESSION_FORMAT_PNG (For Ruby use "::" for all "." when referencing constants)
                                                                      String: png

                                                                      Portable Network Graphics file (Not available on WM/CE).

                                                                      +
                                                                      Constant: Rho.Signature.COMPRESSION_FORMAT_BMP (For Ruby use "::" for all "." when referencing constants)
                                                                      String: bmp

                                                                      Bitmap image file (Not available on iOS).

                                                                      +

                                                                      Property Access:

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

                                                                      fileName : STRING 1.0.0

                                                                      Replaces:name

                                                                      The filename in which to store the signature image, if “image” is used as the outputFormat. The file extension is determined by the compressionFormat used.

                                                                      +

                                                                      Default: signature

                                                                      Property Access:

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

                                                                      height : INTEGER 1.0.0

                                                                      The height of the signature capture area in pixels. Not applicable to full-screen signature capture area.

                                                                      +

                                                                      Default: 150

                                                                      Property Access:

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

                                                                      left : INTEGER 1.0.0

                                                                      The coordinates in pixels of the left side of the signature capture area. Not applicable to full-screen signature capture area.

                                                                      +

                                                                      Default: 15

                                                                      Property Access:

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

                                                                      outputFormat : STRING 4.0.0

                                                                      The return type of the saved signature capture image.

                                                                      +

                                                                      Default: image

                                                                      Possible Values (STRING):

                                                                      Constant: Rho.Signature.OUTPUT_FORMAT_IMAGE (For Ruby use "::" for all "." when referencing constants)
                                                                      String: image

                                                                      Outputs the signature capture image into an image file. The compression method and extension of the image file can be specified in compressionFormat.

                                                                      +
                                                                      Constant: Rho.Signature.OUTPUT_FORMAT_DATAURI (For Ruby use "::" for all "." when referencing constants)
                                                                      String: dataUri

                                                                      Outputs the signature capture image as a DataURI string. (Not available on iOS).

                                                                      +

                                                                      Property Access:

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

                                                                      penColor : STRING 1.0.0

                                                                      RGB or ARGB value that sets the color of the stylus pen ink using HTML web colors.

                                                                      +

                                                                      Default: #FF000000

                                                                      Property Access:

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

                                                                      penWidth : INTEGER 1.0.0

                                                                      Sets the width of the pen line in pixels when using the device’s stylus. On Android this setting will also be applied to any previously drawn signature currently displayed. It is advised that you keep this at 5 or less.

                                                                      +

                                                                      Default: 3

                                                                      Property Access:

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

                                                                      top : INTEGER 1.0.0

                                                                      The coordinates in pixels of the top side of the signature capture area. Not applicable to full-screen signature capture area.

                                                                      +

                                                                      Default: 60

                                                                      Property Access:

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

                                                                      width : INTEGER 1.0.0

                                                                      The width of the signature capture area in pixels. Not applicable to full-screen signature capture area.

                                                                      +

                                                                      Default: 200

                                                                      Property Access:

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

                                                                      Examples

                                                                      + +
                                                                      Capture signature to file (fullscreen) and display it in a view
                                                                      +

                                                                      In order to capture a signature in full-screen mode you need to

                                                                      +
                                                                      :::ruby
                                                                      +           
                                                                      +  def capture_fullscreen
                                                                      +    # Invoke signature capture screen and assign callback
                                                                      +    Rho::Signature.takeFullScreen({}, url_for(:action => :signature_callback))
                                                                      +
                                                                      +    render :action => :show_signature
                                                                      +  end
                                                                      +
                                                                      +  def signature_callback
                                                                      +    # If status is not 'ok', the capture was canceled
                                                                      +    if @params['status'] == 'ok'
                                                                      +
                                                                      +      # By default, the output format is "image", so the imageUri parameter will contain the relative filename of an image
                                                                      +      # We must convert that relative filename to an absolute path in order to access the file
                                                                      +      signature = Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"])
                                                                      +
                                                                      +      # In our example, we will display the signature as soon as it is captured.
                                                                      +      # We have a JavaScript function in our page to set the src attribute of an img element and we will call it now
                                                                      +      #
                                                                      +      WebView.executeJavascript("updateSignature('#{signature}')")
                                                                      +    else
                                                                      +      # if we did not really capture a signature, there is nothing else to do here
                                                                      +      WebView.navigate(url_for(:action => :index ))
                                                                      +    end
                                                                      +  end
                                                                      +                   
                                                                      +               
                                                                      +

                                                                      In the view, we have an img element to display the captured signature and a JavaScript function to update it

                                                                      +
                                                                      :::javascript
                                                                      +           
                                                                      +<div data-role="page">
                                                                      +
                                                                      +
                                                                      +  <div data-role="header" data-position="in-line">
                                                                      +    <h1>Captured signature</h1>
                                                                      +  </div>
                                                                      +
                                                                      +  <div data-role="content">
                                                                      +    <img id="signature-image" src="<%= @signature %>">
                                                                      +  </div>
                                                                      +
                                                                      +  <script type="text/javascript">
                                                                      +    function updateSignature(signature) {
                                                                      +      $("#signature-image").attr('src',signature);
                                                                      +    }
                                                                      +  </script>
                                                                      +
                                                                      +</div>
                                                                      +                   
                                                                      +               
                                                                      Set signature capture properties
                                                                      +

                                                                      Several properties affect the appearance of the signature capture functionality. You can set their values before showing the capture interface:

                                                                      +
                                                                      :::javascript
                                                                      +
                                                                      +           
                                                                      +// Change full-screen from true (default) to false
                                                                      +// Change background color from white (default) to black
                                                                      +// Change pen color from blue (default) to white
                                                                      +Rho.Signature.show ({"fullScreen" : false, "bgColor" : "#000000", "penColor" : "#FFFFFF"});
                                                                      +                   
                                                                      +                 
                                                                      :::ruby
                                                                      +
                                                                      +           
                                                                      +# Change full-screen from true (default) to false
                                                                      +# Change background color from white (default) to black
                                                                      +# Change pen color from blue (default) to white
                                                                      +Rho::Signature.show { :fullScreen => false, :bgColor => "#000000", :penColor => "#FFFFFF" }
                                                                      +                   
                                                                      +                 
                                                                      Capture as DataURI
                                                                      +

                                                                      By default, the Signature API returns the capture as an image. If you prefer a DataURI representation of the signature, use the “outputFormat” property

                                                                      +
                                                                      :::javascript
                                                                      +
                                                                      +           
                                                                      +Rho.Signature.takeFullScreen({"outputFormat" : "dataUri"}, signature_callback)
                                                                      +                   
                                                                      +                 
                                                                      :::ruby
                                                                      +
                                                                      +           
                                                                      +Rho::Signature.takeFullScreen({ :outputFormat => "dataUri" }, url_for(:action => :signature_callback))
                                                                      +                   
                                                                      +                 
                                                                      + +

                                                                      Remarks

                                                                      + +
                                                                      Fullscreen and In-line

                                                                      The signature capture feature can work in two visual modes, Full-screen and In-line. The full-screen variant has buttons to capture, clear and cancel the signature capture box, so the methods: “clear”, “hide”, “capture” don’t need to be used. Whereas with the in-line signature capture, there are no such buttons so these will have to be designed into the app itself.

                                                                      +
                                                                      Parameters which clear the signature

                                                                      The signature capture area is designed to be set up prior to capturing the signature, as such the following parameters will clear any current signature: “width”, “height”, “penColor”, “bgColor”.

                                                                      +
                                                                      Page Navigation

                                                                      In Android, the state of the signature will not be cleared on page navigation whereas in Windows, the state of the signature is cleared.

                                                                      +
                                                                      Persistent Behavior

                                                                      While using “takeFullScreen” method, if we press Home button and re-launch the application the state won’t be persisted in Android platform.

                                                                      +
                                                                      + +

                                                                      Licensing

                                                                      + +
                                                                      This API is considered a RhoElements API and therefore requires a paid subscription to use (either Silver or Gold level). You can review the subscription plans on our licensing page here or on rhomobile.com/pricing.
                                                                      \ No newline at end of file diff --git a/docs/en/5.5/api/signature.xml b/docs/en/5.5/api/signature.xml new file mode 100644 index 00000000..bf59a670 --- /dev/null +++ b/docs/en/5.5/api/signature.xml @@ -0,0 +1,406 @@ + + + + + creates a rectangular box within which the user can draw by using a finger or the device's stylus to record handwritten data. Common usages for this tag include the capture of client/customer signatures and the input of handwritten text/notations. It is recommended to not to rotate the device when Signature window is shown. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["signature"] + +The `signature` extension is also included automatically if you specify the following in your `build.yml` + :::ruby + app_type: "rhoelements" + +> Note: If you are building a Windows Mobile or Windows CE app with this API, you must set your app_type as "rhoelements" in your build.yml as shown [here](../guide/build_config#other-build-time-settings). + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + +## Persistence +With the old PocketBrowser / RhoElements 1 APIs, any events, such as `signatureCaptureEvent` were canceled when a full navigate was performed. The original reason for this was a limitation of the IE engine on WM5 devices. When moving to the common API this was changed so that callbacks are not canceled. + + + +## Enabling the API +There are two methods of enabling the Signature API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Signature API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.signature.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + +## Persistence +With the old PocketBrowser APIs, any events, such as `signatureCaptureEvent` were canceled when a full navigate was performed. The original reason for this was a limitation of the IE engine on WM5 devices. When moving to the common API this was changed so that callbacks are not canceled. + + + iOS, Android, WM + Android, WM + + + + + These properties are used to configure the appearance and the behavior of the signature capture area. + + + + + + + 4.0.0 + Compression format of the image file for the captured signature. On WM/CE, irrespective of setting any format, the output format will be of bitmap type. On WM/CE, when compressionFormat is queried, it will be of bitmap type always. + iOS, Android, WM + Android, WM + + + JPEG file format (Not available on WM/CE). + + + Portable Network Graphics file (Not available on WM/CE). + + + Bitmap image file (Not available on iOS). + Bitmap image file. + + + + + + 4.0.0 + The return type of the saved signature capture image. + iOS, Android, WM + Android, WM + + + Outputs the signature capture image into an image file. The compression method and extension of the image file can be specified in compressionFormat. + + + Outputs the signature capture image as a DataURI string. (Not available on iOS). + Outputs the signature capture image as a DataURI string. + + + + + + 1.0.0 + The filename in which to store the signature image, if "image" is used as the outputFormat. The file extension is determined by the compressionFormat used. + iOS, Android, WM + Android, WM + + + + 1.0.0 + Shows or hides a border for the rectangular capture area. Not applicable to full-screen signature capture area. + Android, WM + + + + 1.0.0 + RGB or ARGB value that sets the color of the stylus pen ink using HTML web colors. + iOS, Android, WM + Android, WM + + + + 1.0.0 + Sets the width of the pen line in pixels when using the device's stylus. On Android this setting will also be applied to any previously drawn signature currently displayed. It is advised that you keep this at 5 or less. + iOS, Android, WM + Android, WM + + + + 1.0.0 + RGB or ARGB value that sets the background color of the signature capture area. + iOS, Android, WM + Android, WM + + + + 1.0.0 + The coordinates in pixels of the left side of the signature capture area. Not applicable to full-screen signature capture area. + iOS, Android, WM + Android, WM + + + + 1.0.0 + The coordinates in pixels of the top side of the signature capture area. Not applicable to full-screen signature capture area. + iOS, Android, WM + Android, WM + + + + 1.0.0 + The width of the signature capture area in pixels. Not applicable to full-screen signature capture area. + iOS, Android, WM + Android, WM + + + + 1.0.0 + The height of the signature capture area in pixels. Not applicable to full-screen signature capture area. + iOS, Android, WM + Android, WM + + + + + + 2.0.0 + Shows a modal window with signature capture area and UI (toolbar with buttons) for cancel / capture and return to main application window. The callback is fired when the signature window is closed (when in full-screen) or when capture is called. On WM/CE, the signature area has visible buttons for 'clear', 'capture' and 'cancel'. In Android / iOS, the signature area has images which will behave as buttons for 'clear', 'capture' and 'cancel'. This function open modal full screen window therefore, other functions related to in-line signature capture (work with inside browser window area) do not affect the capture window shown by this function. + Shows a modal window with signature capture area and UI (toolbar with buttons) for cancel / capture and return to main application window. The callback is fired when the signature window is closed (when in full-screen) or when capture is called. On WM/CE, the signature area has visible buttons for 'clear', 'capture' and 'cancel'. On Android, the signature area has images which will behave as buttons for 'clear', 'capture' and 'cancel'. This function opens a modal full screen window therefore, other functions related to in-line signature capture (work with inside browser window area) do not affect the capture window shown by this function. + iOS, Android, WM + Android, WM + + + Map of signature properties to be set + + Use already set properties + + + + + + + Whether a signature was captured or the signature capture area was dismissed (Fullscreen version only). Possible values:'ok' or 'cancel' + + + If the outputFormat is "image", this will be the URI of the captured signature image. If the outputFormat is "dataUri", this will be the DataURI representation of the captured signature image. + + + If the outputFormat is "image", this will be the URI of the captured signature image. If the outputFormat is "dataUri", this will be the DataURI representation of the captured signature image. + + + + + + + 2.0.0 + Show in-line signature window. This function works with a non-modal signature capture area shown inside browser window. All in-line signature capture functions (like this) do not has affect the capture area shown in takeFullScreen (modal full screen capture area). + iOS, Android, WM + Android, WM + + + Map of signature properties to be set. + + Use existing properties from this API. + + + + + + + 1.0.0 + Captures the in-line signature area as an image. This function works with a non-modal signature capture area shown inside browser window. All in-line signature capture functions (like this) do not has affect the capture area shown in takeFullScreen (modal full screen capture area). + iOS, Android, WM + Android, WM + + + + Whether a signature was captured or the signature capture area was dismissed (Fullscreen version only). Possible values:'ok' or 'cancel' + + + If the outputFormat is "image", this will be the URI of the captured signature image. If the outputFormat is "dataUri", this will be the DataURI representation of the captured signature image. + + + If the outputFormat is "image", this will be the URI of the captured signature image. If the outputFormat is "dataUri", this will be the DataURI representation of the captured signature image. + + + + + + + 1.0.0 + Clears an in-line capture area. This function works with a non-modal signature capture area shown inside browser window. All in-line signature capture functions (like this) do not has affect to capture area shown in takeFullScreen (modal full screen capture area) + iOS, Android, WM + Android, WM + + + + 4.0.0 + Hides an in-line capture area from view. It clears the inputed signature for in-line signature areas. In a hidden state, a user cannot interact with the signature capture area. This function work with non-modal signature capture area showed inside browser window. All in-line signature capture functions (like this) do not has affect to capture area showed in takeFullScreen (modal full screen capture area) + iOS, Android, WM + Android, WM + + + + 4.0.0 + Android, WM + Signature data is formatted into a series of vectors and returned to the application via this callback function. The received data may not represent the entire signature as the vectors will be sent in batches if the signature is large. A single vector (array entry) contains an X, Y coordinate and the beginning / end of the signature is defined by (65535, 65535). This callback is independent of the callback of the capture method, when specified the callback will be called whenever a 'pen up' occurs in the signature box. + + Not providing a callback will result in the vector callback being cleared + + + JavaScript array of vectors which represent the signature. + + + + + + + + +Full-screen and In-line +======================= +The signature capture feature can work in two visual modes, Full-screen and In-line. The full-screen variant has buttons to capture, clear and cancel the signature capture box, so the methods: "clear", "hide", "capture" don't need to be used. Whereas with the in-line signature capture, there are no such buttons so these will have to be designed into the app itself. + +Parameters which clear the signature +==================================== +The signature capture area is designed to be set up prior to capturing the signature, as such the following parameters will clear any current signature: "width", "height", "penColor", "bgColor". + + 1.0.0 + iOS, Android, WM + Android, WM + + + + The signature capture feature can work in two visual modes, Full-screen and In-line. The full-screen variant has buttons to capture, clear and cancel the signature capture box, so the methods: "clear", "hide", "capture" don't need to be used. Whereas with the in-line signature capture, there are no such buttons so these will have to be designed into the app itself. + + + + The signature capture area is designed to be set up prior to capturing the signature, as such the following parameters will clear any current signature: "width", "height", "penColor", "bgColor". + + + + In Android, the state of the signature will not be cleared on page navigation whereas in Windows, the state of the signature is cleared. + + + + While using "takeFullScreen" method, if we press Home button and re-launch the application the state won't be persisted in Android platform. + + + + + + +
                                                                      + In order to capture a signature in full-screen mode you need to + + :signature_callback)) + + render :action => :show_signature + end + + def signature_callback + # If status is not 'ok', the capture was canceled + if @params['status'] == 'ok' + + # By default, the output format is "image", so the imageUri parameter will contain the relative filename of an image + # We must convert that relative filename to an absolute path in order to access the file + signature = Rho::Application.expandDatabaseBlobFilePath(@params["imageUri"]) + + # In our example, we will display the signature as soon as it is captured. + # We have a JavaScript function in our page to set the src attribute of an img element and we will call it now + # + WebView.executeJavascript("updateSignature('#{signature}')") + else + # if we did not really capture a signature, there is nothing else to do here + WebView.navigate(url_for(:action => :index )) + end + end + ]]> + +
                                                                      +
                                                                      + In the view, we have an img element to display the captured signature and a JavaScript function to update it + + + + +
                                                                      +

                                                                      Captured signature

                                                                      +
                                                                      + +
                                                                      + +
                                                                      + + + + + ]]> +
                                                                      +
                                                                      +
                                                                      +
                                                                      + + + +
                                                                      + Several properties affect the appearance of the signature capture functionality. You can set their values before showing the capture interface: + + + false, :bgColor => "#000000", :penColor => "#FFFFFF" } + ]]> + + + + + +
                                                                      +
                                                                      +
                                                                      + + + + +
                                                                      + By default, the Signature API returns the capture as an image. If you prefer a DataURI representation of the signature, use the "outputFormat" property + + + "dataUri" }, url_for(:action => :signature_callback)) + ]]> + + + + + +
                                                                      +
                                                                      +
                                                                      +
                                                                      +
                                                                      +
                                                                      diff --git a/docs/en/5.5/api/singleton_instances.xml b/docs/en/5.5/api/singleton_instances.xml new file mode 100644 index 00000000..4655cfd1 --- /dev/null +++ b/docs/en/5.5/api/singleton_instances.xml @@ -0,0 +1,15 @@ + + + + + + + This is documentation + + + Array of objects. + + + + + diff --git a/docs/en/5.5/api/smartcradle.md b/docs/en/5.5/api/smartcradle.md new file mode 100644 index 00000000..3fcf21a5 --- /dev/null +++ b/docs/en/5.5/api/smartcradle.md @@ -0,0 +1,60 @@ +#SmartCradle +
                                                                      +

                                                                      The SmartCradle API is used to set and retrieve attributes of the MC18 Cradle

                                                                      + + + +

                                                                      Methods

                                                                      + +

                                                                      flashLed(HASH propertyMap)

                                                                      The LED can be flashed to identify device location without unlocking the cradle.

                                                                      +

                                                                      Parameters

                                                                      • propertyMap : HASH

                                                                        The properties associated with reading card data.

                                                                        +

                                                                        • ledOnDuration : INTEGER

                                                                          During unlock the LEDs will flash, this is the on duration of that flash specified in milliseconds. Set to 0 to prevent flashing and keep the LED off. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum).

                                                                          +

                                                                        • ledOffDuration : INTEGER

                                                                          During unlock the LEDs will flash, this is the off duration of that flash specified in milliseconds. Set to 0 to prevent flashing. If the on duration is non-zero and this parameter is zero then the LED will remain on when unlocked. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum).

                                                                          +

                                                                        • smoothingEffect : BOOLEAN

                                                                          Enables or Disables the smoothing effect of LED blinking.

                                                                          +

                                                                        • ledFlashCount : INTEGER

                                                                          ledFlashCount is the no of count it will be flashed. This will take affect for valid values of ledOnDuration and ledOffDuration.

                                                                          +

                                                                      Synchronous Return:

                                                                      • Void

                                                                      Method Access:

                                                                      • Class Method: This method can only be accessed via the API class object.
                                                                        • JavaScript: Rho.SmartCradle.flashLed(HASH propertyMap)
                                                                        • Ruby: Rho::SmartCradle.flashLed(HASH propertyMap)

                                                                      getAllProperties(CallBackHandler callback)

                                                                      This method will return all of object/value pairs for the propertyNames of the API class.

                                                                      +

                                                                      Parameters

                                                                      • callback : CallBackHandler Optional

                                                                      Async Callback Returning Parameters: HASH

                                                                        • : STRING

                                                                      Synchronous Return:

                                                                      • HASH :

                                                                        Map of all available properties

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

                                                                      Method Access:

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

                                                                      getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                      This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                                                                      +

                                                                      Parameters

                                                                      • arrayofNames : ARRAY

                                                                        List of properties I want to know about

                                                                        +

                                                                        • Object : STRING

                                                                      • callback : CallBackHandler Optional

                                                                      Async Callback Returning Parameters: HASH

                                                                        • : STRING

                                                                      Synchronous Return:

                                                                      • HASH :

                                                                        Map of properties I want to know about

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

                                                                      Method Access:

                                                                      • Class Method: This method can only be accessed via the API class object.
                                                                        • JavaScript: Rho.SmartCradle.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                                                        • Ruby: Rho::SmartCradle.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                      getProperty(STRING propertyName, CallBackHandler callback)

                                                                      This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                                                                      +

                                                                      Parameters

                                                                      • propertyName : STRING

                                                                        The property to return info about.

                                                                        +

                                                                      • callback : CallBackHandler Optional

                                                                      Async Callback Returning Parameters: STRING

                                                                        Synchronous Return:

                                                                        • STRING :

                                                                          The property to return info about.

                                                                          + : 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.SmartCradle.getProperty(STRING propertyName, CallBackHandler callback)
                                                                          • Ruby: Rho::SmartCradle.getProperty(STRING propertyName, CallBackHandler callback)

                                                                        setProperties(HASH propertyMap)

                                                                        This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                        +

                                                                        Parameters

                                                                        • propertyMap : HASH

                                                                          Map of properties I want to set

                                                                          +

                                                                          • Object : STRING

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

                                                                        • Class Method: This method can only be accessed via the API class object.
                                                                          • JavaScript: Rho.SmartCradle.setProperties(HASH propertyMap)
                                                                          • Ruby: Rho::SmartCradle.setProperties(HASH propertyMap)

                                                                        setProperty(STRING propertyName, STRING propertyValue)

                                                                        This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                        +

                                                                        Parameters

                                                                        • propertyName : STRING

                                                                          The one property name that I want to set

                                                                          +

                                                                        • propertyValue : STRING

                                                                          The one property value that I want to set

                                                                          +

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

                                                                        • Class Method: This method can only be accessed via the API class object.
                                                                          • JavaScript: Rho.SmartCradle.setProperty(STRING propertyName, STRING propertyValue)
                                                                          • Ruby: Rho::SmartCradle.setProperty(STRING propertyName, STRING propertyValue)

                                                                        unlock(INTEGER ledOnDuration, INTEGER ledOffDuration, INTEGER timeout)

                                                                        Unlocks the terminal from the cradle for the specified period. For Android, the smoothing effect by default is false.

                                                                        +

                                                                        Parameters

                                                                        • ledOnDuration : INTEGER

                                                                          During unlock the LEDs will flash, this is the on duration of that flash specified in milliseconds. Set to 0 to prevent flashing and keep the LED off. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum).

                                                                          +

                                                                        • ledOffDuration : INTEGER

                                                                          During unlock the LEDs will flash, this is the off duration of that flash specified in milliseconds. Set to 0 to prevent flashing. If the on duration is non-zero and this parameter is zero then the LED will remain on when unlocked. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum).

                                                                          +

                                                                        • timeout : INTEGER

                                                                          The cradle will remain unlocked for the length of time in seconds specified by this value. Specified in seconds. Range 10 to 30 inclusive.

                                                                          +

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

                                                                        • Class Method: This method can only be accessed via the API class object.
                                                                          • JavaScript: Rho.SmartCradle.unlock(INTEGER ledOnDuration, INTEGER ledOffDuration, INTEGER timeout)
                                                                          • Ruby: Rho::SmartCradle.unlock(INTEGER ledOnDuration, INTEGER ledOffDuration, INTEGER timeout)

                                                                        unlockEx(HASH propertyMap)

                                                                        Unlocks the terminal from the cradle for the specified period. For Android, the smoothing effect by default is false.

                                                                        +

                                                                        Parameters

                                                                        • propertyMap : HASH

                                                                          The properties associated with reading card data.

                                                                          +

                                                                          • ledOnDuration : INTEGER

                                                                            During unlock the LEDs will flash, this is the on duration of that flash specified in milliseconds. Set to 0 to prevent flashing and keep the LED off. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum).

                                                                            +

                                                                          • ledOffDuration : INTEGER

                                                                            During unlock the LEDs will flash, this is the off duration of that flash specified in milliseconds. Set to 0 to prevent flashing. If the on duration is non-zero and this parameter is zero then the LED will remain on when unlocked. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum).

                                                                            +

                                                                          • timeout : INTEGER

                                                                            The cradle will remain unlocked for the length of time in seconds specified by this value. Specified in seconds. Range 10 to 30 inclusive.

                                                                            +

                                                                          • smoothingEffect : BOOLEAN

                                                                            Enables or Disables the smoothing effect of LED blinking.

                                                                            +

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

                                                                        • Class Method: This method can only be accessed via the API class object.
                                                                          • JavaScript: Rho.SmartCradle.unlockEx(HASH propertyMap)
                                                                          • Ruby: Rho::SmartCradle.unlockEx(HASH propertyMap)
                                                                        + +

                                                                        Properties

                                                                        + +

                                                                        cApiVersion : STRING Read Only

                                                                        CAPI version of the cradle. Not Applicable for Android.

                                                                        +

                                                                        Property Access:

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

                                                                        chargeState : STRING

                                                                        Sets the charge state of the cradle. Values can be either ‘Fast’ or ‘Slow’.

                                                                        +

                                                                        Possible Values (STRING):

                                                                        Constant: Rho.SmartCradle.SMART_CRADLE_FAST (For Ruby use "::" for all "." when referencing constants)
                                                                        String: fast

                                                                        The cradle will charge devices quickly.

                                                                        +
                                                                        Constant: Rho.SmartCradle.SMART_CRADLE_SLOW (For Ruby use "::" for all "." when referencing constants)
                                                                        String: slow

                                                                        The cradle will charge devices slowly.

                                                                        +

                                                                        Property Access:

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

                                                                        columnId : INTEGER

                                                                        The current Column ID of the cradle in the matrix. In Android, the range of columnId is 0 to 255.

                                                                        +

                                                                        Property Access:

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

                                                                        driverVersion : STRING Read Only

                                                                        Driver version of the cradle. Not Applicable for Android.

                                                                        +

                                                                        Property Access:

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

                                                                        firmwareVersion : STRING Read Only

                                                                        Firmware version of the cradle.

                                                                        +

                                                                        Property Access:

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

                                                                        hardwareId : INTEGER Read Only

                                                                        Hardware ID of the cradle

                                                                        +

                                                                        Property Access:

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

                                                                        mfgDate : STRING Read Only

                                                                        Manufacture date of the cradle in DD-MM-YY format. Not Applicable for Android.

                                                                        +

                                                                        Property Access:

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

                                                                        partNumber : STRING Read Only

                                                                        Part number of the cradle.

                                                                        +

                                                                        Property Access:

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

                                                                        rowId : INTEGER

                                                                        The current Row ID of the cradle in the matrix. In Android, the range of rowId is 0 to 255.

                                                                        +

                                                                        Property Access:

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

                                                                        serialNumber : STRING Read Only

                                                                        Serial number of the cradle.

                                                                        +

                                                                        Property Access:

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

                                                                        wallId : INTEGER

                                                                        The current Wall ID of the cradle in the matrix. In Android, the range of wallId is 0 to 255.

                                                                        +

                                                                        Property Access:

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

                                                                        Remarks

                                                                        + +
                                                                        Flashing the Cradle LEDs

                                                                        There is a hardware imposed limit to how quickly the cradle LEDs can be flashed for a quickly flashing LED it is recommended to set the on / off duration to 500ms.

                                                                        +
                                                                        \ No newline at end of file diff --git a/docs/en/5.5/api/smartcradle.xml b/docs/en/5.5/api/smartcradle.xml new file mode 100644 index 00000000..8d167bbb --- /dev/null +++ b/docs/en/5.5/api/smartcradle.xml @@ -0,0 +1,163 @@ + + + + The SmartCradle API is used to set and retrieve attributes of the MC18 Cradle + + +## Enabling the API +There are two methods of enabling the SmartCradle API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the SmartCradle API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.smartcradle.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + Android,CE + The following properties configure the Smart Cradle API + + Sets the charge state of the cradle. Values can be either 'Fast' or 'Slow'. + + + The cradle will charge devices quickly. + + + The cradle will charge devices slowly. + + + + + The current Row ID of the cradle in the matrix. In Android, the range of rowId is 0 to 255. + + + The current Column ID of the cradle in the matrix. In Android, the range of columnId is 0 to 255. + + + The current Wall ID of the cradle in the matrix. In Android, the range of wallId is 0 to 255. + + + Hardware ID of the cradle + + + Part number of the cradle. + + + Serial number of the cradle. + + + Manufacture date of the cradle in DD-MM-YY format. Not Applicable for Android. + + + Driver version of the cradle. Not Applicable for Android. + + + CAPI version of the cradle. Not Applicable for Android. + + + Firmware version of the cradle. + + + + + + + Android,CE + Unlocks the terminal from the cradle for the specified period. For Android, the smoothing effect by default is false. + + + During unlock the LEDs will flash, this is the on duration of that flash specified in milliseconds. Set to 0 to prevent flashing and keep the LED off. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum). + + + During unlock the LEDs will flash, this is the off duration of that flash specified in milliseconds. Set to 0 to prevent flashing. If the on duration is non-zero and this parameter is zero then the LED will remain on when unlocked. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum). + + + The cradle will remain unlocked for the length of time in seconds specified by this value. Specified in seconds. Range 10 to 30 inclusive. + + + + + + Android + Unlocks the terminal from the cradle for the specified period. For Android, the smoothing effect by default is false. + + + The properties associated with reading card data. + + + During unlock the LEDs will flash, this is the on duration of that flash specified in milliseconds. Set to 0 to prevent flashing and keep the LED off. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum). + + + During unlock the LEDs will flash, this is the off duration of that flash specified in milliseconds. Set to 0 to prevent flashing. If the on duration is non-zero and this parameter is zero then the LED will remain on when unlocked. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum). + + + The cradle will remain unlocked for the length of time in seconds specified by this value. Specified in seconds. Range 10 to 30 inclusive. + + + Enables or Disables the smoothing effect of LED blinking. + + + + + + + Android + The LED can be flashed to identify device location without unlocking the cradle. + + + The properties associated with reading card data. + + + During unlock the LEDs will flash, this is the on duration of that flash specified in milliseconds. Set to 0 to prevent flashing and keep the LED off. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum). + + + During unlock the LEDs will flash, this is the off duration of that flash specified in milliseconds. Set to 0 to prevent flashing. If the on duration is non-zero and this parameter is zero then the LED will remain on when unlocked. In Android, this is in mSecs and the range is from 0 mSec(minimum) to 65535 mSec(maximum). + + + Enables or Disables the smoothing effect of LED blinking. + + + ledFlashCount is the no of count it will be flashed. This will take affect for valid values of ledOnDuration and ledOffDuration. + + + + + + + + + + + + 5.1.0 + CE,Android + + + There is a hardware imposed limit to how quickly the cradle LEDs can be flashed for a quickly flashing LED it is recommended to set the on / off duration to 500ms. + + + + + diff --git a/docs/en/5.5/api/system.md b/docs/en/5.5/api/system.md new file mode 100644 index 00000000..5995ba08 --- /dev/null +++ b/docs/en/5.5/api/system.md @@ -0,0 +1,327 @@ +#System +
                                                                        +

                                                                        The System API is used to control and modify core aspects of the device such as the screen, OS and device capabilities.

                                                                        +

                                                                        Enabling the API

                                                                        + +

                                                                        This API is part of the coreapi extension that is included automatically.

                                                                        + +
                                                                        :::ruby
                                                                        +extensions: ["coreapi"]
                                                                        +
                                                                        + +

                                                                        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

                                                                        + +

                                                                        applicationInstall(STRING applicationUrl)

                                                                        Replaces: app_install

                                                                        Install an application.

                                                                        +

                                                                        Parameters

                                                                        • applicationUrl : STRING

                                                                          The url of an application to install on the device.

                                                                          +

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

                                                                        • Class Method: This method can only be accessed via the API class object.
                                                                          • JavaScript: Rho.System.applicationInstall(STRING applicationUrl)
                                                                          • Ruby: Rho::System.applicationInstall(STRING applicationUrl)

                                                                        applicationUninstall(STRING applicationName)

                                                                        Replaces: app_uninstall

                                                                        Uninstall the application. Not Supported on Windows CE devices.

                                                                        +

                                                                        Parameters

                                                                        • applicationName : STRING

                                                                          The name of the application.

                                                                          +

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

                                                                        • Class Method: This method can only be accessed via the API class object.
                                                                          • JavaScript: Rho.System.applicationUninstall(STRING applicationName)
                                                                          • Ruby: Rho::System.applicationUninstall(STRING applicationName)

                                                                        bringToFront()

                                                                        Deprecated

                                                                        Bring application window to the top of the screen.

                                                                        +

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

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

                                                                        clearNetworkStatusNotify()

                                                                        Deprecated

                                                                        Use Network.clearStatusNotify: Clear network status callback.

                                                                        +

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

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

                                                                        deleteFolder(STRING pathToFolder)

                                                                        Deprecated

                                                                        Delete folder.

                                                                        +

                                                                        Parameters

                                                                        • pathToFolder : STRING

                                                                          Path to folder.

                                                                          +

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

                                                                        • Class Method: This method can only be accessed via the API class object.
                                                                          • JavaScript: Rho.System.deleteFolder(STRING pathToFolder)
                                                                          • Ruby: Rho::System.deleteFolder(STRING pathToFolder)

                                                                        deleteRegistrySetting(HASH propertyMap)

                                                                        Deletes the specified value from the device registry. Only applicable on Windows Mobile / Embedded Handheld and CE devices. When running on RhoSimulator, this method is supported only for Windows OS.

                                                                        +

                                                                        Parameters

                                                                        • propertyMap : HASH

                                                                          Map of properties associated with the registry key being set.

                                                                          +

                                                                          • hive : STRING

                                                                            The hive name, setRegistrySetting.

                                                                            +

                                                                          • key : STRING

                                                                            Full path of the key, including ‘\’ separators as required. Remember to use ‘\’ in JavaScript to specify backslash.

                                                                            +

                                                                          • setting : STRING

                                                                            The name of the setting to be deleted.

                                                                            +

                                                                          • persistent : BOOLEAN

                                                                            If the registry value was set to be persistent, ie a corresponding .reg file was created in the \Application folder then setting true here will delete that .reg file.

                                                                            +

                                                                        Synchronous Return:

                                                                        • BOOLEAN :

                                                                          Whether or not the registry key was successfully deleted.

                                                                          +

                                                                        Method Access:

                                                                        • Class Method: This method can only be accessed via the API class object.
                                                                          • JavaScript: Rho.System.deleteRegistrySetting(HASH propertyMap)
                                                                          • Ruby: Rho::System.deleteRegistrySetting(HASH propertyMap)

                                                                        exit()

                                                                        Deprecated

                                                                        Use Application.quit: exit application.

                                                                        +

                                                                        Synchronous Return:

                                                                        • Void

                                                                        Method Access:

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

                                                                        getAllProperties(CallBackHandler callback)

                                                                        This method will return all of object/value pairs for the propertyNames of the API class.

                                                                        +

                                                                        Parameters

                                                                        • callback : CallBackHandler Optional

                                                                        Async Callback Returning Parameters: HASH

                                                                          • : STRING

                                                                        Synchronous Return:

                                                                        • HASH :

                                                                          Map of all available properties

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

                                                                        Method Access:

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

                                                                        getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                        This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                                                                        +

                                                                        Parameters

                                                                        • arrayofNames : ARRAY

                                                                          List of properties I want to know about

                                                                          +

                                                                          • Object : STRING

                                                                        • callback : CallBackHandler Optional

                                                                        Async Callback Returning Parameters: HASH

                                                                          • : STRING

                                                                        Synchronous Return:

                                                                        • HASH :

                                                                          Map of properties I want to know about

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

                                                                        Method Access:

                                                                        • Class Method: This method can only be accessed via the API class object.
                                                                          • JavaScript: Rho.System.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                                                          • Ruby: Rho::System.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                        getProperty(STRING propertyName, CallBackHandler callback)

                                                                        Replaces: get_property

                                                                        This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                                                                        +

                                                                        Parameters

                                                                        • propertyName : STRING

                                                                          The property to return info about.

                                                                          +

                                                                        • callback : CallBackHandler Optional

                                                                        Async Callback Returning Parameters: STRING

                                                                          Synchronous Return:

                                                                          • STRING :

                                                                            The property to return info about.

                                                                            + : 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.System.getProperty(STRING propertyName, CallBackHandler callback)
                                                                            • Ruby: Rho::System.getProperty(STRING propertyName, CallBackHandler callback)

                                                                          getRegistrySetting(HASH propertyMap)

                                                                          Retrieve a value from the device registry. Only applicable on Windows Mobile / Embedded Handheld and CE devices. When running on RhoSimulator, this method is supported only for Windows OS.

                                                                          +

                                                                          Parameters

                                                                          • propertyMap : HASH

                                                                            Map of properties associated with the registry key being set.

                                                                            +

                                                                            • hive : STRING

                                                                              The hive name, see setRegistrySetting.

                                                                              +

                                                                            • key : STRING

                                                                              Full path of the key, including ‘\’ separators as required. Remember to use ‘\’ in JavaScript to specify backslash.

                                                                              +

                                                                            • setting : STRING

                                                                              The name of the setting to be retrieved.

                                                                              +

                                                                          Synchronous Return:

                                                                          • STRING :

                                                                            Registry value of the key.

                                                                            +

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.getRegistrySetting(HASH propertyMap)
                                                                            • Ruby: Rho::System.getRegistrySetting(HASH propertyMap)

                                                                          getStartParams()

                                                                          Return the command line parameters. At Android start parameters are returned as URL query string starting with ‘?’, name-value delimiter ‘=’ and name value pairs delimiter ‘&’.

                                                                          +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

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

                                                                          get_locale()

                                                                          Deprecated

                                                                          Use System.locale property: Current device locale.

                                                                          +

                                                                          Synchronous Return:

                                                                          • STRING

                                                                          Method Access:

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

                                                                          hideSplashScreen()

                                                                          Hide Splash Screen if delay is configured as -1 in rhoconfig.txt

                                                                          +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

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

                                                                          isApplicationInstalled(STRING applicationName)

                                                                          Replaces: app_installed?

                                                                          Checks if the specified applicationName is installed on the device.

                                                                          +

                                                                          Parameters

                                                                          • applicationName : STRING

                                                                            The name of the application.

                                                                            +

                                                                          Synchronous Return:

                                                                          • BOOLEAN

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.isApplicationInstalled(STRING applicationName)
                                                                            • Ruby: Rho::System.isApplicationInstalled(STRING applicationName)

                                                                          isBlobAttr(STRING partition, INTEGER sourceID, STRING attrName)

                                                                          Deprecated

                                                                          Use Database.SQLite3.isBlobAttr: is model attribute is blob.

                                                                          +

                                                                          Parameters

                                                                          • partition : STRING

                                                                          • sourceID : INTEGER

                                                                          • attrName : STRING

                                                                          Synchronous Return:

                                                                          • BOOLEAN

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.isBlobAttr(STRING partition, INTEGER sourceID, STRING attrName)
                                                                            • Ruby: Rho::System.isBlobAttr(STRING partition, INTEGER sourceID, STRING attrName)

                                                                          openUrl(STRING url)

                                                                          Open the application associated with the URL. Behavior may be different on different platforms and depend on installed software. For example, open URL with http:// prefix will execute the Web Browser installed on system and open URL in executed browser. Note: For opening pdf files on android devices it is necessary to add option “no_compression: [ pdf ]” to android section in build.yml. In android, “sms:”,“mailto:”,“tel:”,“http:”,“https:”,“file:” are supported. For file url the proper permission and path has to be given. For external storage space fully qualified path has to be given.(Example:-file:///storage/sdcard/sample.jpg). Hence only external storage space and userFolder are supported for file uri in android.

                                                                          +

                                                                          Parameters

                                                                          • url : STRING

                                                                            URL as string.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.openUrl(STRING url)
                                                                            • Ruby: Rho::System.openUrl(STRING url)

                                                                          runApplication(STRING appName, STRING params, BOOLEAN blockingCall)

                                                                          Replaces: run_app

                                                                          Run an application.

                                                                          +

                                                                          Parameters

                                                                          • appName : STRING

                                                                            The name of the application on the device to run. It depends from platform. On iOS it is BundleURLScheme of executed application.

                                                                            +

                                                                          • params : STRING Optional

                                                                            Start parameters string. Executed Application can receive this string by getStartParams method. Parameter could be just value, or key-value pair separated by ‘=’ sign. Please note that for each platform there are distinct ways to write several params at once. On Android parameters should be separated by an amperstand, on other platforms by a comma or a space.

                                                                            +

                                                                          • blockingCall : BOOLEAN Optional

                                                                            Not Implemented.

                                                                            +

                                                                            False by default.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.runApplication(STRING appName, STRING params, BOOLEAN blockingCall)
                                                                            • Ruby: Rho::System.runApplication(STRING appName, STRING params, BOOLEAN blockingCall)

                                                                          setDoNotBackupAttribute(STRING pathToFile, BOOLEAN doNotBackup)

                                                                          Replaces: set_do_not_bakup_attribute

                                                                          Set do not backup attribute for file.

                                                                          +

                                                                          Parameters

                                                                          • pathToFile : STRING

                                                                            Path to file.

                                                                            +

                                                                          • doNotBackup : BOOLEAN

                                                                            True set doNotBackup attribute to file (exclude this file from backup), false for remove doNotBackup attribute from file.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setDoNotBackupAttribute(STRING pathToFile, BOOLEAN doNotBackup)
                                                                            • Ruby: Rho::System.setDoNotBackupAttribute(STRING pathToFile, BOOLEAN doNotBackup)

                                                                          setNetworkStatusNotify(STRING url, INTEGER poll_interval)

                                                                          Deprecated

                                                                          Use Network.setStatusNotify: set network notification callback.

                                                                          +

                                                                          Parameters

                                                                          • url : STRING

                                                                            The url to the user-defined callback method.

                                                                            +

                                                                          • poll_interval : INTEGER

                                                                            IOS. The network status polling period for systems that can not notify network status change immediately. Default value is 20 seconds.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setNetworkStatusNotify(STRING url, INTEGER poll_interval)
                                                                            • Ruby: Rho::System.setNetworkStatusNotify(STRING url, INTEGER poll_interval)

                                                                          setProperties(HASH propertyMap)

                                                                          This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                          +

                                                                          Parameters

                                                                          • propertyMap : HASH

                                                                            Map of properties I want to set

                                                                            +

                                                                            • Object : STRING

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setProperties(HASH propertyMap)
                                                                            • Ruby: Rho::System.setProperties(HASH propertyMap)

                                                                          setProperty(STRING propertyName, STRING propertyValue)

                                                                          This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                          +

                                                                          Parameters

                                                                          • propertyName : STRING

                                                                            The one property name that I want to set

                                                                            +

                                                                          • propertyValue : STRING

                                                                            The one property value that I want to set

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setProperty(STRING propertyName, STRING propertyValue)
                                                                            • Ruby: Rho::System.setProperty(STRING propertyName, STRING propertyValue)

                                                                          setPushNotification(STRING url, STRING url_params, STRING push_client)

                                                                          Deprecated

                                                                          Use Push.setPushNotification: Register push callback, the method to call upon receiving a push message.

                                                                          +

                                                                          Parameters

                                                                          • url : STRING

                                                                            URL of the callback method. If empty, unregisters rhoconnect-push.

                                                                            +

                                                                          • url_params : STRING Optional

                                                                            Parameters which will be added to callback URL.

                                                                            +

                                                                          • push_client : STRING Optional

                                                                            Name of a push service client. Current values can be ‘rhoconnect_push’ or ‘gcm’ or ‘legacy’ or empty.

                                                                            +

                                                                            The call will be applied to every push client.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setPushNotification(STRING url, STRING url_params, STRING push_client)
                                                                            • Ruby: Rho::System.setPushNotification(STRING url, STRING url_params, STRING push_client)

                                                                          setRegistrySetting(HASH propertyMap)

                                                                          Set a value in the device registry. Only applicable on Windows Mobile / Embedded Handheld and CE devices. When running on RhoSimulator, this method is supported only for Windows OS.

                                                                          +

                                                                          Parameters

                                                                          • propertyMap : HASH

                                                                            Map of properties associated with the registry key being set.

                                                                            +

                                                                            • hive : STRING

                                                                              The hive name.

                                                                              +

                                                                              Possible Values :

                                                                              Constant: Rho::System.REGKEY_CLASSES_ROOT (For Ruby use "::" for all "." when referencing constants)
                                                                              String:HKCR

                                                                              Set the property in the HKEY_CLASSES_ROOT hive.

                                                                              +
                                                                              Constant: Rho::System.REGKEY_CURRENT_USER (For Ruby use "::" for all "." when referencing constants)
                                                                              String:HKCU

                                                                              Set the property in the HKEY_CURRENT_USER hive.

                                                                              +
                                                                              Constant: Rho::System.REGKEY_LOCAL_MACHINE (For Ruby use "::" for all "." when referencing constants)
                                                                              String:HKLM

                                                                              Set the property in the HKEY_LOCAL_MACHINE hive.

                                                                              +
                                                                              Constant: Rho::System.REGKEY_USERS (For Ruby use "::" for all "." when referencing constants)
                                                                              String:HKU

                                                                              Set the property in the HKEY_USERS hive.

                                                                              +
                                                                            • type : STRING

                                                                              The type.

                                                                              +

                                                                              Possible Values :

                                                                              Constant: Rho::System.REGTYPE_SZ (For Ruby use "::" for all "." when referencing constants)
                                                                              String:String

                                                                              The type of the value being set is a string.

                                                                              +
                                                                              Constant: Rho::System.REGTYPE_BINARY (For Ruby use "::" for all "." when referencing constants)
                                                                              String:Binary

                                                                              The type of the value being set is a binary number.

                                                                              +
                                                                              Constant: Rho::System.REGTYPE_DWORD (For Ruby use "::" for all "." when referencing constants)
                                                                              String:DWORD

                                                                              The type of the value being set is a natural number (DWORD)

                                                                              +
                                                                              Constant: Rho::System.REGTYPE_MULTI_SZ (For Ruby use "::" for all "." when referencing constants)
                                                                              String:MultiSZ

                                                                              The type of the value being set is a multi line string. Separate your lines with \n (\n in JavaScript)

                                                                              +
                                                                            • key : STRING

                                                                              Full path of the key, including ‘\’ separators as required. Remember to use ‘\’ in JavaScript to specify backslash.

                                                                              +

                                                                            • setting : STRING

                                                                              The name of the registry setting to be set.

                                                                              +

                                                                            • value : STRING

                                                                              The registry value to be set.

                                                                              +

                                                                            • persistent : BOOLEAN

                                                                              Whether or not to create a corresponding merge file, setting to true will cause your value to persist across a device clean boot. A .reg file is written to the \Application folder on the device to persist the setting.

                                                                              +

                                                                          Synchronous Return:

                                                                          • BOOLEAN :

                                                                            Whether or not the registry key was successfully set.

                                                                            +

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setRegistrySetting(HASH propertyMap)
                                                                            • Ruby: Rho::System.setRegistrySetting(HASH propertyMap)

                                                                          setScreenRotationNotification(STRING url, STRING url_params)

                                                                          Deprecated

                                                                          Use ScreenOrientation.setScreenOrientationEvent: Notify (call a callback method) when the screen rotates.

                                                                          +

                                                                          Parameters

                                                                          • url : STRING

                                                                            URL of the callback method. If empty, unregisters notification callback.

                                                                            +

                                                                          • url_params : STRING Optional

                                                                            Parameters which will be added to callback URL.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setScreenRotationNotification(STRING url, STRING url_params)
                                                                            • Ruby: Rho::System.setScreenRotationNotification(STRING url, STRING url_params)

                                                                          setWindowFrame(INTEGER x, INTEGER y, INTEGER width, INTEGER height)

                                                                          Change application window position and size.

                                                                          +

                                                                          Parameters

                                                                          • x : INTEGER

                                                                            Left corner of window.

                                                                            +

                                                                          • y : INTEGER

                                                                            Top corner of window.

                                                                            +

                                                                          • width : INTEGER

                                                                            Width of window.

                                                                            +

                                                                          • height : INTEGER

                                                                            Height of window.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setWindowFrame(INTEGER x, INTEGER y, INTEGER width, INTEGER height)
                                                                            • Ruby: Rho::System.setWindowFrame(INTEGER x, INTEGER y, INTEGER width, INTEGER height)

                                                                          setWindowPosition(INTEGER x, INTEGER y)

                                                                          Change application window position.

                                                                          +

                                                                          Parameters

                                                                          • x : INTEGER

                                                                            Left corner of window.

                                                                            +

                                                                          • y : INTEGER

                                                                            Top corner of window.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setWindowPosition(INTEGER x, INTEGER y)
                                                                            • Ruby: Rho::System.setWindowPosition(INTEGER x, INTEGER y)

                                                                          setWindowSize(INTEGER width, INTEGER height)

                                                                          Change application window size.

                                                                          +

                                                                          Parameters

                                                                          • width : INTEGER

                                                                            Width of the window.

                                                                            +

                                                                          • height : INTEGER

                                                                            Width of the of window.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.setWindowSize(INTEGER width, INTEGER height)
                                                                            • Ruby: Rho::System.setWindowSize(INTEGER width, INTEGER height)

                                                                          set_application_icon_badge(INTEGER badgeNumber)

                                                                          Deprecated

                                                                          Use System.applicationIconBadge: Set the application icon to have this badge number. Set to 0 (zero) to remove badge.iOS only.

                                                                          +

                                                                          Parameters

                                                                          • badgeNumber : INTEGER

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.set_application_icon_badge(INTEGER badgeNumber)
                                                                            • Ruby: Rho::System.set_application_icon_badge(INTEGER badgeNumber)

                                                                          set_http_proxy_url(STRING proxyURI)

                                                                          Deprecated

                                                                          Use System.httpProxyURI property: To use client with the HTTP proxy.

                                                                          +

                                                                          Parameters

                                                                          • proxyURI : STRING

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.set_http_proxy_url(STRING proxyURI)
                                                                            • Ruby: Rho::System.set_http_proxy_url(STRING proxyURI)

                                                                          set_locale(STRING locale_code, STRING country_code)

                                                                          Deprecated

                                                                          Use Application.setLocale method: set application specific locale.

                                                                          +

                                                                          Parameters

                                                                          • locale_code : STRING

                                                                          • country_code : STRING

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.set_locale(STRING locale_code, STRING country_code)
                                                                            • Ruby: Rho::System.set_locale(STRING locale_code, STRING country_code)

                                                                          set_sleeping(BOOLEAN enable)

                                                                          Deprecated

                                                                          Use System.screenSleeping property: enable / disable phone sleeping.

                                                                          +

                                                                          Parameters

                                                                          • enable : BOOLEAN

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.set_sleeping(BOOLEAN enable)
                                                                            • Ruby: Rho::System.set_sleeping(BOOLEAN enable)

                                                                          startTimer(INTEGER interval, STRING url, STRING url_params)

                                                                          Deprecated

                                                                          Start timer. (It’s works only with Ruby)

                                                                          +

                                                                          Parameters

                                                                          • interval : INTEGER

                                                                            Timer interval.

                                                                            +

                                                                          • url : STRING

                                                                            URL of the callback method.

                                                                            +

                                                                          • url_params : STRING Optional

                                                                            Parameters which will be added to callback URL.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.startTimer(INTEGER interval, STRING url, STRING url_params)
                                                                            • Ruby: Rho::System.startTimer(INTEGER interval, STRING url, STRING url_params)

                                                                          stopTimer(STRING url)

                                                                          Deprecated

                                                                          Stop timer. (It’s works only with Ruby)

                                                                          +

                                                                          Parameters

                                                                          • url : STRING

                                                                            URL of the callback method which identify the timer to stop.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.stopTimer(STRING url)
                                                                            • Ruby: Rho::System.stopTimer(STRING url)

                                                                          unset_http_proxy()

                                                                          Deprecated

                                                                          Use System.httpProxyURI property: Stop using HTTP proxy that was set by the command line, rhoconfig.txt or set_http_proxy_url.

                                                                          +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

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

                                                                          unzipFile(STRING localPathToZip, STRING password, STRING outputFileName)

                                                                          Unzip file.

                                                                          +

                                                                          Parameters

                                                                          • localPathToZip : STRING

                                                                            The path to the file to be unzipped. Application should have write permissions to this folder.

                                                                            +

                                                                          • password : STRING Optional

                                                                            Password for the zip.

                                                                            +

                                                                          • outputFileName : STRING Optional

                                                                            Output file name. Used when decompressing gzip streams.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.unzipFile(STRING localPathToZip, STRING password, STRING outputFileName)
                                                                            • Ruby: Rho::System.unzipFile(STRING localPathToZip, STRING password, STRING outputFileName)

                                                                          updateBlobAttribs(STRING partition, INTEGER sourceID)

                                                                          Deprecated

                                                                          Use Database.updateBlobAttribs: update model blob attributes list.

                                                                          +

                                                                          Parameters

                                                                          • partition : STRING

                                                                          • sourceID : INTEGER

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.updateBlobAttribs(STRING partition, INTEGER sourceID)
                                                                            • Ruby: Rho::System.updateBlobAttribs(STRING partition, INTEGER sourceID)

                                                                          zipFile(STRING localPathToZip, STRING localPathToFile, STRING password)

                                                                          Zip one file. Zip archive must placed to the folder where application can write files.

                                                                          +

                                                                          Parameters

                                                                          • localPathToZip : STRING

                                                                            The path to the specified zip. Application should have write permissions to this folder.

                                                                            +

                                                                          • localPathToFile : STRING

                                                                            The path to the file to be zipped.

                                                                            +

                                                                          • password : STRING Optional

                                                                            Password for the zip.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.zipFile(STRING localPathToZip, STRING localPathToFile, STRING password)
                                                                            • Ruby: Rho::System.zipFile(STRING localPathToZip, STRING localPathToFile, STRING password)

                                                                          zipFiles(STRING localPathToZip, STRING basePath, ARRAY filePathsToZip, STRING password)

                                                                          Zip list of files.

                                                                          +

                                                                          Parameters

                                                                          • localPathToZip : STRING

                                                                            The path to the specified zip.

                                                                            +

                                                                          • basePath : STRING

                                                                            Base path to the files to be zipped.

                                                                            +

                                                                          • filePathsToZip : ARRAY

                                                                            List of file paths to be zipped.

                                                                            +

                                                                          • password : STRING Optional

                                                                            Password for the zip.

                                                                            +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Class Method: This method can only be accessed via the API class object.
                                                                            • JavaScript: Rho.System.zipFiles(STRING localPathToZip, STRING basePath, ARRAY filePathsToZip, STRING password)
                                                                            • Ruby: Rho::System.zipFiles(STRING localPathToZip, STRING basePath, ARRAY filePathsToZip, STRING password)
                                                                          + +

                                                                          Properties

                                                                          + +

                                                                          applicationIconBadge : INTEGER

                                                                          Set the application icon to have this badge number. Set to 0 (zero) to remove badge.

                                                                          +

                                                                          Property Access:

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

                                                                          country : STRING Read Only

                                                                          Current device country code.

                                                                          +

                                                                          Property Access:

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

                                                                          deviceName : STRING Read Only

                                                                          Name of device application running on. Examples: ‘9000’ (BB), ‘iPhone’, ‘dream’ (Android). In Consumer Android device, name of the Industrial Design along with manufacturer name shall be shown.

                                                                          +

                                                                          Property Access:

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

                                                                          deviceOwnerEmail : STRING Read Only

                                                                          Primary email of phone owner. To access this property ‘pim’ capability must be enabled in your build.yml.

                                                                          +

                                                                          Property Access:

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

                                                                          deviceOwnerName : STRING Read Only

                                                                          Name(account name) of phone owner. To access this property ‘pim’ capability must be enabled in your build.yml.

                                                                          +

                                                                          Property Access:

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

                                                                          devicePushId : STRING Read Only

                                                                          Replaces:deviceId

                                                                          Push notifications device ID which may be used to receive push messages.To get this ID , Push service should be configured on the device. Please refer to Push documentation.

                                                                          +

                                                                          Property Access:

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

                                                                          freeServerPort : INTEGER Read Only

                                                                          Get free local server port, available for binding.

                                                                          +

                                                                          Property Access:

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

                                                                          hasCalendar : BOOLEAN Read Only

                                                                          Returns true if calendar support is available.

                                                                          +

                                                                          Property Access:

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

                                                                          hasCamera : BOOLEAN Read Only

                                                                          Returns true if there is a camera available on the device.

                                                                          +

                                                                          Property Access:

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

                                                                          hasCellNetwork : BOOLEAN Read Only

                                                                          Deprecated

                                                                          Use Network.hasCellNetwork to tell if device is connected to the cell network.

                                                                          +

                                                                          Property Access:

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

                                                                          hasNetwork : BOOLEAN Read Only

                                                                          Deprecated

                                                                          Use Network.hasNetwork to tell if the device is connected to the network.

                                                                          +

                                                                          Property Access:

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

                                                                          hasSqlite : BOOLEAN Read Only

                                                                          Deprecated

                                                                          Returns true if the device has sqlite capabilities (previously only BlackBerry did not support this).

                                                                          +

                                                                          Property Access:

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

                                                                          hasTouchscreen : BOOLEAN Read Only

                                                                          Returns true if the device has touch screen capabilities. For Win32 desktop builds this API will return whether mouse support is available.

                                                                          +

                                                                          Property Access:

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

                                                                          hasWifiNetwork : BOOLEAN Read Only

                                                                          Deprecated

                                                                          Use Network.hasWifiNetwork to tell if the device is connected to the wifi network.

                                                                          +

                                                                          Property Access:

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

                                                                          httpProxyURI : STRING

                                                                          Replaces:http_proxy_url

                                                                          Set HTTP proxy parameters for using the Network module. Example: ‘user:password@url:port’. Supports basic authentication only. Do not include ‘http://’. Setting this property overrides http_proxy_uri, http_proxy_host, http_proxy_port, http_proxy_user and http_proxy_password. Proxy settings for Windows Mobile/CE with Zebra WebKit should be configured in the config.xml file.

                                                                          +

                                                                          Property Access:

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

                                                                          isEmulator : BOOLEAN Read Only

                                                                          Returns true if the application is running on a platform emulator.

                                                                          +

                                                                          Property Access:

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

                                                                          isMotorolaDevice : BOOLEAN Read Only

                                                                          Deprecated

                                                                          Returns true if the device supports Motorola device capabilities. APIs will indicate if the property or method is available on Motorola devices only. You can use this property to help your application decide when to take advantage of advanced Motorola capabilities. This property has been deprecated. It is recommended to use ‘isSymbolDevice’ property.

                                                                          +

                                                                          Property Access:

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

                                                                          isRhoSimulator : BOOLEAN Read Only

                                                                          Returns true if the application is running on RhoSimulator.

                                                                          +

                                                                          Property Access:

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

                                                                          isSymbolDevice : BOOLEAN Read Only

                                                                          Returns true if the device supports Symbol device capabilities. APIs will indicate if the property or method is available on Symbol devices only. You can use this property to help your application decide when to take advantage of advanced Symbol capabilities.

                                                                          +

                                                                          Property Access:

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

                                                                          keyboardState : STRING

                                                                          For Windows Mobile and Windows CE the keyboard can be manually shown or hidden as required. All other platforms only support ‘automatic’. The default state for Windows Mobile and Windows CE is manual, for all other platforms it is automatic.

                                                                          +

                                                                          Default: See Description

                                                                          Possible Values (STRING):

                                                                          Constant: Rho.System.KEYBOARD_SHOWN (For Ruby use "::" for all "." when referencing constants)
                                                                          String: shown

                                                                          Shows the on screen keyboard, after setting the keyboard to shown or hidden it will no longer appear / disappear automatically until you set this property to automatic.

                                                                          +
                                                                          Constant: Rho.System.KEYBOARD_HIDDEN (For Ruby use "::" for all "." when referencing constants)
                                                                          String: hidden

                                                                          Hides the on screen keyboard, after setting the keyboard to shown or hidden it will no longer appear / disappear automatically until you set this property to automatic. This is most useful if your device has a hardware keyboard or you are scanning / capturing data to an input field.

                                                                          +
                                                                          Constant: Rho.System.KEYBOARD_AUTOMATIC (For Ruby use "::" for all "." when referencing constants)
                                                                          String: automatic

                                                                          Automatically shows or hides the keyboard as needed by the application.

                                                                          +

                                                                          Property Access:

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

                                                                          localServerPort : INTEGER Read Only

                                                                          Port of the local (embedded) HTTP server. This parameter is mainly for debug purposes. If not specified, the platform will detect a free port on the device and use that one.

                                                                          +

                                                                          Default: 8080

                                                                          Property Access:

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

                                                                          locale : STRING Read Only

                                                                          Current device locale Like ‘en’, ‘ru’ etc.

                                                                          +

                                                                          Property Access:

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

                                                                          lockWindowSize : BOOLEAN

                                                                          Lock / unlock the window size change by the user. When running on RhoSimulator, this method is supported only for Windows OS.

                                                                          +

                                                                          Default: false

                                                                          Property Access:

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

                                                                          oemInfo : STRING Read Only

                                                                          The OEM Information string for the terminal.

                                                                          +

                                                                          Property Access:

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

                                                                          osVersion : STRING Read Only

                                                                          Version OS of device. Examples: ‘4.1’ (Android).

                                                                          +

                                                                          Property Access:

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

                                                                          phoneId : STRING Read Only

                                                                          Hardware based ID. It depends on capabilities configured for an application and has to remain same even across application uninstall/install.

                                                                          +

                                                                          Property Access:

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

                                                                          platform : STRING Read Only

                                                                          Platform where application is running.

                                                                          +

                                                                          Possible Values (STRING):

                                                                          Constant: Rho.System.PLATFORM_WM_CE (For Ruby use "::" for all "." when referencing constants)
                                                                          String: WINDOWS
                                                                          Constant: Rho.System.PLATFORM_ANDROID (For Ruby use "::" for all "." when referencing constants)
                                                                          String: ANDROID
                                                                          Constant: Rho.System.PLATFORM_IOS (For Ruby use "::" for all "." when referencing constants)
                                                                          String: APPLE
                                                                          Constant: Rho.System.PLATFORM_WP8 (For Ruby use "::" for all "." when referencing constants)
                                                                          String: WP8
                                                                          Constant: Rho.System.PLATFORM_WINDOWS_DESKTOP (For Ruby use "::" for all "." when referencing constants)
                                                                          String: WINDOWS_DESKTOP

                                                                          Property Access:

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

                                                                          ppiX : INTEGER Read Only

                                                                          Horizontal PPI (Pixels Per Inch).

                                                                          +

                                                                          Property Access:

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

                                                                          ppiY : INTEGER Read Only

                                                                          Vertical PPI (Pixels Per Inch).

                                                                          +

                                                                          Property Access:

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

                                                                          realScreenHeight : INTEGER Read Only

                                                                          Screen height in real pixels.

                                                                          +

                                                                          Property Access:

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

                                                                          realScreenWidth : INTEGER Read Only

                                                                          Screen width in real pixels.

                                                                          +

                                                                          Property Access:

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

                                                                          screenAutoRotate : BOOLEAN

                                                                          Screen auto rotate.

                                                                          +

                                                                          Default: true

                                                                          Property Access:

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

                                                                          screenHeight : INTEGER Read Only

                                                                          Screen height in logical pixels (used for set coordinates).

                                                                          +

                                                                          Property Access:

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

                                                                          screenOrientation : STRING Read Only

                                                                          Current screen orientation.

                                                                          +

                                                                          Possible Values (STRING):

                                                                          Constant: Rho.System.SCREEN_PORTRAIT (For Ruby use "::" for all "." when referencing constants)
                                                                          String: portrait

                                                                          The return value if the screen is in portrait mode.

                                                                          +
                                                                          Constant: Rho.System.SCREEN_LANDSCAPE (For Ruby use "::" for all "." when referencing constants)
                                                                          String: landscape

                                                                          The return value if the screen is in landscape mode.

                                                                          +

                                                                          Property Access:

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

                                                                          screenSleeping : BOOLEAN

                                                                          If true, then screen will go to sleep by system inactivity timeout. If false then screen never go to sleep while application is in foreground.

                                                                          +

                                                                          Property Access:

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

                                                                          screenWidth : INTEGER Read Only

                                                                          Screen width in logical pixels (used for set coordinates).

                                                                          +

                                                                          Property Access:

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

                                                                          uuid : STRING Read Only

                                                                          The Unique Unit IDentifier for the terminal.

                                                                          +

                                                                          Property Access:

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

                                                                          webviewFramework : STRING Read Only

                                                                          Browser framework identity string.

                                                                          +

                                                                          Property Access:

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

                                                                          Examples

                                                                          + +
                                                                          Get device capabilities
                                                                          +

                                                                          You can find out whether the device has access to several system-dependent features such as calendar, camera, touchscreen, etc.

                                                                          +
                                                                          :::javascript
                                                                          +
                                                                          +// Returns true if device supports Symbol device capabilities, such as Scanner, etc.
                                                                          +var is_symbol_device = Rho.System.isSymbolDevice;
                                                                          +
                                                                          +var has_calendar = Rho.System.hasCalendar;
                                                                          +var has_camera = Rho.System.hasCamera;
                                                                          +var has_cell_network = Rho.System.hasCellNetwork;
                                                                          +var has_wifi_network = Rho.System.hasWifiNetwork;
                                                                          +var has_network = Rho.System.hasNetwork;
                                                                          +var has_sqlite = Rho.System.hasSqlite;
                                                                          +var has_touchscreen = Rho.System.hasTouchscreen;
                                                                          +
                                                                          +message = "Symbol device: "+is_symbol_device+"\n"+
                                                                          +  "Calendar: "+has_calendar+"\n"+
                                                                          +  "Camera: "+has_camera+"\n"+
                                                                          +  "Cell network: "+has_cell_network+"\n"+
                                                                          +  "WiFi: "+has_wifi_network+"\n"+
                                                                          +  "Network: "+has_network+"\n"+
                                                                          +  "SQLite: "+has_sqlite+"\n"+
                                                                          +  "Touchscreen: "+has_touchscreen;
                                                                          +
                                                                          +alert(message);
                                                                          +
                                                                          +                            
                                                                          :::ruby
                                                                          +
                                                                          +# Returns true if device supports Symbol device capabilities, such as barcode scanner, etc.
                                                                          +is_symbol_device = Rho::System.isSymbolDevice
                                                                          +
                                                                          +has_calendar = Rho::System.hasCalendar
                                                                          +has_camera = Rho::System.hasCamera
                                                                          +has_cell_network = Rho::System.hasCellNetwork
                                                                          +has_wifi_network = Rho::System.hasWifiNetwork
                                                                          +has_network = Rho::System.hasNetwork
                                                                          +has_sqlite = Rho::System.hasSqlite
                                                                          +has_touchscreen = Rho::System.hasTouchscreen
                                                                          +
                                                                          +message = "
                                                                          +Symbol device: #{is_symbol_device}
                                                                          +Calendar: #{has_calendar}
                                                                          +Camera: #{has_camera}
                                                                          +Cell network: #{has_cell_network}
                                                                          +WiFi: #{has_wifi_network}
                                                                          +Network: #{has_network}
                                                                          +SQLite: #{has_sqlite}
                                                                          +Touchscreen: #{has_touchscreen}
                                                                          +"
                                                                          +Alert.show_popup(message)
                                                                          +
                                                                          +                            
                                                                          Get version information
                                                                          +

                                                                          Retrieve the version of the underlying Operating System.

                                                                          +
                                                                          :::javascript
                                                                          +
                                                                          +var version_info = Rho.System.osVersion;
                                                                          +alert(version_info);
                                                                          +
                                                                          +                                
                                                                          :::ruby
                                                                          +
                                                                          +version_info = Rho::System.osVersion
                                                                          +Alert.show_popup(version_info)
                                                                          +
                                                                          +                                
                                                                          Install / uninstall other applications
                                                                          +

                                                                          You can ask the system to install or uninstall a different application. This feature is useful for installing sub-applications, custom upgrades, etc.

                                                                          +
                                                                          :::javascript
                                                                          +
                                                                          +// install an application from given url
                                                                          +Rho.System.applicationInstall("/bin/target/android/rhodes-app-debug.apk");
                                                                          +
                                                                          +// uninstall the application
                                                                          +Rho.System.applicationUninstall("rhodes-app");
                                                                          +
                                                                          +                                
                                                                          :::ruby
                                                                          +
                                                                          +#install an application from given url
                                                                          +Rho::System.applicationInstall("/bin/target/android/rhodes-app-debug.apk")
                                                                          +
                                                                          +# uninstall the application
                                                                          +Rho::System.applicationUninstall("rhodes-app")
                                                                          +
                                                                          +                                
                                                                          Get the local server port for debug purposes
                                                                          +

                                                                          If necessary, you can read the embedded HTTP server’s port, for debugging purposes.

                                                                          +
                                                                          :::javascript
                                                                          +
                                                                          +// Get port of the local (embedded) HTTP server
                                                                          +var local_port = Rho.System.localServerPort;
                                                                          +alert(local_port);
                                                                          +
                                                                          +                                
                                                                          :::ruby
                                                                          +
                                                                          +# Get port of the local (embedded) HTTP served
                                                                          +local_port = Rho::System.localServerPort()
                                                                          +Alert.show_popup(local_port)
                                                                          +
                                                                          +                                
                                                                          Zipping and unzipping files
                                                                          +

                                                                          If you ever need to build or extract zip archives, RhoMobile includes easy-to-use APIs for this task.

                                                                          +
                                                                          :::javascript
                                                                          +
                                                                          +// unzip file
                                                                          +Rho.System.unzipFile("/app/public/sample.zip");
                                                                          +
                                                                          +// zip file
                                                                          +Rho.System.zipFile("/app/public/zipfile.zip", "/app/public/sample.txt");
                                                                          +
                                                                          +                                
                                                                          :::ruby
                                                                          +
                                                                          +# unzip a file
                                                                          +Rho::System.unzipFile("/app/public/sample.zip")
                                                                          +
                                                                          +# zip a file
                                                                          +Rho::System.zipFile("/app/public", "/app/public/sample.txt")
                                                                          +
                                                                          +                                
                                                                          Working with the Windows Registry
                                                                          +

                                                                          On devices running Windows Mobile, Windows CE, Windows Embedded Handheld and Windows Embedded CE it is possible to interact with the registry, this example shows how to do that.

                                                                          +
                                                                          :::ruby
                                                                          +
                                                                          +#/app/Model
                                                                          +
                                                                          +#  Retrieve a value from the Registry
                                                                          +def get_registry_sync
                                                                          +    theRegSetting = Rho::System.getRegistrySetting({hive:'HKLM', key:'software', Setting:'RhoElementsTest'})
                                                                          +    puts "Registry Setting retrieved: #{theRegSetting}"
                                                                          +end
                                                                          +
                                                                          +#  Set a value in the registry which will persist across a clean boot of the device
                                                                          +def set_registry_sync
                                                                          +    theRegSetting = Rho::System.setRegistrySetting({hive:'HKLM', type:'String', key:'Software', setting:'RhoElementsTest', value:'MVC ftw', persistent:true})
                                                                          +    puts "Registry Setting Success?: #{theRegSetting}"
                                                                          +end
                                                                          +
                                                                          +#  Delete a value from the registry
                                                                          +def delete_registry_sync
                                                                          +    theRegSetting = Rho::System.deleteRegistrySetting({hive:'HKLM', key:'Software', setting:'RhoElementsTest', persistent:true})
                                                                          +    puts "Registry Deleting Success?: #{theRegSetting}"
                                                                          +end
                                                                          +
                                                                          +                            
                                                                          \ No newline at end of file diff --git a/docs/en/5.5/api/system.xml b/docs/en/5.5/api/system.xml new file mode 100644 index 00000000..ccbbb7f7 --- /dev/null +++ b/docs/en/5.5/api/system.xml @@ -0,0 +1,901 @@ + + + + + The System API is used to control and modify core aspects of the device such as the screen, OS and device capabilities. + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the System API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the System API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.system.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + The System API supports the following properties. + + + + + + It is internal property for using in debugger (signal for main window close). + + + Platform where application is running. + + + + + + + + + + + + + + + + + + WM, CE, Win32, Android + + + Returns true if there is a camera available on the device. + WM, CE, Android, iOS + + + Screen width in logical pixels (used for set coordinates). + + + Screen height in logical pixels (used for set coordinates). + + + Screen width in real pixels. + + + Screen height in real pixels. + + + Current screen orientation. + + + The return value if the screen is in portrait mode. + + + The return value if the screen is in landscape mode. + + + + + Horizontal PPI (Pixels Per Inch). + + + Vertical PPI (Pixels Per Inch). + + + + Primary email of phone owner. To access this property 'pim' capability must be enabled in your build.yml. + Android + + + Name(account name) of phone owner. To access this property 'pim' capability must be enabled in your build.yml. + Android + + + Push notifications device ID which may be used to receive push messages.To get this ID , Push service should be configured on the device. Please refer to Push documentation. + + + Hardware based ID. It depends on capabilities configured for an application and has to remain same even across application uninstall/install. + WM, CE, Android + + + Name of device application running on. Examples: '9000' (BB), 'iPhone', 'dream' (Android). In Consumer Android device, name of the Industrial Design along with manufacturer name shall be shown. + + + Version OS of device. Examples: '4.1' (Android). + + + Current device locale Like 'en', 'ru' etc. + + + Current device country code. + + + Returns true if the application is running on a platform emulator. + + + Returns true if the application is running on RhoSimulator. + + + Returns true if calendar support is available. + + + Returns true if the device supports Symbol device capabilities. APIs will indicate if the property or method is available on Symbol devices only. You can use this property to help your application decide when to take advantage of advanced Symbol capabilities. + + + Returns true if the device supports Motorola device capabilities. APIs will indicate if the property or method is available on Motorola devices only. You can use this property to help your application decide when to take advantage of advanced Motorola capabilities. This property has been deprecated. It is recommended to use 'isSymbolDevice' property. + + + The OEM Information string for the terminal. + + WM, CE, Android + + + The Unique Unit IDentifier for the terminal. + + WM, CE, Android + + + Set the application icon to have this badge number. Set to 0 (zero) to remove badge. + iOS + + + Set HTTP proxy parameters for using the Network module. Example: 'user:password@url:port'. Supports basic authentication only. Do not include 'http://'. Setting this property overrides http_proxy_uri, http_proxy_host, http_proxy_port, http_proxy_user and http_proxy_password. Proxy settings for Windows Mobile/CE with Zebra WebKit should be configured in the config.xml file. + Android, iOS, WM, Win32 + WM, Win32, Android + + + Lock / unlock the window size change by the user. When running on RhoSimulator, this method is supported only for Windows OS. + Win32 + + + For Windows Mobile and Windows CE the keyboard can be manually shown or hidden as required. All other platforms only support 'automatic'. The default state for Windows Mobile and Windows CE is manual, for all other platforms it is automatic. + WM + + + + Shows the on screen keyboard, after setting the keyboard to shown or hidden it will no longer appear / disappear automatically until you set this property to automatic. + + + Hides the on screen keyboard, after setting the keyboard to shown or hidden it will no longer appear / disappear automatically until you set this property to automatic. This is most useful if your device has a hardware keyboard or you are scanning / capturing data to an input field. + + + Automatically shows or hides the keyboard as needed by the application. + + + + + Port of the local (embedded) HTTP server. This parameter is mainly for debug purposes. If not specified, the platform will detect a free port on the device and use that one. + + + Get free local server port, available for binding. + + + Screen auto rotate. + Android, iOS + Android + + + Returns true if the device has touch screen capabilities. For Win32 desktop builds this API will return whether mouse support is available. + + + Browser framework identity string. + + + If true, then screen will go to sleep by system inactivity timeout. If false then screen never go to sleep while application is in foreground. + Android, iOS + WM, Android + + + Use Network.hasNetwork to tell if the device is connected to the network. + + + Use Network.hasWifiNetwork to tell if the device is connected to the wifi network. + + + Use Network.hasCellNetwork to tell if device is connected to the cell network. + + + Returns true if the device has sqlite capabilities (previously only BlackBerry did not support this). + + + + + + Use property names methods instead. + + + + + + + + + + + Install an application. + iOS, WM, Win32, Android + WM, Win32, Android + + + The url of an application to install on the device. + + + + + + Checks if the specified applicationName is installed on the device. + iOS, WM, Win32, Android + WM, Win32, Android + + + The name of the application. + + + + + + + Uninstall the application. Not Supported on Windows CE devices. + WM, Win32, Android + + + The name of the application. + + + + + + Return the command line parameters. At Android start parameters are returned as URL query string starting with '?', name-value delimiter '=' and name value pairs delimiter '&'. + + WM, CE, Win32, Android + + + + Open the application associated with the URL. Behavior may be different on different platforms and depend on installed software. For example, open URL with http:// prefix will execute the Web Browser installed on system and open URL in executed browser. Note: For opening pdf files on android devices it is necessary to add option "no_compression: [ pdf ]" to android section in build.yml. In android, "sms:","mailto:","tel:","http:","https:","file:" are supported. For file url the proper permission and path has to be given. For external storage space fully qualified path has to be given.(Example:-file:///storage/sdcard/sample.jpg). Hence only external storage space and userFolder are supported for file uri in android. + + Open the application associated with the URL. Behavior may be different on different platforms and depend on installed software. For example, open URL with http:// prefix will execute the Web Browser installed on system and open URL in executed browser. Note: Opening pdf files on Android devices is not supported. In android, "sms:","mailto:","tel:","http:","https:","file:" are supported. Hence it is recommended to use storage space or userFolder for the file uri. + + + + URL as string. + + + + + + Unzip file. + + + The path to the file to be unzipped. Application should have write permissions to this folder. + + + Password for the zip. + + + + + Output file name. Used when decompressing gzip streams. + + + + + + + + Zip one file. Zip archive must placed to the folder where application can write files. + + + The path to the specified zip. Application should have write permissions to this folder. + + + The path to the file to be zipped. + + + Password for the zip. + + + + + + + Zip list of files. + + + The path to the specified zip. + + + Base path to the files to be zipped. + + + List of file paths to be zipped. + + + Password for the zip. + + + + + + + Set a value in the device registry. Only applicable on Windows Mobile / Embedded Handheld and CE devices. When running on RhoSimulator, this method is supported only for Windows OS. + Set a value in the device registry. Only applicable on Windows Mobile / Embedded Handheld and CE devices. + WM + + + Map of properties associated with the registry key being set. + + + The hive name. + + + Set the property in the HKEY_CLASSES_ROOT hive. + + + Set the property in the HKEY_CURRENT_USER hive. + + + Set the property in the HKEY_LOCAL_MACHINE hive. + + + Set the property in the HKEY_USERS hive. + + + + + The type. + + + The type of the value being set is a string. + + + The type of the value being set is a binary number. + + + The type of the value being set is a natural number (DWORD) + + + The type of the value being set is a multi line string. Separate your lines with \n (\\n in JavaScript) + + + + + Full path of the key, including '\' separators as required. Remember to use '\\' in JavaScript to specify backslash. + + + The name of the registry setting to be set. + + + The registry value to be set. + + + Whether or not to create a corresponding merge file, setting to true will cause your value to persist across a device clean boot. A .reg file is written to the \Application folder on the device to persist the setting. + + + + + + Whether or not the registry key was successfully set. + + + + + Retrieve a value from the device registry. Only applicable on Windows Mobile / Embedded Handheld and CE devices. When running on RhoSimulator, this method is supported only for Windows OS. + Retrieve a value from the device registry. Only applicable on Windows Mobile / Embedded Handheld and CE devices. + WM + + + Map of properties associated with the registry key being set. + + + The hive name, see setRegistrySetting. + + + Full path of the key, including '\' separators as required. Remember to use '\\' in JavaScript to specify backslash. + + + The name of the setting to be retrieved. + + + + + + Registry value of the key. + + + + + Deletes the specified value from the device registry. Only applicable on Windows Mobile / Embedded Handheld and CE devices. When running on RhoSimulator, this method is supported only for Windows OS. + Deletes the specified value from the device registry. Only applicable on Windows Mobile / Embedded Handheld and CE devices. + WM + + + Map of properties associated with the registry key being set. + + + The hive name, setRegistrySetting. + + + Full path of the key, including '\' separators as required. Remember to use '\\' in JavaScript to specify backslash. + + + The name of the setting to be deleted. + + + If the registry value was set to be persistent, ie a corresponding .reg file was created in the \Application folder then setting true here will delete that .reg file. + + + + + + Whether or not the registry key was successfully deleted. + + + + + Change application window position and size. + Win32 + + + Left corner of window. + + + Top corner of window. + + + Width of window. + + + Height of window. + + + + + + Change application window position. + Win32 + + + Left corner of window. + + + Top corner of window. + + + + + + Change application window size. + Win32 + + + Width of the window. + + + Width of the of window. + + + + + + Bring application window to the top of the screen. + WM + + + + Replace application bundle. + + + Local path to bundle folder. See Build Application/Upgrade Application section to find out how to build bundle on computer. + + + Update parameters. + + + If true, when Application will not be automatically restarted after the replace bundle is finished. + + + + + + + + Delete folder. + + + Path to folder. + + + + + + Set do not backup attribute for file. + iOS + + + Path to file. + + + True set doNotBackup attribute to file (exclude this file from backup), false for remove doNotBackup attribute from file. + + + + + + Use Database.SQLite3.isBlobAttr: is model attribute is blob. + + + + + + + + + + Use Database.updateBlobAttribs: update model blob attributes list. + + + + + + + + Use System.locale property: Current device locale. + + + + + Use Application.setLocale method: set application specific locale. + + + + + + + + Use Push.setPushNotification: Register push callback, the method to call upon receiving a push message. + + + URL of the callback method. If empty, unregisters rhoconnect-push. + + + Parameters which will be added to callback URL. + + + + Name of a push service client. Current values can be 'rhoconnect_push' or 'gcm' or 'legacy' or empty. + + The call will be applied to every push client. + + + + + + + Use ScreenOrientation.setScreenOrientationEvent: Notify (call a callback method) when the screen rotates. + iOS, Android, WM + WM, Android + + + URL of the callback method. If empty, unregisters notification callback. + + + Parameters which will be added to callback URL. + + + + + + Use Application.quit: exit application. + + + Use System.screenSleeping property: enable / disable phone sleeping. + + + + + + Start timer. (It's works only with Ruby) + + + Timer interval. + + + URL of the callback method. + + + Parameters which will be added to callback URL. + + + + + + Stop timer. (It's works only with Ruby) + + + URL of the callback method which identify the timer to stop. + + + + + Use Network.setStatusNotify: set network notification callback. + + + The url to the user-defined callback method. + + + IOS. The network status polling period for systems that can not notify network status change immediately. Default value is 20 seconds. + + + + + Use Network.clearStatusNotify: Clear network status callback. + + + Use System.httpProxyURI property: To use client with the HTTP proxy. + + + + WM, CE, WIN32 + + + Use System.httpProxyURI property: Stop using HTTP proxy that was set by the command line, rhoconfig.txt or set_http_proxy_url. + WM, CE, WIN32 + + + Use System.applicationIconBadge: Set the application icon to have this badge number. Set to 0 (zero) to remove badge.iOS only. + iOS + + + + + + Run an application. + iOS, WM, Win32, Android + WM, Win32, Android + + + The name of the application on the device to run. It depends from platform. On iOS it is BundleURLScheme of executed application. + The name of the application on the device to run. + + + Start parameters string. Executed Application can receive this string by getStartParams method. Parameter could be just value, or key-value pair separated by '=' sign. Please note that for each platform there are distinct ways to write several params at once. On Android parameters should be separated by an amperstand, on other platforms by a comma or a space. + + + + Not Implemented. + + False by default. + + + + + + Hide Splash Screen if delay is configured as -1 in rhoconfig.txt + Android + + + + 1.0.0 + iOS, WM, Win32, WP8, Android + WM, Win32, Android + + + + +
                                                                          + You can find out whether the device has access to several system-dependent features such as calendar, camera, touchscreen, etc. + + + + + + +
                                                                          +
                                                                          +
                                                                          + + + +
                                                                          + Retrieve the version of the underlying Operating System. + + + + + + +
                                                                          +
                                                                          +
                                                                          + + + +
                                                                          + You can ask the system to install or uninstall a different application. This feature is useful for installing sub-applications, custom upgrades, etc. + + + + + + +
                                                                          +
                                                                          +
                                                                          + + + +
                                                                          + If necessary, you can read the embedded HTTP server's port, for debugging purposes. + + + + + + +
                                                                          +
                                                                          +
                                                                          + + + +
                                                                          + If you ever need to build or extract zip archives, RhoMobile includes easy-to-use APIs for this task. + + + + + + +
                                                                          +
                                                                          +
                                                                          + + + +
                                                                          + On devices running Windows Mobile, Windows CE, Windows Embedded Handheld and Windows Embedded CE it is possible to interact with the registry, this example shows how to do that. + + + + +
                                                                          +
                                                                          +
                                                                          +
                                                                          +
                                                                          +
                                                                          diff --git a/docs/en/5.5/api/videocapture.md b/docs/en/5.5/api/videocapture.md new file mode 100644 index 00000000..17cd9e32 --- /dev/null +++ b/docs/en/5.5/api/videocapture.md @@ -0,0 +1,90 @@ +#Videocapture +
                                                                          +

                                                                          captures video files from the default camera device.Only the foreground application is given access to capture video, when an application is sent to the background any capture that is in progress will be canceled and it will automatically relinquish control of the video hardware. When brought back to the foreground, an application previously using the video capture will have its previous configuration (eg. name etc.) reapplied to the plug-in automatically. Please note that any file transfer that is in progress continues even if the application is sent to the background.

                                                                          +

                                                                          Enabling the API

                                                                          + +

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

                                                                          + +
                                                                          :::ruby
                                                                          +extensions: ["mediacapture"]
                                                                          +
                                                                          + +

                                                                          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

                                                                          + +

                                                                          cancel()

                                                                          Stops capturing video and discards any captured video data. No file transfer takes place if the video capture is canceled. NOTE: This is not applicable for Android and iOS as the video capture window is full screen and provides a button to cancel the video capture.

                                                                          +

                                                                          Synchronous Return:

                                                                          • Void

                                                                          Method Access:

                                                                          • Instance Method: This method can be accessed via an instance object of this class:
                                                                            • myObject.cancel()
                                                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                                                            • JavaScript: Rho.Videocapture.cancel()
                                                                            • Ruby: Rho::Videocapture.cancel()

                                                                          getAllProperties(CallBackHandler callback)

                                                                          This method will return all of object/value pairs for the propertyNames of the API class.

                                                                          +

                                                                          Parameters

                                                                          • callback : CallBackHandler Optional

                                                                          Async Callback Returning Parameters: HASH

                                                                            • : STRING

                                                                          Synchronous Return:

                                                                          • HASH :

                                                                            Map of all available properties

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

                                                                          Method Access:

                                                                          • Instance Method: This method can be accessed via an instance object of this class:
                                                                            • myObject.getAllProperties(CallBackHandler callback)
                                                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                                                            • JavaScript: Rho.Videocapture.getAllProperties(CallBackHandler callback)
                                                                            • Ruby: Rho::Videocapture.getAllProperties(CallBackHandler callback)

                                                                          getDefault()

                                                                          This method will return an object that represents the default instance of the API Class. For example Camera.getDefault will return a Camera object that represents the default camera.

                                                                          +

                                                                          Synchronous Return:

                                                                          • SELF_INSTANCE :

                                                                            Default object of Module.

                                                                            +

                                                                          Method Access:

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

                                                                          getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                          This method will return a set of object/value pairs for the list of the propertyName that is passed in. The propertyNames must be a valid property of the API class.

                                                                          +

                                                                          Parameters

                                                                          • arrayofNames : ARRAY

                                                                            List of properties I want to know about

                                                                            +

                                                                            • Object : STRING

                                                                          • callback : CallBackHandler Optional

                                                                          Async Callback Returning Parameters: HASH

                                                                            • : STRING

                                                                          Synchronous Return:

                                                                          • HASH :

                                                                            Map of properties I want to know about

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

                                                                          Method Access:

                                                                          • Instance Method: This method can be accessed via an instance object of this class:
                                                                            • myObject.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                                                          • Default Instance: This method can be accessed via the default instance object of this class.
                                                                            • JavaScript: Rho.Videocapture.getProperties(ARRAY arrayofNames, CallBackHandler callback)
                                                                            • Ruby: Rho::Videocapture.getProperties(ARRAY arrayofNames, CallBackHandler callback)

                                                                          getProperty(STRING propertyName, CallBackHandler callback)

                                                                          This method will return the value of the propertyName that is passed in. The propertyName must be a valid property of the API class.

                                                                          +

                                                                          Parameters

                                                                          • propertyName : STRING

                                                                            The property to return info about.

                                                                            +

                                                                          • callback : CallBackHandler Optional

                                                                          Async Callback Returning Parameters: STRING

                                                                            Synchronous Return:

                                                                            • STRING :

                                                                              The property to return info about.

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

                                                                            Method Access:

                                                                            • Instance Method: This method can be accessed via an instance object of this class:
                                                                              • myObject.getProperty(STRING propertyName, CallBackHandler callback)
                                                                            • Default Instance: This method can be accessed via the default instance object of this class.
                                                                              • JavaScript: Rho.Videocapture.getProperty(STRING propertyName, CallBackHandler callback)
                                                                              • Ruby: Rho::Videocapture.getProperty(STRING propertyName, CallBackHandler callback)

                                                                            setDefault(SELF_INSTANCE: Rho::Videocapture defaultInstance)

                                                                            This method allows you to set the attributes of the default object instance by passing in an object of the same class.

                                                                            +

                                                                            Parameters

                                                                            • defaultInstance : SELF_INSTANCE: Rho::Videocapture

                                                                              An instance object that is of the same class.

                                                                              +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Class Method: This method can only be accessed via the API class object.
                                                                              • JavaScript: Rho.Videocapture.setDefault(SELF_INSTANCE: Rho::Videocapture defaultInstance)
                                                                              • Ruby: Rho::Videocapture.setDefault(SELF_INSTANCE: Rho::Videocapture defaultInstance)

                                                                            setProperties(HASH propertyMap)

                                                                            This method will set the values of a list of properties for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                            +

                                                                            Parameters

                                                                            • propertyMap : HASH

                                                                              Map of properties I want to set

                                                                              +

                                                                              • Object : STRING

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Instance Method: This method can be accessed via an instance object of this class:
                                                                              • myObject.setProperties(HASH propertyMap)
                                                                            • Default Instance: This method can be accessed via the default instance object of this class.
                                                                              • JavaScript: Rho.Videocapture.setProperties(HASH propertyMap)
                                                                              • Ruby: Rho::Videocapture.setProperties(HASH propertyMap)

                                                                            setProperty(STRING propertyName, STRING propertyValue)

                                                                            This method will set the value of a property for the API class. The propertyName must be a valid property for the class and must also not be read only.

                                                                            +

                                                                            Parameters

                                                                            • propertyName : STRING

                                                                              The one property name that I want to set

                                                                              +

                                                                            • propertyValue : STRING

                                                                              The one property value that I want to set

                                                                              +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Instance Method: This method can be accessed via an instance object of this class:
                                                                              • myObject.setProperty(STRING propertyName, STRING propertyValue)
                                                                            • Default Instance: This method can be accessed via the default instance object of this class.
                                                                              • JavaScript: Rho.Videocapture.setProperty(STRING propertyName, STRING propertyValue)
                                                                              • Ruby: Rho::Videocapture.setProperty(STRING propertyName, STRING propertyValue)

                                                                            start(CallBackHandler callback)

                                                                            Starts capturing video until either ‘stop’ is received, or ‘duration’ is reached. NOTE: On Android this meta tag wouldn’t immediately start recording and presents a preview window with controls (start, stop and cancel) for recording.

                                                                            +

                                                                            Parameters

                                                                            • callback : CallBackHandler Optional

                                                                            Async Callback Returning Parameters: OBJECT

                                                                              • transferResult : STRING

                                                                                Reports success or failure of transfer.

                                                                                +

                                                                              • fileName : STRING

                                                                                Name of the saved file (absolute path).

                                                                                +

                                                                              • fileSize : STRING

                                                                                Size of the saved file in kilobytes (KB).

                                                                                +

                                                                            Synchronous Return:

                                                                            • Void :

                                                                              Not providing a callback to be invoked will result in that file is saved only locally and file is not transfered.

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

                                                                            Method Access:

                                                                            • Instance Method: This method can be accessed via an instance object of this class:
                                                                              • myObject.start(CallBackHandler callback)
                                                                            • Default Instance: This method can be accessed via the default instance object of this class.
                                                                              • JavaScript: Rho.Videocapture.start(CallBackHandler callback)
                                                                              • Ruby: Rho::Videocapture.start(CallBackHandler callback)

                                                                            stop()

                                                                            Stops capturing video and either saves the file locally, or transfers it to a remote server. NOTE: This is not applicable for Android and iOS as the video capture window is full screen and provides a button to stop the video capture. Please note that the file transfer happens as specified even if we don’t call the stop method.

                                                                            +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Instance Method: This method can be accessed via an instance object of this class:
                                                                              • myObject.stop()
                                                                            • Default Instance: This method can be accessed via the default instance object of this class.
                                                                              • JavaScript: Rho.Videocapture.stop()
                                                                              • Ruby: Rho::Videocapture.stop()
                                                                            + +

                                                                            Properties

                                                                            + +

                                                                            duration : INTEGER

                                                                            Specifies the number of milliseconds of video to capture. This is the maximum number of milliseconds of video to capture when the ‘start’ method is called if not interrupted with the ‘stop’ method. The duration cannot be set to less than 1000 milliseconds, if a value of less than 1000 milliseconds is specified, the interval will be defaulted to 5000 milliseconds.

                                                                            +

                                                                            Default: 5000

                                                                            Property Access:

                                                                            • Instance: This property can be accessed via an instance object of this class:
                                                                              • myObject.duration
                                                                            • Default Instance: This property can be accessed via the default instance object of this class.
                                                                              • JavaScript: Rho.Videocapture.duration
                                                                              • Ruby: Rho::Videocapture.duration

                                                                            fileName : STRING

                                                                            The path and name of the file that the video is saved to locally on the device. When the video capture completes the file is saved in the root directory of the device (In case of Android this is the external storage directory). For example, if the user specifies ‘/video/file1’ then the file gets saved as ‘/mnt/sdcard/video/file1.mp4’ in Android, and as ‘\video\file1.mov’ on Windows. The file extension should not be provided as this is determined by the platform (.mp4 in Android and .mov in Windows). On iOS you’ll need to provide the entire path, including the extension, which should be .MOV.

                                                                            +

                                                                            Property Access:

                                                                            • Instance: This property can be accessed via an instance object of this class:
                                                                              • myObject.fileName
                                                                            • Default Instance: This property can be accessed via the default instance object of this class.
                                                                              • JavaScript: Rho.Videocapture.fileName
                                                                              • Ruby: Rho::Videocapture.fileName

                                                                            resolution : STRING

                                                                            The resolution of the video file to be captured.

                                                                            +

                                                                            Default: HIGH

                                                                            Possible Values (STRING):

                                                                            Constant: Rho.Videocapture.LOW (For Ruby use "::" for all "." when referencing constants)
                                                                            String: low

                                                                            Low resolution.

                                                                            +
                                                                            Constant: Rho.Videocapture.HIGH (For Ruby use "::" for all "." when referencing constants)
                                                                            String: high

                                                                            High resolution.

                                                                            +

                                                                            Property Access:

                                                                            • Instance: This property can be accessed via an instance object of this class:
                                                                              • myObject.resolution
                                                                            • Default Instance: This property can be accessed via the default instance object of this class.
                                                                              • JavaScript: Rho.Videocapture.resolution
                                                                              • Ruby: Rho::Videocapture.resolution

                                                                            saveToGallery : BOOLEAN

                                                                            Specifies whether or not to save the recorded video file into the device gallery.

                                                                            +

                                                                            Property Access:

                                                                            • Instance: This property can be accessed via an instance object of this class:
                                                                              • myObject.saveToGallery
                                                                            • Default Instance: This property can be accessed via the default instance object of this class.
                                                                              • JavaScript: Rho.Videocapture.saveToGallery
                                                                              • Ruby: Rho::Videocapture.saveToGallery
                                                                            + +

                                                                            Examples

                                                                            + +
                                                                            Basic Example
                                                                            +

                                                                            The default video capture object on the device is enabled when the index view is loaded.

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +#/app/Model
                                                                            +def index
                                                                            +    Rho::Videocapture.fileName = '/RhoVideoCapture'
                                                                            +    Rho::Videocapture.duration = 30000
                                                                            +    Rho::Videocapture.start(url_for(:action => :mysaveevent))
                                                                            +end
                                                                            +  def mysaveevent
                                                                            +       puts "Save params: #{@params}"
                                                                            +       puts "Result is #{@params['transferResult']}"
                                                                            +       puts "Name is #{@params['fileName']}"
                                                                            +       puts "Size is #{@params['size']}"
                                                                            +  end
                                                                            +
                                                                            +                            
                                                                            +

                                                                            Then in index.erb file:

                                                                            +
                                                                            + +

                                                                            Remarks

                                                                            + +
                                                                            Memory requirements

                                                                            Once duration has been reached the video file will be saved or transferred. Calling ‘stop’ once this has occurred will have no effect. A Video Capture will fail if there is not sufficient space on the device’s filesystem to store it.

                                                                            +
                                                                            File Formats

                                                                            The output file format on Android is MP4 and on Windows is WMV.

                                                                            +
                                                                            SDCard Access

                                                                            Extensions which came from RhoElements (i.e. AudioCapture) that could possibly write files to external storage will require “write SD card” permissions as part of the extension’s AndroidManifest. You cannot remove the ability to write to the SD card as it would cause the extension to malfunction. Therefore, the capability has already been granted on build, and any capability added by you will be ignored. This being the case, the following extensions will always be able to write to the SD card by default.

                                                                            +
                                                                            \ No newline at end of file diff --git a/docs/en/5.5/api/videocapture.xml b/docs/en/5.5/api/videocapture.xml new file mode 100644 index 00000000..79869f08 --- /dev/null +++ b/docs/en/5.5/api/videocapture.xml @@ -0,0 +1,203 @@ + + + + + + + + captures video files from the default camera device.Only the foreground application is given access to capture video, when an application is sent to the background any capture that is in progress will be canceled and it will automatically relinquish control of the video hardware. When brought back to the foreground, an application previously using the video capture will have its previous configuration (eg. name etc.) reapplied to the plug-in automatically. Please note that any file transfer that is in progress continues even if the application is sent to the background. + +## Enabling the API +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["mediacapture"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the VideoCapture API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the VideoCapture API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.videocapture.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + WM, CE, Android, iOS + WM, CE, Android + + + These properties are used for configuring video capture. + + Specifies the number of milliseconds of video to capture. This is the maximum number of milliseconds of video to capture when the 'start' method is called if not interrupted with the 'stop' method. The duration cannot be set to less than 1000 milliseconds, if a value of less than 1000 milliseconds is specified, the interval will be defaulted to 5000 milliseconds. + WM, CE, Android, iOS + WM, CE, Android + + + + The path and name of the file that the video is saved to locally on the device. When the video capture completes the file is saved in the root directory of the device (In case of Android this is the external storage directory). For example, if the user specifies '/video/file1' then the file gets saved as '/mnt/sdcard/video/file1.mp4' in Android, and as '\video\file1.mov' on Windows. The file extension should not be provided as this is determined by the platform (.mp4 in Android and .mov in Windows). On iOS you'll need to provide the entire path, including the extension, which should be .MOV. + The path and name of the file that the video is saved to locally on the device. When the video capture completes the file is saved in the root directory of the device (In case of Android this is the external storage directory). For example, if the user specifies '/video/file1' then the file gets saved as '/mnt/sdcard/video/file1.mp4' in Android, and as '\video\file1.mov' on Windows. The file extension should not be provided as this is determined by the platform (.mp4 in Android and .mov in Windows). + WM, CE, Android, iOS + WM, CE, Android + + + + Specifies whether or not to save the recorded video file into the device gallery. + WM, CE, Android + + + + The resolution of the video file to be captured. + WM, CE, Android + + + Low resolution. + + + High resolution. + + + + + + + + Starts capturing video until either 'stop' is received, or 'duration' is reached. NOTE: On Android this meta tag wouldn't immediately start recording and presents a preview window with controls (start, stop and cancel) for recording. + WM, CE, Android, iOS + Android, WM, CE + + Not providing a callback to be invoked will result in that file is saved only locally and file is not transfered. + + + + + Reports success or failure of transfer. + + + Name of the saved file (absolute path). + + + Size of the saved file in kilobytes (KB). + + + + + + + Stops capturing video and either saves the file locally, or transfers it to a remote server. NOTE: This is not applicable for Android and iOS as the video capture window is full screen and provides a button to stop the video capture. Please note that the file transfer happens as specified even if we don't call the stop method. + Stops capturing video and either saves the file locally, or transfers it to a remote server. NOTE: This is not applicable for Android as the video capture window is full screen and provides a button to stop the video capture. Please note that the file transfer happens as specified even if we don't call the stop method. + WM + + + + Stops capturing video and discards any captured video data. No file transfer takes place if the video capture is canceled. NOTE: This is not applicable for Android and iOS as the video capture window is full screen and provides a button to cancel the video capture. + Stops capturing video and discards any captured video data. No file transfer takes place if the video capture is canceled. NOTE: This is not applicable for Android as the video capture window is full screen and provides a button to cancel the video capture. + WM + + + + Enumerates all the available cameras for capturing video. + + Array of video capture objects. + + + + + + 1.0.0 + Android, WM, iOS + Android, WM + + + + Once duration has been reached the video file will be saved or transferred. Calling 'stop' once this has occurred will have no effect. A Video Capture will fail if there is not sufficient space on the device's filesystem to store it. + + + + The output file format on Android is MP4 and on Windows is WMV. + + + Extensions which came from RhoElements (i.e. AudioCapture) that could possibly write files to external storage will require "write SD card" permissions as part of the extension's AndroidManifest. You cannot remove the ability to write to the SD card as it would cause the extension to malfunction. Therefore, the capability has already been granted on build, and any capability added by you will be ignored. This being the case, the following extensions will always be able to write to the SD card by default. + + + + + + +
                                                                            + The default video capture object on the device is enabled when the index view is loaded. + + :mysaveevent)) +end + def mysaveevent + puts "Save params: #{@params}" + puts "Result is #{@params['transferResult']}" + puts "Name is #{@params['fileName']}" + puts "Size is #{@params['size']}" + end +]]> + + +
                                                                            +
                                                                            + Then in index.erb file: + + +
                                                                            +
                                                                            +

                                                                            Videocapture Extension Test

                                                                            + >Home +
                                                                            +
                                                                            Output goes here
                                                                            +
                                                                            + +
                                                                            +
                                                                            +]]> + +
                                                                            +
                                                                            +
                                                                            +
                                                                            +
                                                                            +
                                                                            +
                                                                            \ No newline at end of file diff --git a/docs/en/5.5/api/websocket.md b/docs/en/5.5/api/websocket.md new file mode 100644 index 00000000..ad6f3583 --- /dev/null +++ b/docs/en/5.5/api/websocket.md @@ -0,0 +1,30 @@ +#WebSocket +
                                                                            +

                                                                            This API provides access to the WebSocket protocol for two-way communication with a remote host.

                                                                            + + + +

                                                                            Methods

                                                                            + +

                                                                            Destructor close()

                                                                            Closes the connection.

                                                                            +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Class Method: This method is a destructor and can only be accessed via the object that was created by the `new` constructor.
                                                                              • JavaScript: myObj.close()
                                                                              • Ruby: @myObj.close()

                                                                            send(STRING message)

                                                                            Transmits data using the connection.

                                                                            +

                                                                            Parameters

                                                                            • message : STRING

                                                                              Data to transmit.

                                                                              +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Instance Method: This method can be accessed via an instance object of this class:
                                                                              • myObject.send(STRING message)
                                                                            + +

                                                                            Properties

                                                                            + +

                                                                            onclose : CALLBACK

                                                                            This callback is fired when connection is closed. It’s argument provides two members – ‘code’ and ‘reason’.'

                                                                            +

                                                                            Property Access:

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

                                                                            onerror : CALLBACK

                                                                            This callback is fired if error occurs. Use callback argument’s ‘message’ attribute to access error message.

                                                                            +

                                                                            Property Access:

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

                                                                            onmessage : CALLBACK

                                                                            This callback is fired when message is received. Use callback argument’s ‘data’ attribute to access received message.

                                                                            +

                                                                            Property Access:

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

                                                                            onopen : CALLBACK

                                                                            This callback is fired when connection is established.

                                                                            +

                                                                            Property Access:

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

                                                                            readyState : INTEGER Read Only

                                                                            Represents the state of the connection.

                                                                            +

                                                                            Property Access:

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

                                                                            url : STRING Read Only

                                                                            URL passed to Websocket constructor.

                                                                            +

                                                                            Property Access:

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

                                                                            Constants

                                                                            + +
                                                                            CONNECTING

                                                                            The connection has not yet been established.

                                                                            +
                                                                            OPEN

                                                                            The WebSocket connection is established and communication is possible.

                                                                            +
                                                                            CLOSING

                                                                            The connection is going through the closing handshake, or the close() method has been invoked.

                                                                            +
                                                                            CLOSED

                                                                            The connection has been closed or could not be opened.

                                                                            +
                                                                            \ No newline at end of file diff --git a/docs/en/5.5/api/websocket.xml b/docs/en/5.5/api/websocket.xml new file mode 100644 index 00000000..88569595 --- /dev/null +++ b/docs/en/5.5/api/websocket.xml @@ -0,0 +1,143 @@ + + + + + This API provides access to the WebSocket protocol for two-way communication with a remote host. + +## Enabling the API +There are two methods of enabling the Websocket API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Websocket API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.websocket.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + The connection has not yet been established. + + + + The WebSocket connection is established and communication is possible. + + + + The connection is going through the closing handshake, or the close() method has been invoked. + + + + The connection has been closed or could not be opened. + + + + + +- + + This callback is fired when connection is established. + + + + This callback is fired when message is received. Use callback argument's 'data' attribute to access received message. + + + + This callback is fired if error occurs. Use callback argument's 'message' attribute to access error message. + + + + This callback is fired when connection is closed. It's argument provides two members - 'code' and 'reason'.' + + + + + + URL passed to Websocket constructor. + + + + Represents the state of the connection. + + + + Currently will return empty string. + + + + Currently will return empty string. + + + + + + + + + Android + Constructor function for Websocket object + + + Specifies the URL to which to connect. + + + + + Currently not supported. + + + + + Websocket object + + + + + Closes the connection. + Android + + + + Android + Transmits data using the connection. + + + Data to transmit. + + + + + + + + + + + 1.0.0 + + + + diff --git a/docs/en/5.5/api/webview.md b/docs/en/5.5/api/webview.md new file mode 100644 index 00000000..ae6bbd22 --- /dev/null +++ b/docs/en/5.5/api/webview.md @@ -0,0 +1,204 @@ +#WebView +
                                                                            +

                                                                            The Webview is the core container used for rendering your application code. You can control certain behaviors of the webview by using this API class.

                                                                            +

                                                                            Enabling the API

                                                                            + +

                                                                            This API is part of the coreapi extension that is included automatically.

                                                                            + +
                                                                            :::ruby
                                                                            +extensions: ["coreapi"]
                                                                            +
                                                                            + +

                                                                            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

                                                                            + +

                                                                            active_tab()

                                                                            Deprecated

                                                                            Use NativeTabbar.currentTab property: returns the current tab index.

                                                                            +

                                                                            Synchronous Return:

                                                                            • INTEGER

                                                                            Method Access:

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

                                                                            currentLocation(INTEGER tabIndex)

                                                                            Returns the relative url (location) of the current page(without server and port); the last URL loaded to WebView from Ruby controller action.

                                                                            + +

                                                                            If you open your page in WebView, and after it makes a few jumps by linking (for example, to outside web adresses for example), currentLocation will still return the initial url opened in WebView. Also, if you use JQMobile, current_location has the initial URL, but does not reflect the actual window.location containing the JQMobile additional address by adding #, etc. See currentUrl.

                                                                            +

                                                                            Parameters

                                                                            • tabIndex : INTEGER Optional Default: -1

                                                                              TabBar tab index. If no tab bar present, index is ignored.Tab should be loaded once to return current url.

                                                                              +

                                                                              Current location of active WebView.

                                                                              +

                                                                            Synchronous Return:

                                                                            • STRING

                                                                            Method Access:

                                                                            • Class Method: This method can only be accessed via the API class object.
                                                                              • Ruby: Rho::WebView.currentLocation(INTEGER tabIndex)

                                                                            currentURL(INTEGER tabIndex)

                                                                            Replaces: get_current_url

                                                                            Returns the actual URL in WebView. This works the same as the JavaScript window.location.href.

                                                                            +

                                                                            Parameters

                                                                            • tabIndex : INTEGER Optional Default: -1

                                                                              TabBar tab index. If no tab bar present, index is ignored.

                                                                              +

                                                                              Current url of active WebView.

                                                                              +

                                                                            Synchronous Return:

                                                                            • STRING

                                                                            Method Access:

                                                                            • Class Method: This method can only be accessed via the API class object.
                                                                              • Ruby: Rho::WebView.currentURL(INTEGER tabIndex)

                                                                            executeJavascript(STRING javascriptText, INTEGER tabIndex)

                                                                            Replaces: execute_js executeJavaScript

                                                                            Execute JavaScript on the current page from your controller.

                                                                            + +

                                                                            For most mobile platforms, WebView.execute_js has been implemented via redirection to URL with ‘javascript:’ schema. If WebView.execute_js used in an AJAX call handler method in the controller, it may lead to the situation where the success javascript handler will never be executed. This may happen because, at the moment of success handler should be executed, a URL of the page already has been changed. This means no handlers from the previous page are valid.

                                                                            +

                                                                            Parameters

                                                                            • javascriptText : STRING

                                                                              The call to the JavaScript method on the current page, such as “test();”.

                                                                              +

                                                                            • tabIndex : INTEGER Optional Default: -1

                                                                              TabBar tab index. If no tab bar present, index is ignored.

                                                                              +

                                                                              Execute javascript in active WebView.

                                                                              +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Class Method: This method can only be accessed via the API class object.
                                                                              • Ruby: Rho::WebView.executeJavascript(STRING javascriptText, INTEGER tabIndex)

                                                                            full_screen_mode(BOOLEAN enable)

                                                                            Deprecated

                                                                            Use WebView.fullScreen property: Switch to / from full screen mode.

                                                                            +

                                                                            Parameters

                                                                            • enable : BOOLEAN

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Class Method: This method can only be accessed via the API class object.
                                                                              • JavaScript: Rho.WebView.full_screen_mode(BOOLEAN enable)
                                                                              • Ruby: Rho::WebView.full_screen_mode(BOOLEAN enable)

                                                                            refresh(INTEGER tabIndex)

                                                                            Force WebView to refresh the current page.

                                                                            +

                                                                            Parameters

                                                                            • tabIndex : INTEGER Optional Default: -1

                                                                              TabBar tab index. If no tab bar present, index is ignored.

                                                                              +

                                                                              Refresh active WebView.

                                                                              +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Class Method: This method can only be accessed via the API class object.
                                                                              • JavaScript: Rho.WebView.refresh(INTEGER tabIndex)
                                                                              • Ruby: Rho::WebView.refresh(INTEGER tabIndex)

                                                                            save(STRING format, STRING path, INTEGER tabIndex)

                                                                            Save current page to file system.

                                                                            +

                                                                            Parameters

                                                                            • format : STRING

                                                                              Format of the saved page.

                                                                              +

                                                                              Possible Values :

                                                                              Constant: Rho::WebView.SAVE_FORMAT_JPEG (For Ruby use "::" for all "." when referencing constants)
                                                                              String:jpeg

                                                                              Save as jpeg image.

                                                                              +
                                                                            • path : STRING

                                                                              Path to the file / folder to save the page.

                                                                              +

                                                                            • tabIndex : INTEGER Optional Default: -1

                                                                              TabBar tab index. If no tab bar present, index is ignored.

                                                                              +

                                                                              If tabbar index omitted then active WebView will be saved.

                                                                              +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Class Method: This method can only be accessed via the API class object.
                                                                              • JavaScript: Rho.WebView.save(STRING format, STRING path, INTEGER tabIndex)
                                                                              • Ruby: Rho::WebView.save(STRING format, STRING path, INTEGER tabIndex)

                                                                            setCookie(STRING url, STRING cookie)

                                                                            When WebView loads the specified url (either by selecting link or from calling WebView.navigate), it will add this cookie to the HTTP request.Not implemented for WebKit.

                                                                            +

                                                                            Parameters

                                                                            • url : STRING

                                                                              Set a cookie to be used by WebView for this url.

                                                                              +

                                                                            • cookie : STRING

                                                                              One or more name-value pairs of the format “NAME=VALUE”. Separate multiple name-value pairs with a semicolon, such as “NAME1=VALUE1; NAME2=VALUE2”.

                                                                              +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Class Method: This method can only be accessed via the API class object.
                                                                              • Ruby: Rho::WebView.setCookie(STRING url, STRING cookie)

                                                                            set_menu_items(HASH menuItems)

                                                                            Deprecated

                                                                            Use Application.nativeMenu property: set native menu items.

                                                                            +

                                                                            Parameters

                                                                            • menuItems : HASH

                                                                              Map of menu items: name to action.

                                                                              +

                                                                            Synchronous Return:

                                                                            • Void

                                                                            Method Access:

                                                                            • Class Method: This method can only be accessed via the API class object.
                                                                              • JavaScript: Rho.WebView.set_menu_items(HASH menuItems)
                                                                              • Ruby: Rho::WebView.set_menu_items(HASH menuItems)
                                                                            + +

                                                                            Properties

                                                                            + +

                                                                            activeTab : INTEGER Read Only

                                                                            Return an active tab index. For change active tab use Use Rho.NativeTabbar.currentTab property.

                                                                            +

                                                                            Property Access:

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

                                                                            cacheSize : INTEGER Read Only

                                                                            The browser cache size, in whole MBs. Defines in config.xml: Navigation\Cache.

                                                                            +

                                                                            Property Access:

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

                                                                            enableCache : BOOLEAN Read Only

                                                                            Enable / disable Browser cache. Use ‘WebView.enableCache’ parameter in rhoconfig.txt to configure this value.

                                                                            +

                                                                            Default: true

                                                                            Property Access:

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

                                                                            enablePageLoadingIndication : BOOLEAN Read Only

                                                                            Show page loading indication. On Windows Mobile/CE this property can be set only in config.xml: GUI\HourglassEnabled. At Android use ‘disable_loading_indication’ parameter in rhoconfig.txt to configure this value.

                                                                            +

                                                                            Default: true

                                                                            Property Access:

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

                                                                            enableWebPlugins : BOOLEAN Read Only

                                                                            Enable / disable web plug-ins. Use ‘enable_web_plugins’ parameter in rhoconfig.txt to configure this value. This option only has effect on Android versions before 4.0 (ICS). It mainly affects if Flash content is displayed.

                                                                            +

                                                                            Default: true

                                                                            Property Access:

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

                                                                            enableZoom : BOOLEAN Read Only

                                                                            Enable WebView zoom. Use ‘enable_screen_zoom’ parameter in rhoconfig.txt to configure this value.

                                                                            +

                                                                            Default: true

                                                                            Property Access:

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

                                                                            fontFamily : STRING Read Only

                                                                            Specifies the default font to use when rendering text in web pages. The specified font should be a TrueType font present on the device. On Windows the default font has been set to ‘Tahoma’ as this is present on all Symbol WM / CE devices, note that Tahoma has no italic or oblique variants. On the Enterprise Tablet the default is Droid Sans Fallback. The font specified must be stored in \Windows for Windows WM / CE devices, or /system/fonts for Enterprise Tablet. Defines in config.xml: HTMLStyles\FontFamily

                                                                            +

                                                                            Property Access:

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

                                                                            framework : STRING Read Only

                                                                            Same as System.webViewFramework.

                                                                            +

                                                                            Property Access:

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

                                                                            fullScreen : BOOLEAN

                                                                            Use full screen mode.

                                                                            +

                                                                            Default: false

                                                                            Property Access:

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

                                                                            navigationTimeout : INTEGER

                                                                            Can be defined in config.xml: Navigation\NavTimeout. Number of milliseconds(maximum is 45000) before the browser times out and navigates to the page specified in the badlink setting. If it is determined that the destination is unreachable regardless of wait time, the badlink may be loaded before NAVTIMEOUT. This is the time taken to establish communication with the server, not the time taken to fully load the page.Note that the navigation timeout will not be invoked when navigating to the start page, best practice is to store your first page locally to avoid connectivity issues at start up, you can then redirect to an online page if desired.

                                                                            +

                                                                            Default: 45000

                                                                            Property Access:

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

                                                                            scrollTechnique : STRING Read Only

                                                                            Specifies the technique used to scroll about the page.Defines in config.xml: Scrolling\ScrollTechnique.

                                                                            +

                                                                            Default: FingerScroll

                                                                            Possible Values (STRING):

                                                                            Constant: Rho.WebView.SCROLL_NONE (For Ruby use "::" for all "." when referencing constants)
                                                                            String: None

                                                                            No scrollbars will be displayed and the page will not respond to finger swipes.

                                                                            +
                                                                            Constant: Rho.WebView.SCROLL_SCROLLBARS (For Ruby use "::" for all "." when referencing constants)
                                                                            String: Scrollbars

                                                                            When the size of the page is larger than the screen scrollbars will be presented which can be used to scroll the page.

                                                                            +
                                                                            Constant: Rho.WebView.SCROLL_FINGER (For Ruby use "::" for all "." when referencing constants)
                                                                            String: FingerScroll

                                                                            You can scroll around the page using finger swiping.

                                                                            +

                                                                            Property Access:

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

                                                                            textZoomLevel : INTEGER

                                                                            Sets the font size to be displayed on the page, set to 0 for the smallest font and 4 for the largest font.

                                                                            +

                                                                            Property Access:

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

                                                                            userAgent : STRING Read Only

                                                                            Defines in config.xml: Navigation\UserAgent. When visiting a web server the WebKit browser will report its self as the specified user agent. Use the following substitution variables:

                                                                            + +
                                                                              +
                                                                            • %p – platform name (“Windows CE ” + version number)
                                                                            • +
                                                                            • %w – WebKit version number
                                                                            • +
                                                                            • %e – WebKit version number.
                                                                            • +
                                                                            + + +

                                                                            Use the UserAgent setting to spoof your device to the server, e.g. to view content designed for the desktop on your mobile screen. +From RhoElements 2.1 onwards the default value was changed to work out of the box with a greater number of server configurations, prior to RhoElements 2.1 the default user agent was: “Mozilla/5.0 (%p) AppleWebKit/%w (KHTML, like Gecko) WebKit/%e Safari/%w”

                                                                            +

                                                                            Property Access:

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

                                                                            viewportEnabled : BOOLEAN Read Only

                                                                            Whether to enable or disable viewport meta tag processing.Defines in config.xml: Navigation\ViewportEnabled.

                                                                            +

                                                                            Default: true

                                                                            Property Access:

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

                                                                            viewportWidth : INTEGER Read Only

                                                                            Default viewport width to use for pages that do not have a viewport meta tag (uses 1:1 scaling if not specified).Defines in config.xml: Navigation\ViewportWidth.

                                                                            +

                                                                            Property Access:

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

                                                                            zoomPage : FLOAT

                                                                            Sets the zoom factor of the page. Factor 1.0 is no zoom, values less than 1.0 are zoomed out and values greater than 1.0 are zoomed in.It is recommended to not to use the zoom value less than 1.0 because the page doesn’t look in readable format.In Android new Zoom value takes effect on current page, Previous page has to be revisited for the new zoom values to take effect

                                                                            +

                                                                            Property Access:

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

                                                                            Examples

                                                                            + +
                                                                            Execute javascript
                                                                            +

                                                                            You can call the WebView and make it execute JavaScript code from a Ruby controller. This can be particularly helpful in order to reuse JavaScript functionality that is already included in your pages.

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +#call javascript alert on the current page
                                                                            +Rho::WebView.executeJavascript("alert('This is Webview.executejavascript function');")
                                                                            +
                                                                            +                            
                                                                            +

                                                                            As an example, you can invoke JQuery Mobile’s changePage.

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +#call JQuery Mobile from a Ruby controller
                                                                            +Rho::WebView.executeJavascript("$.mobile.changePage('#my_page');")
                                                                            +
                                                                            +                            
                                                                            +

                                                                            You can also call your own functions.

                                                                            +
                                                                            :::javascript
                                                                            +
                                                                            +function greet(name) {
                                                                            +    alert("Hello, "+name);
                                                                            +}
                                                                            +
                                                                            +                            
                                                                            +

                                                                            From the Ruby controller we can execute the JavaScript function that may be in the view.

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +#call a custom JavaScript function from Ruby
                                                                            +Rho::WebView.executeJavascript("greet('John Doe');")
                                                                            +
                                                                            +                            
                                                                            Use full-screen mode
                                                                            +

                                                                            The WebView can be set to use all the available screen real-estate by turning on “full-screen” mode.

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +# Toggle fullScreen on / off
                                                                            +Rho::WebView.fullScreen = !Rho::WebView.fullScreen
                                                                            +
                                                                            +                            
                                                                            +

                                                                            This property can also be assigned to in JavaScript.

                                                                            +
                                                                            :::javascript
                                                                            +
                                                                            +// Fullscreen can also be invoked from JavaScript
                                                                            +Rho.WebView.fullScreen = true;
                                                                            +
                                                                            +Rho.WebView.fullScreen = false;
                                                                            +
                                                                            +                            
                                                                            Navigate
                                                                            +

                                                                            This is the section that will appear before the code block.

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +#Force WebView to navigate to a URL.
                                                                            +Rho::WebView.navigate(url_for(:action => :my_action))
                                                                            +
                                                                            +                            
                                                                            +

                                                                            You can also navigate outside of your application, to an external site.

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +#Navigate out of the local application and into an externally-served site
                                                                            +Rho::WebView.navigate("http://www.example.com");
                                                                            +
                                                                            +                            
                                                                            +

                                                                            This API is also available from JavaScript.

                                                                            +
                                                                            :::javascript
                                                                            +
                                                                            +//Navigate out of the local application and into an externally-served site
                                                                            +Rho.WebView.navigate("http://www.example.com");
                                                                            +
                                                                            +                            
                                                                            Navigate back
                                                                            +

                                                                            This is the section that will appear before the code block.

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +#Force WebView to navigate to the previous page using Browser back.
                                                                            +Rho::WebView.navigateBack
                                                                            +
                                                                            +                            
                                                                            +

                                                                            The same method is available in JavaScript.

                                                                            +
                                                                            :::javascript
                                                                            +
                                                                            +//Force WebView to navigate to the previous page using Browser back.
                                                                            +Rho.WebView.navigateBack();
                                                                            +
                                                                            +                            
                                                                            Refresh the page
                                                                            +

                                                                            Reload the current URL into the WebView. This is useful especially after having updated data that must be now shown to the user

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +# Update database or variables here
                                                                            +# ...
                                                                            +# Refresh the current page to show new information
                                                                            +Rho::WebView.refresh
                                                                            +
                                                                            +                            
                                                                            +

                                                                            By default, “refresh” will update the current view. If you are using the native Tabbar and have multiple WebViews, you can specify which one to refresh.

                                                                            +
                                                                            :::ruby
                                                                            +
                                                                            +# Reload the page on WebView number 2
                                                                            +Rho::WebView.refresh(2)
                                                                            +
                                                                            +                            
                                                                            +

                                                                            Also available from JavaScript.

                                                                            +
                                                                            :::javascript
                                                                            +
                                                                            +// Reload the current page
                                                                            +Rho.WebView.refresh()
                                                                            +
                                                                            +// Reload the page on WebView number 3
                                                                            +Rho.WebView.refresh(3)
                                                                            +
                                                                            +                            
                                                                            \ No newline at end of file diff --git a/docs/en/5.5/api/webview.xml b/docs/en/5.5/api/webview.xml new file mode 100644 index 00000000..c5193af7 --- /dev/null +++ b/docs/en/5.5/api/webview.xml @@ -0,0 +1,515 @@ + + + + + The `Webview` is the core container used for rendering your application code. You can control certain behaviors of the webview by using this API class. + The `Webview` is the core container used for rendering your application code. You can control certain behaviors of the webview by using this API class. + +> Note: There is currently an issue with hyperlinks on CE devices using the IE Engine: if you are attempting to click a link while holding the shift hardware key on the device, the link will not work properly. This is a known issue and is being worked on currently. + + + +## Enabling the API +This API is part of the `coreapi` extension that is included automatically. + :::ruby + extensions: ["coreapi"] + +## JavaScript Usage +Be sure to review the [JavaScript API Usage](/guide/api_js) guide for important information about using this API in JavaScript. + +## Ruby Usage +Be sure to review the [Ruby API Usage](/guide/api_ruby) guide for important information about using this API in Ruby. + + +## Enabling the API +There are two methods of enabling the Webview API: + +* Include all ebapi modules or +* Include only the API modules you need + +For either of these methods, you'll need to include files from the `/Enterprise Browser/JavaScript Files/Enterprise Browser` directory on the computer that you installed the Enterprise Browser. + +### Include all JS API modules +To include all JS APIs, you must copy the ebapi-modules.js file to a location accessible by your app's files and include the JavaScript file in your app. For instance, to include the modules file in your index.html, with the file in the same directory as your index.html, you would add the following line to the <head> section of your index.html: + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"></script> + +> Note: that the pathing for this file is relative to the current page. + +This will define the EB class within the page. Any page you need to use the modules will need to have the .js file included in this fashion. + +### Include only the modules you need +To include single APIs, you must first include the `ebapi.js` in your HTML as well as the API file you want to use. For instance, to use the Webview API, I would add the following code to my HTML file(s), assuming the API files have been copied to the same directory as the HTML. + + :::html + <script type="text/javascript" charset="utf-8" src="ebapi.js"></script> + <script type="text/javascript" charset="utf-8" src="eb.webview.js"></script> + +The ebapi.js file is necessary for all single API inclusions. + + + + + + + + + + + + + + + Same as System.webViewFramework. + + + Use full screen mode. + WM, CE, Win32, Android + + + Enable WebView zoom. Use 'enable_screen_zoom' parameter in rhoconfig.txt to configure this value. + Enable WebView zoom. Use 'EnableZoom' parameter in Config.xml to configure this value. + Android + + + Show page loading indication. On Windows Mobile/CE this property can be set only in config.xml: GUI\\HourglassEnabled. At Android use 'disable_loading_indication' parameter in rhoconfig.txt to configure this value. + Show page loading indication. On Windows Mobile/CE this property can be set only in config.xml: GUI\\HourglassEnabled. At Android use 'disable_loading_indication' parameter in Config.xml to configure this value. + WM, CE, Android + WebKit on Windows Mobile/CE + + + Enable / disable web plug-ins. Use 'enable_web_plugins' parameter in rhoconfig.txt to configure this value. This option only has effect on Android versions before 4.0 (ICS). It mainly affects if Flash content is displayed. + Enable / disable web plug-ins. Use 'enable_web_plugins' parameter in Config.xml to configure this value. This option only has effect on Android versions before 4.0 (ICS). It mainly affects if Flash content is displayed. + Android + + + Can be defined in config.xml: Navigation\\NavTimeout. Number of milliseconds(maximum is 45000) before the browser times out and navigates to the page specified in the badlink setting. If it is determined that the destination is unreachable regardless of wait time, the badlink may be loaded before NAVTIMEOUT. This is the time taken to establish communication with the server, not the time taken to fully load the page.Note that the navigation timeout will not be invoked when navigating to the start page, best practice is to store your first page locally to avoid connectivity issues at start up, you can then redirect to an online page if desired. + WM + WebKit + + + + Specifies the technique used to scroll about the page.Defines in config.xml: Scrolling\\ScrollTechnique. + WM + WebKit + + + No scrollbars will be displayed and the page will not respond to finger swipes. + + + When the size of the page is larger than the screen scrollbars will be presented which can be used to scroll the page. + + + You can scroll around the page using finger swiping. + + + + + Specifies the default font to use when rendering text in web pages. The specified font should be a TrueType font present on the device. On Windows the default font has been set to 'Tahoma' as this is present on all Symbol WM / CE devices, note that Tahoma has no italic or oblique variants. On the Enterprise Tablet the default is Droid Sans Fallback. The font specified must be stored in \Windows for Windows WM / CE devices, or /system/fonts for Enterprise Tablet. Defines in config.xml: HTMLStyles\\FontFamily + WM + WebKit + + + Defines in config.xml: Navigation\\UserAgent. When visiting a web server the WebKit browser will report its self as the specified user agent. Use the following substitution variables: + +* %p - platform name ("Windows CE " + version number) +* %w - WebKit version number +* %e - WebKit version number. + +Use the UserAgent setting to spoof your device to the server, e.g. to view content designed for the desktop on your mobile screen. +From RhoElements 2.1 onwards the default value was changed to work out of the box with a greater number of server configurations, prior to RhoElements 2.1 the default user agent was: "Mozilla/5.0 (%p) AppleWebKit/%w (KHTML, like Gecko) WebKit/%e Safari/%w" + + WM + WebKit + + + + Whether to enable or disable viewport meta tag processing.Defines in config.xml: Navigation\\ViewportEnabled. + WM + WebKit + + + Default viewport width to use for pages that do not have a viewport meta tag (uses 1:1 scaling if not specified).Defines in config.xml: Navigation\\ViewportWidth. + WM + WebKit + + + The browser cache size, in whole MBs. Defines in config.xml: Navigation\\Cache. + WM + WebKit + + + Enable / disable Browser cache. Use 'WebView.enableCache' parameter in rhoconfig.txt to configure this value. + Android + + + Configurable HTTP headers. Not yet implemented. + WM + WebKit + + + Sets the zoom factor of the page. Factor 1.0 is no zoom, values less than 1.0 are zoomed out and values greater than 1.0 are zoomed in.It is recommended to not to use the zoom value less than 1.0 because the page doesn't look in readable format.In Android new Zoom value takes effect on current page, Previous page has to be revisited for the new zoom values to take effect + WM, Android + WebKit + + + Sets the font size to be displayed on the page, set to 0 for the smallest font and 4 for the largest font. + WM, Android + WebKit + + + Return an active tab index. For change active tab use Use Rho.NativeTabbar.currentTab property. + + + + + + + + + + + + Force WebView to refresh the current page. + + + TabBar tab index. If no tab bar present, index is ignored. + + Refresh active WebView. + + + + + + + Force WebView to navigate to a URL. White page flickering during transition may happen if a controller action method doesn't return any rendered value, but instead performs a WebView.navigate(someUrl) call. It is important to avoid using WebView.navigate in Ruby action methods because WebView.navigate is intended to be used in callback methods asynchronously. + + + Navigate to this url. + + + + TabBar tab index. If no tab bar present, index is ignored. Please avoid of navigate in not opened tab - this is unsupported on Android. + + Refresh active WebView. + + + + + + + Force WebView to navigate to the previous page using Browser back. + + + TabBar tab index. If no tab bar present, index is ignored. + + Navigate back in active WebView. + + + + + + + Returns the relative url (location) of the current page(without server and port); the last URL loaded to WebView from Ruby controller action. + +If you open your page in WebView, and after it makes a few jumps by linking (for example, to outside web adresses for example), currentLocation will still return the initial url opened in WebView. Also, if you use JQMobile, current_location has the initial URL, but does not reflect the actual window.location containing the JQMobile additional address by adding #, etc. See currentUrl. + + + + + TabBar tab index. If no tab bar present, index is ignored.Tab should be loaded once to return current url. + + Current location of active WebView. + + + + + + + + + Returns the actual URL in WebView. This works the same as the JavaScript window.location.href. + iOS, Android + Android + + + + TabBar tab index. If no tab bar present, index is ignored. + + Current url of active WebView. + + + + + + + + + Execute JavaScript on the current page from your controller. + +For most mobile platforms, WebView.execute_js has been implemented via redirection to URL with 'javascript:' schema. If WebView.execute_js used in an AJAX call handler method in the controller, it may lead to the situation where the success javascript handler will never be executed. This may happen because, at the moment of success handler should be executed, a URL of the page already has been changed. This means no handlers from the previous page are valid. + + + + + The call to the JavaScript method on the current page, such as "test();". + + + + TabBar tab index. If no tab bar present, index is ignored. + + Execute javascript in active WebView. + + + + + + + Use NativeTabbar.currentTab property: returns the current tab index. + + + + + + Use WebView.fullScreen property: Switch to / from full screen mode. + + + + + + + When WebView loads the specified url (either by selecting link or from calling WebView.navigate), it will add this cookie to the HTTP request.Not implemented for WebKit. + + Android, Win32, iOS + Win32, Android + + + Set a cookie to be used by WebView for this url. + + + One or more name-value pairs of the format "NAME=VALUE". Separate multiple name-value pairs with a semicolon, such as "NAME1=VALUE1; NAME2=VALUE2". + + + + + + Save current page to file system. + Android + + + Format of the saved page. + + + Save as jpeg image. + + + + + Path to the file / folder to save the page. + + + + TabBar tab index. If no tab bar present, index is ignored. + + If tabbar index omitted then active WebView will be saved. + + + + + + + WM, CE,Android + Use Application.nativeMenu property: set native menu items. + + + Map of menu items: name to action. + + + + + + + + + + + 1.0.0 + WM, CE, Win32, Android, iOS, WP8 + WM, CE, Win32, Android + + + +
                                                                            + You can call the WebView and make it execute JavaScript code from a Ruby controller. This can be particularly helpful in order to reuse JavaScript functionality that is already included in your pages. + + + + +
                                                                            +
                                                                            + As an example, you can invoke JQuery Mobile's changePage. + + + + +
                                                                            +
                                                                            + You can also call your own functions. + + + + +
                                                                            +
                                                                            + From the Ruby controller we can execute the JavaScript function that may be in the view. + + + + +
                                                                            +
                                                                            +
                                                                            + + + +
                                                                            + The WebView can be set to use all the available screen real-estate by turning on "full-screen" mode. + + + + +
                                                                            +
                                                                            + This property can also be assigned to in JavaScript. + + + + +
                                                                            +
                                                                            +
                                                                            + + + +
                                                                            + This is the section that will appear before the code block. + + :my_action)) +]]> + + +
                                                                            +
                                                                            + You can also navigate outside of your application, to an external site. + + + + +
                                                                            +
                                                                            + This API is also available from JavaScript. + + + + +
                                                                            +
                                                                            +
                                                                            + + + +
                                                                            + This is the section that will appear before the code block. + + + + +
                                                                            +
                                                                            + The same method is available in JavaScript. + + + + +
                                                                            +
                                                                            +
                                                                            + + + +
                                                                            + Reload the current URL into the WebView. This is useful especially after having updated data that must be now shown to the user + + + + +
                                                                            +
                                                                            + By default, "refresh" will update the current view. If you are using the native Tabbar and have multiple WebViews, you can specify which one to refresh. + + + + +
                                                                            +
                                                                            + Also available from JavaScript. + + + + +
                                                                            +
                                                                            +
                                                                            +
                                                                            +
                                                                            +
                                                                            diff --git a/docs/en/5.5/googlesearch.txt b/docs/en/5.5/googlesearch.txt new file mode 100644 index 00000000..53a033b5 --- /dev/null +++ b/docs/en/5.5/googlesearch.txt @@ -0,0 +1,19 @@ +#Google Search + + +
                                                                            Loading
                                                                            + + + \ No newline at end of file diff --git a/docs/en/5.5/guide/api_js.md b/docs/en/5.5/guide/api_js.md new file mode 100644 index 00000000..c8aa08cd --- /dev/null +++ b/docs/en/5.5/guide/api_js.md @@ -0,0 +1,198 @@ +# Using RhoMobile JavaScript APIs +You may also include only the modules you intend to use, to improve page loading times. To do this, you must include the file `rhoapi.js` prior to including the specific JS modules. The `rhoapi.js` file creates the Rho name-space needed for the JavaScript APIs to function properly. + + :::html + + + +### JavaScript ORM +If you are going to be using the JS ORM API, you'll also need to include this line in any files that will be using it: + + :::html + + +## JavaScript RhoMobile Application Structure +The following application structure is what is minimally required to build a JavaScript RhoMobile Application. You can still use the [App Generator](creating_a_project#creating-a-project-with-rhostudio) to create the default structure, but then remove the `app` folder that is generated for a `Ruby` MVC app. + + :::html + - build.yml + - rhoconfig.txt (start_path points to starting html page) + - rakefile + - icon (folder for application icon) + - public (root folder for 'web application') + +## Build.yml settings +Be sure to include the extensions and capabilities that are required for the APIs that are being used. In addition, you should specify the following setting in the `build.yml` file: + :::yaml + javascript_application: true + +When this flag is specified, the Ruby VM will not start at application start, and all ruby files will be ignored. + +**NOTE: If you do not specify this parameter and remove your `app` folder then the build process will fail.** + +## Using JS APIs from a Web Server Application +To load application files to the RhoMobile application from an external Web server - set `start_path` in `rhoconfig.txt` to point to http:// or https:// protocol URI + :::ruby + start_path='http://heroku.com/myapp/index.html' + +To use Common APIs you have to copy `rhoapi-modules.js` to your web server application, so it can be loaded from your html pages. [Read More](webapps#using-rhomobile-js-apis) about using RhoMobile 4 JavaScript APIs from a web server application. + +## Using your own objects +Some API classes support instance objects. This allows you to maintain your own objects and assign different properties to them. + +In the following example we want to save a reference to the front facing camera of the device so that we can manipulate the front facing camera properties separate from the rear-facing camera: + + :::javascript + var desiredCamera; + Rho.Camera.enumerate(function (e) + { + if (e.type == Rho.Camera.FRONT_TYPE) + desiredCamera = e; + }); + +We can then reference instance methods on that object + + :::javascript + var cameraProperties = + {desiredWidth:1024, desiredHeight:768}; + + desiredCamera.take_picture(cameraProperties, + fnHandlePicture(e)); + + +## Setting Properties +There are a few different ways you can set properties. + +### Using the default instance +One way is to use the default instance of the API class. This will change the property of the object in a global sense until it is changed again (or the application is exited): + + :::javascript + Rho.Class.Property = value; + +For example the following snippet will turn of the `illuminationMode` for the default Barcode instance. + + :::javascript + Rho.Barcode.illuminationMode='alwaysOff'; + +### Using special class methods +You can also use special class methods to set a property (as long as the class supports this method): + + :::javascript + Rho.Barcode.setProperty('illuminationMode','alwaysOff'); + +You can also use a special class method to set multiple properties in one line of code (as long as the class supports this method): + + :::javascript + // An object of propertyName:value is passed into the setProperties method + Rho.Barcode.setProperties({ illuminationMode:'alwaysOff' , code128:'enabled'}); + +### With another method +Some methods support passing in an `propertyMap` as a parameter to a method. Like with the `setProperties` method, you would pass in an object of multiple propertyName:propertyValue + + :::javascript + // Enable the default instance of Barcode with code128 enabled and illuminationMode off + // the first parameter of this method is a propertyMap + Rho.Barcode.enable({ illuminationMode:'alwaysOff' , code128:'enabled'}, bchandler()); + +**NOTE: In the API reference, when a parameter is of type propertyMap, all possible values are not shown in the documentation. However you may use any non read-only property listed for that object class (unless otherwise specified).** + +## Getting Properties +There are a few ways to get an object's property values: + +### Reading values synchronously +The following examples use a synchronous method that will be blocking. + +The following example uses the `getProperty` class method. This method may not be available on all APIs. + + :::javascript + var iMode = Rho.Barcode.getProperty('illuminationMode'); + +You can use the `getProperties` method for a list of propeties you wish to know about. An array of property names is passed into this method + + :::javascript + // An object is returned by the getProperties method + var settingsObj = Rho.Barcode.getProperties(['illuminationMode' ,'code128']); + + // The object properties will be the list of properties used + if (settingsObj.illuminationMode == 'alwaysOff')... + +You can also use the `getAllProperties` method to get all properties of an object + + :::javascript + var settingsObj = Rho.Barcode.getAllProperties(); + +**NOTE: Some APIs like Barcode have many properties and there may be an undesirable performance hit for reading all properties available. Use this method sparingly.** + +### Reading values Asynchronously +There are a few ways you can read properties in non-blocking asynchronously way by specifying a callback: + +The following code snippet uses a self-describing autonomous function that will execute when the callback is executed + + :::javascript + Barcode.getAllProperties(function(e) + { + alert(e.code128); + }); + +The following code snippet also uses a self-describing anonymous function that will execute when the callback is executed. This time we are also passing in other parameters + + :::javascript + Barcode.getProperties(["autoEnter","code128"], + function (e) + { + alert(e.code128); + }); + +**NOTE: For methods that support callbacks, the callback function will always be the last parameter of the method** + +The following code snippet uses a function name for the callback instead of an anonymous function + + :::javascript + Barcode.getAllProperties(fnPropertyPerser(e)); + +## Handling callbacks +Some methods will support a callback for returning information in an unblocking asynchronous way. This will be indicated in the documentation by a parameter named `callback` + + :::javascript + Barcode.take(HASH propertyMap, CallbackHandler callback) + +The callback parameter will either be marked as Optional or marked as Mandatory + +Be sure to check the type of object the callback will be returning as well as the list of available callback parameters for each method. Typically the callback will return an object with a pre-defined set of objects that can be accessed for information. + +### Callback as anonymous function +The following code snippet takes a picture from the device's camera and will run the anonymous function + + :::javascript + // The documentation will list the callback type as well as callback parameters that are available + Rho.Camera.takePicture(...,function(e){ + alert(e.status); + };); + + +### Callback as a JavaScript function +The following code snippet takes a picture from the device's camera and then calls another JavaScript function `mycallbackhandler`: + + :::javascript + Rho.Camera.takePicture(..., mycallbackHandler()); + + function mycallbackHandler(params) + { + // The documentation will list the callback type as well as callback parameters that are available + alert(params.status); + } + +### Callback as a ruby controller method +You may want the callback to return to a ruby controller method or a particular view. For example when a picture is taken you may want to store an object and display a view showing all images captured. Recall that accessing RhoMobile ruby controller methods/views is simply using a url string + + :::javascript + Rho.Camera.takePicture(...,'/Images/imageTakeHandler'); + + :::ruby + def imageTakeHandler + #callback object will be in params object + + # some code to same image in database + + render :action => :list + end \ No newline at end of file diff --git a/docs/en/5.5/guide/api_ruby.md b/docs/en/5.5/guide/api_ruby.md new file mode 100644 index 00000000..53234c10 --- /dev/null +++ b/docs/en/5.5/guide/api_ruby.md @@ -0,0 +1,150 @@ +# Using RhoMobile Ruby APIs + +RhoMobile applications support access to device, system and framework capabilities through a common API set whether you are building Rhodes, RhoElements or RhoMobile enabled web apps. + + +## Using your own objects +Some API classes support instance objects. This allows you to maintain your own objects and assign different properties to them. + +In the following example we want to save a reference to the front facing camera of the device so that we can manipulate the front facing camera properties seperate from the rear-facing camera: + + :::ruby + @desiredCamera; + Rho::Camera.enumerate(lambda |e| + { + if (e.type == Rho::Camera.FRONT_TYPE) + @desiredCamera = e + }) + +We can then reference instance methods on that object + + :::ruby + @cameraProperties = + {:desiredWidth=>1024, :desiredHeight=>768} + + desiredCamera.take_picture(@cameraProperties, + fnHandlePicture()) + + +## Setting propeties +There are a few different ways you can set properties. + +### Using the default instance +One way is to use the default instance of the API class. This will change the property of the object in a global sense until it is changed again (or the application is exited): + + :::ruby + Rho::Class.Property = value; + +For example the following snippet will turn of the `illuminationMode` for the default Barcode instance. + + :::ruby + Rho::Barcode.illuminationMode='alwayOff' + +### Using special class methods +You can also use special class methods to set a property (as long as the class supports this method): + + :::ruby + Rho::Barcode.setProperty :illuminationMode, 'alwaysOff' + +You can also use a special class method to set multiple properties in one line of code (as long as the class supports this method): + + :::ruby + # An object of propertyName:value is passed into the setProperties method + Rho::Barcode.setProperties { :illuminationMode => 'alwaysOff' , :code128 => 'enabled'} + +### With another method +Some methods support passing in an `propertyMap` as a parameter to a method. Like with the `setProperties` method, you would pass in an object of multiple propertyName:propertyValue + + :::ruby + # Enable the default instance of Barcode with code128 enabled and illuminationMode off + # the first parameter of this method is a propertyMap + Rho::Barcode.enable ( { :illuminationMode => 'alwaysOff' , :code128 => 'enabled'}, url_for :action => :mycallback) + +**NOTE: In the API reference, when a parameter is of type propertyMap, all possible values are not shown in the documentation. However you may use any non read-only property listed for that object class (unless otherwise specified).** + +## Getting properties +There are a few ways to get an object's property values: + +### Reading values synchronously +The following examples use a synchronous method that will be blocking. + +The following example uses the `getProperty` class method. This method may not be available on all APIs. + + :::ruby + iMode = Rho::Barcode.getProperty('illuminationMode') + +You can use the `getProperties` method for a list of propeties you wish to know about. An array of property names is passed into this method + + :::ruby + # An object is returned by the getProperties method + settingsHash = Rho::Barcode.getProperties(['illuminationMode' ,'code128']) + + # The object properties will be the list of properties used + if settingsHash.illuminationMode == 'alwaysOff'... + +You can also use the `getAllProperties` method to get all properties of an object + + :::ruby + settingsHash = Rho::Barcode.getAllProperties() + +**NOTE: Some APIs like Barcode have many properties and there may be an undesirable performance hit for reading all properties available. Use this method sparingly.** + +### Reading values Asynchronously +There are a few ways you can read properties in non-blocking asynchronously way by specifying a callback: + +The following code snippet uses a lambda function that will execute when the callback is executed + + :::ruby + Barcode.getAllProperties(lambda{|e| puts e.code128}) + +The following code snippet also uses a lambda function that will execute when the callback is executed. This time we are also passing in other parameters + + :::javascript + Barcode.getProperties(['autoEnter','code128','code39'], + lambda{|e| puts e.code128}) + +The following code snippet uses a controller method name for the callback instead of an anonymous function + + :::javascript + Barcode.getAllProperties(fnPropertyPerser()); + +## Handling callbacks +> NOTE: For methods that support callbacks, the callback function will always be the last parameter of the method. + +Some methods will support a callback for returning information in an unblocking asynchronous way. This will be indicated in the documentation by a parameter named `callback` + + :::ruby + Rho::Barcode.take(HASH propertyMap, HASH callback) + +The callback parameter will either be marked as Optional or marked as Mandatory + +Be sure to check the type of object the callback will be returning as well as the list of available callback parameters for each method. Typically the callback will return an object with a pre-defined set of objects that can be accessed for information. + +### Callback as lambda function +The following code snippet takes a picture from the device's camera and will run the lambda function + + :::ruby + # The documentation will list the callback type as well as callback parameters that are available + Rho::Camera.takePicture(...,lambda{ |e| + puts e['status'] } + ) + + +### Callback as a ruby controller method +You may want the callback to return to a ruby controller method or a particular view. For example when a picture is taken you may want to store an object and display a view showing all images captured. Recall that accessing RhoMobile ruby controller methods/views is simply using a url string + + :::ruby + Rho::Camera.takePicture(..., url_for :action => :imageTakeHandler) + + + :::ruby + def imageTakeHandler + #callback object will be in params object + + # some code to same image in database + + render :action => :list + end + +**NOTE: In previous versions of RhoMobile, the ruby callback was specified as a parameter like: `:callback => (url_for :action => :imageTakeHandler)`. This is no longer part of the methods parameters and must be specified as the final parameter without the `:callback =>` notation** + diff --git a/docs/en/5.5/guide/apisummary.md b/docs/en/5.5/guide/apisummary.md new file mode 100644 index 00000000..69bea5ab --- /dev/null +++ b/docs/en/5.5/guide/apisummary.md @@ -0,0 +1,1187 @@ +# RhoMobile API Summary +Below is a list of the new common APIs for RhoMobile Suite 5.5, which are recommended for all new projects. If you're moving a 2.x app to 5.x, please consult the [2.x migration guide](apiusage). + +## 5.5 APIs +
                                                                            +

                                                                            + + - API/platform is supported +

                                                                            +

                                                                            + + - API is available only on Symbol devices +

                                                                            +
                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                            LANGUAGESPLATFORMS
                                                                            Class
                                                                            + Application +
                                                                            + AudioCapture +
                                                                            + Barcode +
                                                                            + Battery +
                                                                            + BluetoothManager * +
                                                                            + BluetoothSession * +
                                                                            + Camera +
                                                                            + CardReader +
                                                                            + Config +
                                                                            + Database +
                                                                            + Device +
                                                                            + Geolocation +
                                                                            + Intent +
                                                                            + KeyCapture +
                                                                            + KeyState +
                                                                            + Log +
                                                                            + Mapview * +
                                                                            + Mediaplayer +
                                                                            + NativeMenubar +
                                                                            + NativeTabbar +
                                                                            + NativeToolbar +
                                                                            + Navbar +
                                                                            + NdefMessage * +
                                                                            + NdefRecord * +
                                                                            + Network +
                                                                            + NFCManager * +
                                                                            + NFCTag * +
                                                                            + NFCTagTechnology_IsoDep * +
                                                                            + NFCTagTechnology_MifareClassic * +
                                                                            + NFCTagTechnology_MifareUltralight * +
                                                                            + NFCTagTechnology_Ndef * +
                                                                            + NFCTagTechnology_NdefFormatable * +
                                                                            + NFCTagTechnology_NfcA * +
                                                                            + NFCTagTechnology_NfcB * +
                                                                            + NFCTagTechnology_NfcF * +
                                                                            + NFCTagTechnology_NfcV * +
                                                                            + NFCTagTechnology * +
                                                                            + Notification +
                                                                            + ORM & ORMModel +
                                                                            + Printer +
                                                                            + Printer Zebra +
                                                                            + Push +
                                                                            + RhoConnectClient +
                                                                            + RhoContact * +
                                                                            + RhoController * +
                                                                            + RhoError * +
                                                                            + RhoEvent * +
                                                                            + RhoFile +
                                                                            + RhomSource * +
                                                                            + RhoProfiler * +
                                                                            + RhoUtils * +
                                                                            + ScreenOrientation +
                                                                            + Sensor +
                                                                            + SignalIndicators +
                                                                            + Signature +
                                                                            + SignatureCapture (inline) * +
                                                                            + SmartCradle +
                                                                            + System +
                                                                            + Timer +
                                                                            + Webview +
                                                                            + +**These API classes are implemented in RhoMobile Suite 2.2 but are not yet included in the new Common API class set for RhoMobile Suite 5.5. They use the older 2.2 format and support Ruby only except as noted.* + +**NOTE: When using 2.2 APIs in RhoMobile 5.5, the [2.2 API compatibility matrix](../../2.2.0/rhoelements/apicompatibility) applies.** + + +### JavaScript APIs +To use the JavaScript APIs in RhoElements 2.2, **you must add the `public/js/rho_javascript_api.js` file to the .html, .erb, or .js file that's calling the JavaScript method**. This file is created at build time as part of the application package and can coexist with RhoMobile 5.5 JavaScript API file `rhoapi-modules.js`. However, it has been altered from the version built using 2.2, and must be regenerated to allow it to properly coexist with other files of your 5.5 app. + + +### JavaScript ORM +If you're using the JavaScript ORM API, include this line in any files that will be calling it: + :::html + + +### Using older JavaScript APIs +In the event that a pre-4.0 JavaScript API is required to work with one of the new Common JavaScript APIs, it is possible to create a compatibility layer this way: + + :::html + + + + + + + + + + + + + +NOTE: Important: Modules must be loaded in this order! + +##Future Common APIs +Toward the goal of supplying a Common API format for both JavaScript and Ruby, the following API classes will be included in future versions of RhoMobile Suite 5.x. + +### RhoElements 2.2 APIs +The 2.2 RhoElement APIs are supported only on Zebra WebKit, which is still available on Windows Mobile/CE and Android platforms. The APIs for 5.x support the stock Android WebKit by default. + +### Rhodes 2.2 APIs +2.2 Rhodes APIs that were not replaced by an equivalent RhoMobile 5.5 API (ex: Camera) are supported on all platforms that were supported previously. Ruby APIs will behave exactly as they did before. Note that some of the Rhodes 2.2 APIs provided JavaScript support but used a different version of the RhoMobile JavaScript API library: `rho_javascript_api.js` + +To generate this file you must enable JavaScript by putting `rho-javascript` into extensions in your build.yml. + + :::yaml + extensions: ["rho-javascript"] diff --git a/docs/en/5.5/guide/apiusage.md b/docs/en/5.5/guide/apiusage.md new file mode 100644 index 00000000..15b91857 --- /dev/null +++ b/docs/en/5.5/guide/apiusage.md @@ -0,0 +1,438 @@ +# Migrating Your RhoMobile App to v5.4 + +RhoMobile Suite 5.x and higher offers a set of common APIs to access device, system and framework capabilities from your JavaScript and Ruby code. + + +## RhoConnect Client +In RhoMobile Suite 5.4, the [RhoConnectClient API](../api/rhoconnectclient) is accessed through an extension. To use the RhoConnect Client, you must specify `rhoconnect-client` in the extensions section of your application's `build.yml` (as below). If you are using RhoConnect, you should also consult the [RhoConnect Migration Guide](../rhoconnect/migration) for details about migrating your RhoConnect application. + + :::ruby + extensions: ["rhoconnect-client"] + +## Android WebKit +RhoMobile Suite 5.4 uses the stock Android WebKit included with the Android SDK you're building with as the default. Version 5.x RhoElement APIs will work only with the stock WebKit. However, [pre-5.x RhoElement APIs](#using-22-apis) **must be used with the Zebra WebKit for Android**. + +## Shared Runtime +RhoMobile Suite 2.0 included the RhoElements Shared Runtime, a pre-built RhoMobile application that provided application configuration options for the Zebra WebKit and RhoElements API extensions. This allowed HTML/JS applications to run without requiring the developer to build a separate a RhoMobile application. + +Since the RhoMobile suite 5.4 no longer includes a pre-built shared runtime, it is recommended that you build a simple RhoMobile application to point to your HTML application. This will allow you to optimize the application by including only the extensions and capabilities used by your application. + +## JavaScript Licensing +RhoMobile Suite 5.4 increases the number of APIs with JavaScript access from prior versions. In addition, JavaScript licensing restrictions associated with some APIs and the Zebra WebKit are removed, and are now in sync with those of Ruby. Licensing restrictions are now at the API class level rather than the language level. For example, use of the Camera API is now free on JavaScript *and* Ruby. [Read more about licensing](licensing). + +## API Platform Support +It is the intention for all APIs to work across all supported platforms. In RhoMobile Suite 2.2, support for platforms was indicated using an [API compatibility matrix](../../2.2.0/rhoelements/apicompatibility) at the API class level. Version 5.4 contains fewer exceptions, and the platforms that are supported will be indicated at the individual API property or method level. Please [refer to the API Summary](apisummary) for an overview. + +## Replaced APIs +New APIs that have replaced those previously available will be highlighted in the menus and descriptions of the API reference documentation, as below: + +[System.applicationInstall API](../api/system#mapplicationInstall) Replaces: app_install. + +## Deprecated APIs +Deprecated APIs will be highlighted as such in menus and descriptions of the API reference documentation. While some deprecated APIs might remain functional, they will no longer be supported or enhanced, as below: + +[System.hasNetwork](../api/system#phasNetwork) Deprecated + +The associated description will indicate alternative API(s). + +## API Migration Table +The following is a summary of new APIs and how previous APIs relate to it. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                            +Class + +Description + +Previous RhoMobile Suite 2.2 API +
                                                                            +Application + +Interface with application level methods and properties + +Rename of RhoApplication and will also contain the MSI specific Application +
                                                                            +Barcode + +Scan bar codes using device's camera, laser or 2d imager + +Barcode and Scanner have been amalgamated. All decoders have now been brought into the same API rather than having a separate API for each. +
                                                                            +Battery + +Displays a battery signal icon in a native window without requiring users to draw their own icon + +Previously existed in 2.2 Battery +
                                                                            +CardReader + +Interface for device's Mag Stripe Reader (MSR) + +Previously existed in 2.2: CardReader +
                                                                            +Database + +Accessing RhoMobile's built in database + +Same as Database class in 2.2 +
                                                                            +KeyCapture + +Allows capturing hardware key events. + +Previously existed in 2.2: KeyCapture +
                                                                            +KeyState + +Indicator of hardware key state (Shift, Caps, Alt). + +Previously existed in 2.2: KeyState + +
                                                                            +Log + +Interface for Rhomobile logging capabilities + +Rename of RhoLog as well as combine log settings from RhoElement's Config.xml file +
                                                                            +Mediaplayer + +Playback audio and ringtones. + +Added functionality to RingtoneManager class +
                                                                            +NativeMenubar + +Defining custom menus for your application. + +Replaces @menu and @default_menu api +
                                                                            +NativeTabbar + +Provides native UI tabs with multiple webview instances. + +Similar to previous NativeTabbar class +
                                                                            +NativeToolbar + +Provides a native toolbar UI element. + +Similar to previous NativeToolbar class +
                                                                            +Navbar + +Native navigation for iOS applications. + +Similar to previous Navbar class +
                                                                            +Network + +See device's network status or make network connections + +AsyncHTTP and Network have been amalgamated +
                                                                            +Notification + +Provides visual, audio and tactile alerts to the user. + +2.2 APIs: Alert and Notification have been combined +
                                                                            +Orm & OrmModel + +Apis for user defined Data models + +Previously Rhomobile Data Models were accessible only through the Rhom API via Ruby +
                                                                            +Push + +HTTP based push messaging + +RhoElemnents Push API +
                                                                            +RhoConnectClient + +Synchronization interface with RhoConnect server applications + +Rename of SyncEngine +
                                                                            +RhoFile + +Allows access to the device's file system. + +Mostly the same as the previous File class +
                                                                            +ScreenOrientation + +Allows control or detection of screen orientation behavior. + +Uses 2.2 ScreenOrientation class and replaces set_screen_rotation_notification +
                                                                            +Sensor + +Allows direct access to device sensors like accelerometer, proximity, light, etc + +Rename of 2.2 RawSensors class and adds additional functionality. +
                                                                            +SignalIndicators + +Graphical indicator of WiFi strength + +Previous 2.2 API: Signal +
                                                                            +System + +Control and modify core aspects of the device such as the screen, OS and device capabilities. + +Amalgamation of System and Generic +
                                                                            +Webview + +Interface with application's Webview container + +Same as Webview class in 2.2. Also Contains text zoom and page zoom parameters previously found in the Zoom module. +
                                                                            + +## Using 2.2 APIs +Below is a list of API classes available in RhoMobile Suite 2.2 and have not yet have been incorporated in the new Common API class set for RhoMobile Suite 5.4. These APIs are still available in the 2.2 format. The following API classes will be incorporated into furture versions of the RhoMobile Suite so as to supply a common API format for in both JavaScript and Ruby. + +**NOTE: When using 2.2 APIs in RhoMobile 5.4, the [2.2 API compatibility matrix](../../2.2.0/rhoelements/apicompatibility) still applies.** + +* [Mapview](../../2.2.0/rhodesapi/mapview-api) +* [Contacts](../../2.2.0/rhodesapi/rhocontact-api) +* Calendar +* System.Process +* [Registry](../../2.2.0/rhoelements/registry) +* [AudioCapture](../../2.2.0/rhoelements/AudioCapture) +* [Config](../../2.2.0/rhodesapi/rhoconfig-api) +* [GeoLocation](../../2.2.0/rhodesapi/geolocation-api) +* [Gesture](../../2.2.0/rhoelements/Gesture) +* Printing +* [Systemtime](../../2.2.0/rhoelements/systemTime) +* [Comm](../../2.2.0/rhoelements/comm) +* [Addressbar](../../2.2.0/rhoelements/addressbar) +* [Alarm](../../2.2.0/rhoelements/alarm) +* [Bluetooth](../../2.2.0/rhodesapi/bluetoothmanager-api) +* [NFC](../../2.2.0/rhodesapi/NFCManager-api) +* [Timer](../../2.2.0/rhodesapi/timer-api) +* [Backlight](../../2.2.0/rhoelements/backlight) +* [Keylight](../../2.2.0/rhoelements/Keylight) +* [Memory](../../2.2.0/rhoelements/memory) +* [Reboot](../../2.2.0/rhoelements/reboot) + +### RhoElements 2.2 APIs +The 2.2 RhoElement APIs are supported on Zebra WebKit only. This WebKit is still available on Windows Mobile/CE and some Android platforms, but the default for 5.4 is the stock Android WebKit. + +### Rhodes 2.2 APIs +2.2 Rhodes APIs that were not replaced by an equivalent RhoMobile 5.4 API (ex: Camera) are supported on all platforms that were supported previously. Ruby APIs will behave exactly as they did before. Note that some of the Rhodes 2.2 APIs provided JavaScript support, but used a different version of the RhoMobile JavaScript API library: `rho_javascript_api.js`. + +To generate this file, you must enable JavaScript by including `rho-javascript` in the extensions section of your `build.yml` file. + + :::yaml + extensions: ["rho-javascript"] + +To use the JavaScript API, **you must add the `public/js/rho_javascript_api.js` file to the .html, .erb, or .js file that's calling the JavaScript method**. This file is created at build time as part of the application package and can coexist with RhoMobile 5.4 the JavaScript API file `rhoapi-modules.js`. However, it has been altered from the version built using 2.2, and must be regenerated to allow it to properly coexist with other files of your 5.4 app. + + +### JavaScript ORM +If you're using the JavaScript ORM API, include this line in any files that will be calling it: + + :::html + + +## Backward Compatibility + +### RhoElements Meta Tags +Meta tags that are specific to RhoElements should continue to function in a RhoMobile 5.4 application, as long as its `build.yml` contains the following: + + :::yaml + app_type: 'rhoelements' + capabilities: 'motorola_browser' + +However, the use of Meta tags is a deprecated feature and will not be supported in future versions of RhoMobile. It is recommended that all Meta tags be converted to use the associated JavaScript capability using the new common API classes. + +Deprecated format: + :::html + + +Use instead: + :::javascript + Rho.Barcode.enable(); + +### RhoElements JavaScript APIs +JavaScript APIs that are specific to RhoElements should continue to function in a RhoMobile 5.4 application, as long as its `build.yml` contains the following: + + :::yaml + app_type: 'rhoelements' + capabilities: 'motorola_browser' + +It is recommended that JavaScript API calls be converted to use the associated JavaScript capability using the new common API classes. + +Old format: + :::JavaScript + scanner.enable() // should still work + +New format: + Rho.Barcode.enable() // the current 5.4 equivalent + +### Parameter ordering +In a few rare cases, an API in version 2.2 has the same naming as in 5.4, but the ordering of parameters may have changed. For example: + + :::ruby + # In RhoMobile 2.2 Params are callback, paramHash + # This will fail in a 5.4 application + Rho::Barcode.enable(url_for(:action => :barcode_callback), {:camera => 'front'}) + + # In RhoMobile 5.4 Params are now paramHash, callback + Rho::Barcode.enable( {:camera => 'front'},url_for(:action => :barcode_callback)) + +In all new 5.4 API classes, callbacks are now specified as the last parameter. + +**NOTE: The benefit of converting these APIs to the current 5.4 methods includes support for additional combinations of supported operating systems and platforms. There also are several [new ways of accessing](api_js) these APIs through instance objects and special common methods that were not implemented previously.** + +### API behavior on Page change +In version 2.2, some APIs by default will reset the device they control when navigating between app pages. In 5.4, the devices are not reset between page navigations, but is left in the previous state. Therefore, it will be up to the application to control behavior on page load. + +For example, if a 2.2 application activates the barcode scanner on Page1 with a callbackhandler, navigating to a page with no scanner will disable it. Depending on the desired behavior, an equivalent 5.4 app must handle the setting or disabling of the scanner on page load. + +## Removed APIs +The following APIs are no longer included in the RhoMobile Suite: + +* [DateTimePicker](../rhodesapi/datetimepicker-api) - There are many HTML5 options available for this +* [Airbeam](../rhoelements/airbeam) - Can be controlled via [System.runApplication](../api/system#mrunApplication) +* [BottomCommandArea](../rhoelements/bottomcommandarea) & [TopCommandArea](../rhoelements/topcommandarea) - RhoElements-specific APIs used for debugging +* [History](../rhoelements/historyback2) - Better JavaScript methods exist +* [ODAX](../rhoelements/odax) - Better HTML5 methods exist +* [Zoom](../rhoelements/zoom) - Incorporated into the [WebView API](../api/webview) \ No newline at end of file diff --git a/docs/en/5.5/guide/app_icon_splash.md b/docs/en/5.5/guide/app_icon_splash.md new file mode 100644 index 00000000..4e9eaabe --- /dev/null +++ b/docs/en/5.5/guide/app_icon_splash.md @@ -0,0 +1,143 @@ +# Application Icon and Splash Screen +## Application Name +In the build.yml in your application folder there is an entry "name". This is the display name that the user will see on the device. Example: + + :::yml + name: My Own App + +## Application Icons +Place your image to use as an icon into the folder called `icon` in your application. If you created an app called `testapp` then the folder would be `testapp/icon`. + +* Windows Mobile and Windows: You can add an icon in two formats: `icon.png` and `icon.ico`. +* iOS 4.0: Apple require three icons for application: 57x57, 72x72 and 114x114 pixels. Prepare such files, name them as `icon57.png`, `icon72.png` and `icon114.png` and place into `icon` folder + + testapp/ + build.yml + Rakefile + rhoconfig.txt + app/ + public/ + icon/ + icon.png + icon.ico + +### iOS +* Target->info->General->Name +* Target->info->Build->Product Name (for all configurations) +* rhodes\platform\iphone\icon.png, icon57.png, icon72.png, icon114.png - change to your icons +* check rhodes\platform\iphone\Info.plist it should contain BundleName=${PRODUCT_NAME} + +#### Splash Screen Images on Different Devices +Apple has released a lot of devices with varying sizes and you must account for this in building your app by using the following files for their respective devices. + +* loading-568h@2x.png - size 640x1136 - for iPhone 5/5S/5C +* loading-667h@2x.png - size 750x1334 - for iPhone 6 +* loading-736h@3x.png - size 1242x2208 - for iPhone 6-Plus + +In XCode, these files will be converted to the following file names. also just add the files into the XCode project. + +* Default-568h@2x.png - size 640x1136 - for iPhone 5/5S/5C +* Default-667h@2x.png - size 750x1334 - for iPhone 6 +* Default-736h@3x.png - size 1242x2208 - for iPone 6 Plus + +If you choose to manually add the files into your XCode project, you'll need to also edit your info.plist as such: + + :::xml + UILaunchImages + + + UILaunchImageMinimumOSVersion + 8.0 + UILaunchImageName + Default-568h + UILaunchImageOrientation + Portrait + UILaunchImageSize + {320, 568} + + + UILaunchImageMinimumOSVersion + 8.0 + UILaunchImageName + Default-667h + UILaunchImageOrientation + Portrait + UILaunchImageSize + {375, 667} + + + UILaunchImageMinimumOSVersion + 8.0 + UILaunchImageName + Default-736h + UILaunchImageOrientation + Portrait + UILaunchImageSize + {414, 736} + + + +### Android +You can change the icon for your Android application by replacing icon.png, which is in your application icon folder, with a new icon.png. + +### Windows Mobile +Windows Mobile Shell program caches program icons. This cache is cleared only when the device or the simulator is restarted. If you change the icon of your application, you have to restart the device or simulator: uninstall/install is not enough. + + +## Loading screen +Rhodes supports the display of a custom "Loading" screen while your application is launching. This screen's source is the file loading.html, located at /app/loading.html. + +Alternatively, you can replace loading.html with an image named loading.png if you just want a simple image to be displayed. + +You can control how image presented by modifying splash_screen options in [rhoconfig.txt](runtime_config#rhoconfigtxt): + +* delay - how long splash screen should be displayed (in seconds) +* center,vcenter,hcenter - picture alignment +* zoom,vzoom,hzoom - scaling options + +Examples: + +Place the splash screen in the center and show it for 5 seconds: + :::ruby + splash_screen='delay=5;center' + +Center the splash screen horizontally, scale it vertically to file all available space, and show it for 5 seconds: + :::ruby + splash_screen='delay=5;hcenter;vzoom' + +You can customize you loading image (showed on start of application) for each platform by platform suffix: + +* Android `loading.android.png` +* iPhone `loading.iPhone.png` +* WM `loading.wm.png` + +If application doesn't have platform specific `loading.png`, then Rhodes will try to load default `loading.png`. + +For iPhone you may define a set of loading images. See Apple documentation about these images, [section Application Launch Images in Build-Time Configuration Details](http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BuildTimeConfiguration/BuildTimeConfiguration.html). + +If you are building for iPhone using rake commands, place `loading.png` to your applications "app" folder. If you created an app called `testapp` then the folder would be `testapp/app`. Also you can add some additional images for so loading screen look better on different devices: + +* loading.png - size 320x480 - size 320x480 – for iPhone/iPod/iPad and other non iOS devices. +* loading@2x.png - size 640x960 – for from iPhone4/iPod4/Iphone4S (retina). +* loading-Portrait.png - size 768x1024 – for iPad in Portrait orientation. +* loading-Portrait@2x.png - size 1536x2048 - for iPad retina in Portrait orientation. +* loading-PortraitUpsideDown.png - size 768x1024 – for iPad in Portrait Upside Down orientation. +* loading-PortraitUpsideDown@2x.png - size 1536x2048 – for iPad retina in Portrait Upside Down orientation. +* loading-Landscape.png - size 1024x768 – for iPad in Landscape orientation. +* loading-Landscape@2x.png - size 2048x1536 – for iPad retina in Landscape orientation. +* loading-LandscapeLeft.png - size 1024x768 – for iPad in Landscape Left orientation. +* loading-LandscapeLeft@2x.png - size 2048x1536 – for iPad retina in Landscape Left orientation. +* loading-LandscapeRight.png - size 1024x768 - size 1024x768 – for iPad in Landscape Right orientation. +* loading-LandscapeRight@2x.png - size 2048x1536 – for iPad retina in Landscape Right orientation. + +If you are using xCode to build for iPhone, you should add to your project Default.png image. You can also add some additional images for better work on different devices: + +* Default.png - size 320x480 - for iPhone/iPod/iPhone4/iPad +* Default@2x.png - size 640x960 - for iPhone4/iPod4, if not defined then use Default.png +* Default-Portrait.png - size 768x1024 - for iPad in Portrait orientation on start, if not defined then Default@2x.png will be used +* Default-PortraitUpsideDown.png - size 768x1024 - for iPad in Portrait orientation on start, if not defined then Default-Portrait.png will be used +* Default-Landscape.png - size 1024x768 - for iPad in Landscape orientation on start, if not defined then Default@2x.png will be used +* Default-LandscapeLeft.png - size 1024x768 - for iPad in LandscapeLeft orientation on start, if not defined then Default-Landscape.png will be used +* Default-LandscapeRight.png - size 1024x768 - for iPad in LandscapeRight orientation on start, if not defined then Default-Landscape.png will be used + +> Note: Use rake command "rake build:iphone:setup_xcode_project" to setup the XCode project for changes in the current application (include loading images, icons, etc.) \ No newline at end of file diff --git a/docs/en/5.5/guide/app_upgrade.md b/docs/en/5.5/guide/app_upgrade.md new file mode 100644 index 00000000..8a9a2a47 --- /dev/null +++ b/docs/en/5.5/guide/app_upgrade.md @@ -0,0 +1,131 @@ +# Upgrading a RhoMobile Application + +RhoMobile supports application upgrades for iPhone (non AppStore distribution), Android, and Windows Mobile. You can do a total upgrade or partial upgrade. + +## Total Upgrade + +You can replace the total application bundle with a new bundle packed in an update bundle archive file. + +### Prepare Total Application Package + +To prepare the upgrade package for iPhone, run this command in your application folder: + + :::term + $ rake build:iphone:upgrade_package + +The application package will be placed in `/bin/target/iphone`. + +To prepare the upgrade package for Android, run this command in your application folder: + + :::term + $ rake build:android:upgrade_package + +The application package will be placed in `/bin/target/android`. + +To prepare the upgrade package for Windows Mobile, run this command in your application folder: + + :::term + $ rake build:wm:upgrade_package + +The application package will be placed in `/bin/target/wmp6`. + +### Download Bundle Package and Replace Application Current Bundle + +Download package: + :::ruby + if !::Rho::RhoSupport.rhobundle_download(url_to_package, url_for(:action => :httpdownload_callback)) + render :action =>:error + else + render :action => :wait_download, :back => '/app' + end + +Unzip and replace package: + :::ruby + if System.unzip_file(::Rho::RhoSupport.rhobundle_getfilename())==0 + System.replace_current_bundle( File.dirname(::Rho::RhoSupport.rhobundle_getfilename()) ) + render :action => :wait_replace, :back => '/app' + else + WebView.navigate url_for :action => :error + end + +The application will restart automatically. + +NOTE: On iPhone and Android, the application has to be started manually. + +NOTE: When using Rho::RhoSupport.rhobundle_download method on a network that has proxies, you may need to configure a proxy exception on the device, if your HTTP server is also on that same network. Example: local network has an IP subnet of 192.168 and it uses a proxy. On the Windows Mobile device, go into System >> Settings >> Connections >> Advanced and add 192.168.* to the proxy exception list. + +NOTE: The URL parameter for rhobundle_download must be a HTTP URL - FTP is not supported. + +## Partial Upgrade + +You can add new files or replace old files with new ones and create an updated bundle packed in an update bundle archive file. + +### Prepare Partial Application Package + +To add new files or replace old files with new ones in your current application's bundle content, make a list of the files in a file named `upgrade_package_add_files.txt`. Here is an example of upgrade_package_add_files.txt. + + app/index.erb + app/Bundle/controller.rb + app/Bundle/error.erb + +In the same way, you can also remove files with an `upgrade_package_remove_files.txt` file. Here is an example of upgrade_package_remove_files.txt. + + app/Bundle/wait.erb + app/Model2 + +Execute the rake commands in your application folder to perform the partial upgrade. + +To prepare partial upgrade package for iPhone run in application folder: + + :::term + $ rake build:iphone:upgrade_package_partial + +Application package will be placed to /bin/target/iphone + +To prepare partial upgrade package for Android run in application folder: + + :::term + $ rake build:android:upgrade_package_partial + +Application package will be placed to /bin/target/android + +To prepare partial upgrade package for Windows Mobile run in application folder: + + :::term + $ rake build:wm:upgrade_package_partial + +Application package will be placed to /bin/target/wmp6. + +### Download Bundle Package and Replace Application Current Bundle + +You then unzip, upload and replace the application package. + +Download package: + :::ruby + if !::Rho::RhoSupport.rhobundle_download(url_to_package, url_for(:action => :httpdownload_callback)) + render :action =>:error + else + render :action => :wait_download, :back => '/app' + end + +Upload and Replace Package: + :::ruby + if System.unzip_file(::Rho::RhoSupport.rhobundle_getfilename())==0 + System.replace_current_bundle( File.dirname(::Rho::RhoSupport.rhobundle_getfilename()), { :callback => url_for(:action => :update_finished_callback), :do_not_restart_app => true } ) + render :action => :wait_replace, :back => '/app' + else + WebView.navigate url_for :action => :error + end + +With the System.replace_current_bundle method, you can supply a params hash with the following options. + +`:callback` - url with callback. Called when upgrade bundle procedure is finished. +`:do_not_restart_app` - bool, if true your application will not automatically restart after the procedure is finished. + +One of the callback parameters should be `status`: `"ok"` or `"error"`. + +NOTE: Use :do_not_restart_app very carefully. You can disable the restart of your application after a bundle update only if you change only images, JavaScript, and other similar types of files, but if you change files such as Ruby code, models, etc. In general, we recommend you do not use this parameter if you do not understand how your application works on your particular platform. Restarting your application after an update is safe. + +## Sample Upgrade Bundle Package + +See [Reload bundle demo](http://github.com/rhomobile/ReloadBundleDemo) for more information. diff --git a/docs/en/5.5/guide/appdesign.md b/docs/en/5.5/guide/appdesign.md new file mode 100644 index 00000000..88dad699 --- /dev/null +++ b/docs/en/5.5/guide/appdesign.md @@ -0,0 +1,64 @@ +#Application Architecture + +RhoMobile comes with built in mechanisms to create a streamlined application architecture that uses a MVC approach to cleanly seperate your data, business logic and user interface code. Using the RhoMobile's App and Model Generators allows you to get coding quickly by providing templates and prebuilt code. of course, you can choose to implement your own application architecture or use a JavaScript based framework like Backbone.JS + + +##What is MVC +The Model View Controller pattern separates data definitions (models) from business logic (controllers) from interfaces (views). MVC based apps are far more maintainable and understandable. All modern web development languages now use MVC as their dominant approach (Java/Struts, ASP.NET MVC, Python/Django, Ruby/Rails, PHP/Zend). + +By convention, files for each Model include a controller, a model class and view templates described below. + +## Model +To store data locally RhoMobile uses Sqlite on iPhone, Android, and Windows Mobile.On Blackberry version up to 5.0 Rhodes uses Hsql. On version 5.0 and higher it is possible to use Sqlite or Hsql. To access and manipulate stored data you may use RhoMobile's [ORM](../api/Orm) or [OrmModel](../api/OrmModel) APIs. ORM stands for object relational mapper and it provides a high level way to make the local database easier to program to. + +By convention, your model class is located in the model's folder. For the model "UserBase" the file would be called "user_base.rb" + +Example of added upper_name method to the model: + + :::ruby + class UserBase + include Rhom::PropertyBag + #add model specific code here + def upper_name + self.name.upcase + end + end + +See more details about Data Models [here](local_database). + +## Views (Templates) +Each controller action usually associated with a View template. The .erb files mentioned above are the templates used for views. Rhodes follows the Rails convention for template naming. + +* index.erb - lists the data model objects +* edit.erb - lets you edit the object +* show.erb - shows the object's attribute values +* new.erb - creates a new object + +These files are all created by the [rhodes generator](creating_a_project#creating-a-project-with-rhostudio). Inside the template, any valid HTML, JavaScript, and Ruby can be used, with Ruby code enclosed in <% and %> tags. See more information about Ruby ERB [here](http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/). + +## Controller +Each generated model controller has several actions to perform basic CRUD (create, read, update and delete) on the object. These actions are: + +* index - lists all objects +* new - displays the editing form for creating a new object +* create - actually creates the object +* edit - edits an existing object +* update - updates properties of the object +* show - views the object +* delete - deletes the object + +Developer's may also create any number of controller actions by simply defining new methods in the controller class. Each action associated with a url and can be performed by calling that url from the View in the WebView control. WebView control is a Web Browser imbedded in the application UI. + +For example, if you have an Account Model your controller actions will be in account_controller.rb file. To defined an action called 'list' you would create a method 'list' in the account_controller.rb file: + :::ruby + def list + #implement required business logic here + #... + #return result to the browser + render :action => :list + end + +To access this method from a view, you would specify the url to be 'Account/list' url. + + + diff --git a/docs/en/5.5/guide/barcode.md b/docs/en/5.5/guide/barcode.md new file mode 100644 index 00000000..6627f047 --- /dev/null +++ b/docs/en/5.5/guide/barcode.md @@ -0,0 +1,164 @@ +# Barcode + +The Barcode API class allows you to capture barcode data using your devices camera and/or dedicated scanning component like a 1D laser or 2D imager scanner found on Zebra Technologies devices. + +Because RhoMobile Suite is designed to run on both Consumer devices and Zebra Technologies' enterprise devices support for the Barcode API will vary from device to device. In general if you are developing for a consumer device the number of symbologies available to you will be limited to just the most common ones, eg EAN13, UPCA etc and your scanning will be via the device camera. If your application is running on Zebra Technologies' hardware you will have much finer control over a more fully featured Scanner, often with a choice of scanner hardware on the device. In general if you wish to capture a single barcode in a ‘one shot’ use case, eg your App just wants to capture a single barcode to be submitted to a price comparison website then use Barcode.take(callback); if your application is expecting a number of barcodes to be received, common in enterprise scenarios for example a user in a warehouse then use Barcode.enable(callback). + +## Default Object and Instance Objects +In RhoMobile 5.0, we have introduced instance objects on certain API classes. For the Barcode API, if you simply access `Rho.Barcode` or `Rho::Barcode` this will invoke the default object which will pick the `best` scan engine on the device. You can also define your own instance of Barcode object by either using the [Barcode.getDefault()](../api/barcode#mgetDefaultSTATIC) method or by using one of the objects returned in the [Barcode.enumerate()](../api/barcode#menumerateSTATIC) method. If you would like to change the properties of the default scanner so that you do not need to always reset properties or keep a global variable instance available + +JavaScript + :::javascript + var defaultScanner = Rho.Barcode.getDefault(); + defaultScanner.allDecoders = false; + defaultScanner.code128 = true; + Rho.Barcode.setDefault(defaultScanner); + +Ruby + :::ruby + @defaultScanner = Rho::Barcode.getDefault() + @defaultScanner.allDecoders = false + @defaultScanner.code128 = true + Rho.Barcode.setDefault(@defaultScanner) + + +## Detecting Barcode Capabilities +To see what barcode scanners are available to use, you can use the `Barcode.enumerate method`. This method will return an array of `Barcode` instance objects. You can then use the Barcode instance methods and properties. + +JavaScript + :::javascript + var scanners; + + function choose_scanner(){ + + // Enumerate returns an array of scanner objects + scanners = Rho::Barcode.enumerate(); + + // now the variable scanners contains an array of Barcode objects + + } + + function scan_using_chosen_scanner(scanner_index) { + var scanner = scanners[scanner_index]; + + // scanner will now be an instance object of Barcode + // so I can use Barcode methods like .take() + scanner.take({}, scan_received_callback); + } + +Ruby + :::ruby + def choose_scanner + # Obtain list of available scanners on the system. + $scanners = Rho::Barcode.enumerate + + end + + def scan_using_chosen_scanner + # receive an integer as parameter, which represent the number of the scanner we wish to use + scanner = $scanners[@params["scannerIndex"].to_i] + scanner.take({}, url_for(:action => :scan_received_callback)) + end + +## Scanning Barcodes +There are a few ways to scan a barcode and the options available to you will depend on the type of device you have + +### Univeral Method +`Barcode.take` is a universal method for scanning barcodes that will work across all devices and platforms (as long as there are scanning capabilities either through a camera or scan engine). When called, this method immediately invokes either the camera or the 1D Laser/2D Imager scan engines. + +When the barcode is scanned, the data will be returned in the callback return object. This object will contain a `status` and `barcode` attribute with the result. If the user decided to not scan a barcode or a timeout occured, then the status will be `cancel` + +JavaScript + :::javascript + function scan_using_default_scanner(){ + // Scan with default options + // We could have passed in an object of Barcode.properties + // in the first param + Rho.Barcode.take({}, scan_received); + } + + function scan_received(params) + // Did we actually find a barcode ? + // If status is not 'ok', the scan was cancelled + + if (params["status"]=="ok") { + alert('Barcode scanning complete. Scanned barcode: '+params["barcode"]); + } else { + alert('Barcode scanning aborted'); + } + + } + +Ruby + :::ruby + def scan_using_default_scanner + # Scan with default options + # We could have passed in some Barcode.properties in the first param + Rho::Barcode.take({}, url_for(:action => :scan_received)) + end + + def scan_received + # Did we actually find a barcode ? + # If status is not 'ok', the scan was cancelled + if @params["status"] == "ok" + Rho::Log.info(@params["barcode"],"Barcode result") + else + Rho::Log.info("Cancelled", "Barcode result") + end + end + +### Dedicated Hardware Trigger +On Zebra Technologies devices there is a dedicated hardware button that is used as a `scanner trigger`. In order to use this feature, you would use [Barcode.enable()](../api/barcode#menable). This will enable the scanner trigger for accepting barcodes. Like with the `take` method, we could optionally pass in a set of properties to use, but must always provide a callback for handling the result. + +The `Barcode.enable()` returns a different set of callback parameters: + +* **data** : The data decoded by the scanner or imaging device +* **source** : The source device and human readable decoder type of the decoded barcode or symbol +* **type** : Hex value representing the decoder type +* **time** : The time at which the decode occurred (hh:mm:ss) +* **length** : The length of the decoded barcode or symbol +* **direction** : The direction the barcode was scanned, either forward, reverse or unavailable + +Once the barcode button is enabled, anytime the user presses the trigger the scanner will be started and upon scanning a barcode the callback method will be called. When you no longer need or want this behavior you should disable the scanner button using [Barcode.disable()](../api/barcode#mdisable) + +JavaScript + :::javascript + function scan_using_msi_trigger(){ + // Enable the scan button on MSI device + + Rho.Barcode.enable({}, scan_received); + } + + function scan_received(params) + // the enable method returns a different set of callback params + // and only is called when a barcode is scanned + // if the user decides to not scan a barcode this method + // will not be called + + + alert('Barcode scanning complete. Scanned barcode: '+params["data"]); + + // disable the scan trigger + Rho.Barcode.disable(); + } + +Ruby + :::ruby + def scan_using_msi_trigger + // Enable the scan button on MSI device + + Rho::Barcode.enable {}, url_for(:action => :scan_received) + end + + def scan_received(params) + // the enable method returns a different set of callback params + // and only is called when a barcode is scanned + // if the user decides to not scan a barcode this method + // will not be called + + + Rho::Log.info(@params["data"],"Barcode result") + + // disable the scan trigger + Rho::Barcode.disable() + end diff --git a/docs/en/5.5/guide/bluetooth.md b/docs/en/5.5/guide/bluetooth.md new file mode 100644 index 00000000..894c322d --- /dev/null +++ b/docs/en/5.5/guide/bluetooth.md @@ -0,0 +1,105 @@ +# Bluetooth + +Bluetooth API provide access to Bluetooth serial port connection between phone and another phone, phone and PC, phone and external Bluetooth device (for example external Bluetooth GPS device). + +To allow Bluetooth enable the bluetooth capability. This is done by adding the following lines to build.yml: + + :::yaml + capabilities: + - bluetooth + +Currently Bluetooth support has the following limitations: + +* On Apple device (iPhone, iPad etc.), you can connect only to another Apple device. +* On any platform, except iPhone, you should pair your devices before making connection. +* You can change local device name for display on another device only on iOS and Android platform - for WM use system settings for change local device name. +* Only one connection session can be created and used on any device. You should close your current session before making another session. +* One-to-few peers connection scheme is unsupported. + +There are two steps to make connection and start using of Bluetooth : + +* Make connection session: execute `Rho::BluetoothManager.create_session` and setup callback where you receive result of connection. That callback will get events related to making connection(connect ok, canceled by user, error). Connection provided by platform specific UI. +* For make connection without UI, you should execute `Rho::BluetoothManager.create_server_and_wait_for_connection` on server and `Rho::BluetoothManager.create_client_connection_to_device` on client. On client you should specify server name(display name - not Bluetooth ID!) for connect. Specify callback - callback have the same parameters with `Rho::BluetoothManager.create_session`. You can cancel connection process by `Rho::BluetoothManager.stop_current_connection_process` +* After receiving successful result and name of connected device in create_session_callback you should setup session_callback by `Rho::BluetoothSession.set_callback` to process incoming session events from connected device (data received) or event related to this session connection(disconnect, errors). + +**NOTE: Connection without UI worked only on iOS and Android platforms!** + +### Bluetooth API + +You can use the [BluetoothManager API](../rhodesapi/bluetoothmanager-api) to make a connection between your Bluetooth-equipped device and another Bluetooth-equipped device. + + * [is_bluetooth_available](../rhodesapi/bluetoothmanager-api#isbluetoothavailable) - Returns true if Bluetooth is available on the device, false otherwise. + * [off_bluetooth](../rhodesapi/bluetoothmanager-api#offbluetooth) - Turn Bluetooth off. + * [set_device_name](../rhodesapi/bluetoothmanager-api#setdevicename) - Change the local device name. + * [get_device_name](../rhodesapi/bluetoothmanager-api#getdevicename) - Get local device name for current device. + * [get_last_error](../rhodesapi/bluetoothmanager-api#getlasterror) - Returns the last error: OK or ERROR or CANCEL. + * [create_session](../rhodesapi/bluetoothmanager-api#createsession) - Creates a Bluetooth session. + * [create_server_and_wait_for_connection](../rhodesapi/bluetoothmanager-api#createserverandwaitforconnection) - Connect without a user interface. Makes the current device discoverable for another device, and waits for the client connection from the other device. + * [create_client_connection_to_device](../rhodesapi/bluetoothmanager-api#createclientconnectiontodevice) - Connect without user interface. Make the client connection to another device. + * [stop_current_connection_process](../rhodesapi/bluetoothmanager-api#stopcurrentconnectionprocess) - When connecting without user interface (`create_server_and_wait_for_connection`), cancel the current connection. + +You can use the [BluetoothSession API](../rhodesapi/bluetoothsession-api) to manage a connection session between your Bluetooth-equipped device and another Bluetooth-equipped device. + + * [set_callback](../rhodesapi/bluetoothsession-api#setcallback) - Set the Bluetooth session callback. + * [disconnect](../rhodesapi/bluetoothsession-api#disconnect) - Disconnect from the device. + * [get_status](../rhodesapi/bluetoothsession-api#getstatus) - Get the session status. + * [read](../rhodesapi/bluetoothsession-api#read) - Read data from the connected device. + * [write](../rhodesapi/bluetoothsession-api#write) - Write data to the connected device. + * [read_string](../rhodesapi/bluetoothsession-api#readstring) - Read string from the connected device. + * [write_string](../rhodesapi/bluetoothsession-api#writestring) - Write string to the connected device. + +### Example of Controller with using Bluetooth API + +This is not a complete example (for a link to a complete example, see the link below this example). This code just shows how you can make a connection and send/receive strings. + + :::ruby + require 'rho/rhocontroller' + require 'rho/rhobluetooth' + + class BluetoothController < Rho::RhoController + @layout = :simplelayout + $connected_device = nil + + def index + render + end + + def start_bluetooth + if Rho::BluetoothManager.is_bluetooth_available() + Rho::BluetoothManager.create_session(Rho::BluetoothManager::ROLE_CLIENT, url_for( :action => :connection_callback)) + end + end + + def send_string(str) + Rho::BluetoothSession.write_string($connected_device, str) + end + + def connection_callback + if @params['status'] == Rho::BluetoothManager::OK + $connected_device = @params['connected_device_name'] + Rho::BluetoothSession.set_callback($connected_device, url_for( :action => :session_callback)) + send_string('Hello friend !') + end + end + + def session_callback + if @params['event_type'] == Rho::BluetoothSession::SESSION_INPUT_DATA_RECEIVED + while Rho::BluetoothSession.get_status($connected_device) > 0 + str = Rho::BluetoothSession.read_string($connected_device) + + # use received string + + end + end + end + + def close_all + Rho::BluetoothSession.disconnect($connected_device) + Rho::BluetoothManager.off_bluetooth() + end + + end + +### Example of chat application using Bluetooth connection + +You can find a complete example of using Bluetooth API in [Rhodes-System-Api-Samples](http://github.com/rhomobile/rhodes-system-api-samples). See Bluetooth Chat Demo page - [BluetoothChat](http://github.com/rhomobile/rhodes-system-api-samples/tree/master/app/BluetoothChat/). In this example you can see how to exchange text messages between two different devices. You also can use this example for connect to external Bluetooth device (external GPS device for example) or PC or Mac (use terminal to see and send messages). diff --git a/docs/en/5.5/guide/build_android.md b/docs/en/5.5/guide/build_android.md new file mode 100644 index 00000000..2aa1e42d --- /dev/null +++ b/docs/en/5.5/guide/build_android.md @@ -0,0 +1,274 @@ +# Build for Android +## Setup +Follow the instructions for [setting up the development environment](nativesdksetup#setup-for-android) for building Android applications. + +### Building Remotely +Alternatively, you can create the device builds remotely with RhoMobile hosted builds. Refer to our [remote build guide](../../hosted/guide/remote-build-guide) for more info. + +## Set up minimal Android SDK API level +The minimal API level supported by Rhodes is 4 (Android 1.6) +You can set a greater minimal API level in build.yml. For example, the following entry will restrict installing your application on any Android OS prior to 3.0: + + :::yml + android: + minSDK: 11 + +## Device capabilities settings in build.yml +On Android, you must specify your device capabilities the your application will use. By default, these capabilities are NOT enabled. + +In RhoStudio, you can double-click on your application's build.yml file, then click the Rhobuild setting tab, then click the Capabilities: Add button. You will see a list of capabilities you can check to activate for your application. + +![img](http://rhodocs.s3.amazonaws.com/rhostudio-tutorial/select-capabilities-4.0.png) + +You can also edit the build.yml file directly with a text editor. Here is a list of capabilities you can add to the capabilities section in your application build.yml file. + + :::txt + audio + camera + gps + network_state + phone + pim + record_audio + vibrate + bluetooth + calendar + sdcard + push + hardware_acceleration + +## Customizing application's AndroidManifest.xml +If you have an urgent need to put changes in AndroidManifest.xml that are not supported by build settings, you may edit a manifest template located at /platform/android/Rhodes/AndroidManifest.xml.erb. Please note that **this** template does not relate to a particular application: it is used for every Android application build. + +> Note: To see how to change AndroidManifest.xml at extension build, see [Extending the Rhodes Framework](native_extensions#platform-specific-notes). + +You can also specify an android manifest file for your app in particular by specifying a path to the template in your build.yml file. + +For Example: + + :::yml + android: + manifest_template: path/to/template.erb + +## Building and Running Your Android Application with RhoStudio +To start the build process, create a Run Configuration: select your project in the Project Explorer, and either: + * select Run->Run Configurations... from the main menu, + * or right-click on your project, and select Run As->Run Configurations from the popup menu. + +![img](http://rhodocs.s3.amazonaws.com/build-rhodes-app/run-configurations-menu-4.0.png) + +The Run Configurations window appears. + +### Running on the Android Simulator with RhoStudio +To run on the Android simulator, select Android in Platform, Simulator in Simulator type, and enter the name of the AVD in AVD name. Then click the Run button. + +![img](http://rhodocs.s3.amazonaws.com/build-rhodes-app/run-configurations-avd-4.0.png) + +You can get a list of the AVD names by running the SDK setup: on Macintosh and Linux, navigate to and run /tools/android. On Windows, navigate to and run /SDK Setup.exe. Then click Virtual devices. + +![img](http://rhodocs.s3.amazonaws.com/build-rhodes-app/android-virtual-devices-4.0.png) + +> Note: You must install versions of the Android emulator that correspond to the version of Android that you set in your build.yml. For instance, if you set your Android version to 4.4.2 as such: + :::yml + android: + version: 4.4.2 +You must have the 4.4.2 emulator installed or the app will not run properly or may not run at all. + +### Running on an Android Device with RhoStudio +To run on an Android device, first set up your device as shown in the Android documentation for [Using Hardware Devices](http://developer.android.com/guide/developing/device.html). + +Then connect your Android device to your computer with a USB cable. + +In the Run Configurations window, select Android in Platform, and Device in Simulator type. + +### Reading the Log File with RhoStudio +After you run your application in RhoStudio, your application log file, rholog.txt, is stored in your application directory. You can open and read rholog.txt in RhoStudio by double-clicking on it in the Project Explorer. + +## Building and Running Your Android Application from the Command Line +From the command line, navigate to your application directory. + +To run your application in the Android emulator, run the following command: + + :::term + $ rake run:android + +You can adjust the settings of the Android emulator from your application's build.yml file. For example, to specify the platform version number and the emulator AVD name: + + :::yml + android: + version: 2.1 + emulator: myDeviceEmulator20 + +You can also disable the Android title in the application and set the orientation to portrait (or landscape): + + :::yml + android: + android_title: 0 + orientation: portrait + +If the rake command gets stuck, you can kill the command window, open another window, and run: + + :::term + $ adb start-server + $ rake run:android + +> Note: If you didn't run your Android simulator yet or don't have AVD configuration set, you will be asked a few questions about emulator configuration. You should answer "yes" for most questions or use default answers. As a result new AVD configuration will be created. + +To uninstall your application from the emulator, run: + + :::term + $ rake uninstall:android + +To run on an Android device, first set up your device as shown in the Android documentation for [Using Hardware Devices](http://developer.android.com/guide/developing/device.html). + +Connect your Android to your computer with a USB cable. You can verify that your device is connected by executing: + + :::term + $ adb devices + +If connected, you'll see the device name listed. If your computer doesn't see the device, try killing the adb process first: + + :::term + $ adb kill-server + $ adb install .apk + +After you have your device connected, navigate to your application directory and run: + + :::term + $ rake run:android:device + +This will build your application and sign it with auto-generated self-signed certificate. + +To uninstall your application from the device, run: + + :::term + $ rake uninstall:android:device + +## Building an Android Production Version +### Modifying the build.yml +To build a production version of your application, edit your application's build.yml as below: + + :::yml + android: + production: + certificate: path/to/your/developer/certificate + password: "password-of-the-certificate" + alias: "keystore.alias" + +This will use the specified certificate to sign your application. If the certificate is not found, it will be auto-generated, and you'll be prompted with several questions like your name, organization etc. The path to the certificate may be absolute or relative to your app directory. If you don't want to use an auto-generated certificate, refer to the [these instructions](http://developer.android.com/guide/publishing/app-signing.html) on how to create a certificate manually. + +### Setting your application name, icon and loading screen +You will need to provide a name and icon for the application that the user will see on the device. You can also customize the loading screen that is shown while your application is launching. Refer to the [Application Icon and Splash Screen](app_icon_splash) guide for detailed information. + +You can refer to the [recommended icon guidelines](http://developer.android.com/design/style/iconography.html). + +### Turn off developer options +Update your application's configuration files to make sure developer / debug / profile options are turned off. + +The below values can be used as a guide for `rhoconfig.txt`, skip any setting which is not already present. + + :::term + MinSeverity = 3 + LogToOutput = 0 + net_trace = 0 + log_skip_post = 0 + +The below values can be used as a guide for `build.yml`, skip any setting which is not already present. + + :::yml + profiler: 0 + +### Creating your application package +Once your configuration is set up, you can run: + + :::term + $ rake device:android:production + +The signed APK will be located in `/bin/target`. + +## Installing Your Application Package to Your Android Device +To install the application on the device run: + + :::term + $ adb -d install -r /bin/target/_signed.apk + +## Publishing on Google Play +### Getting a Google Play publisher account +To publish your application on Google Play you need a publisher account. Visit the [Google Play Developer Console](https://play.google.com/apps/publish/) to create one. + +### Getting a Google Wallet Merchant account +If you want to sell your application on Google Play, you will also need to set up a Merchant Account. + +To setup a merchant account: + +* Login to the [Developer Console](https://play.google.com/apps/publish/) +* Goto 'Financial reports' and then click on 'Setup a Merchant Account now'. + +### Uploading and Publishing your application +The Google Play [Launch Checklist](http://developer.android.com/distribute/googleplay/publish/preparing.html) has detailed steps needed to publish your application. + +Below is a short summary of the steps to be done on the Developer Console: + +* Choose the content rating for your application +* Choose the countries for distribution +* Choose the compatible devices for your application +* Choose your pricing (or free) +* Add screenshots, video, license agreement, etc. +* Uploading the APK +* Complete the application's product details +* Publish + +Refer to the [Google Play developer console](https://developer.android.com/distribute/googleplay/publish/console.html) documentation for more information and step-by-step instructions. + +## Publishing on other Android marketplaces +Because Android is an open platform, you are not limited to publishing only on the Google Play store: you can also distribute your .apk packages directly to end-users as a download, or sign up for alternative marketplaces such as the [Amazon Appstore for Android](http://www.amazon.com/mobile-apps/b?ie=UTF8&node=2350149011) ([Developer reference documentation](https://developer.amazon.com/welcome.html)) + +## Using Linux +On Macintosh and Windows computers, you can create RhoMobile apps within RhoStudio. However, on Linux installations, you can use Eclipse, since RhoStudio is not available for Linux. + +Create a new workspace in the following directory: `/platform/android` + +In Eclipse, open Window > Preferences. + +Click on Android node in the tree and specify the file path to the installed Android SDK (for example: `~/android-sdk`). + +Import all projects from the directory for your new workspace: `/platform/android` + +If you have set the option to build sources automatically, your project will be compiled just after the import. + +Select Properties from the RhoMobile project context menu and select one of the latest Google API targets for Android. + +Check the bin directory. You should see the Rhodes.apk file that was created. It will be signed with the debug key provided with SDK. + +Now you are ready to install your application on your device and/or emulator. + +In case of troubles in Eclipse while setting up the Android SDK and target, try "Rhodes project context menu" > "Android Tools" > "Fix Project Properties". + +It is possible your application has stopped unexpectedly just after the first build. In this case try to copy auto-generated java source files from the application folder /bin/tmp to the Rhodes project. + +## Getting application log from device or emulator +To see all emulator messages, run 'adb logcat' and start application on emulator. + +To see all device messages, run 'adb -d logcat' and start application on device. + +## Remarks +### SDCard Access +Extensions which came from RhoElements (i.e. AudioCapture) that could possibly write files to external storage will require "write SD card" permissions as part of the extension's AndroidManifest. You cannot remove the ability to write to the SD card as it would cause the extension to malfunction. Therefore, the capability has already been granted on build, and any capability added by you will be ignored. This being the case, the following extensions will always be able to write to the SD card by default: + +* AudioCapture +* MediaCapture + +### Supported Icons +The android build script supports icons for different screen density. To use this feature .png icons with exact size suffix should be added to `/icon` folder. + +Next icon file names are supported: + +* icon.png - remains as default icon resource +* icon36.png - LDPI screen density icon. +* icon48.png - MDPI +* icon72.png - HDPI +* icon96.png - XHDPI +* icon144.png - XXHDPI +* icon192.png - XXXHDPI + +The suffix means _recommended_ icon dimension in pixels and it is allowed to have slightly different size. In other words in icon36.png can actually be an image with size 32x32 or even 72x72. \ No newline at end of file diff --git a/docs/en/5.5/guide/build_config.md b/docs/en/5.5/guide/build_config.md new file mode 100644 index 00000000..cd9cd1f6 --- /dev/null +++ b/docs/en/5.5/guide/build_config.md @@ -0,0 +1,580 @@ +# Build time configuration +Build time settings are dictated by a file in your app directory called `build.yml`. By default, this file has the most commonly used settings and some defaults that will work fine for most platforms. However, you may need to modify it at certain points. For example, if you need to build for an iOS device, you'll need to change the iphone: sdk: section to use an `iphoneos` SDK instead of an `iphonesimulator` SDK. Other special requirements apply to building for Android. Please refer to the [Android-specific Settings section](#android-specific-settings) for more information. + +This doc will provide guidelines and examples for modifying the `build.yml` file without jeopardizing your app. + +## Default build.yml Settings +When you create your app, a default version of the build.yml file will be generated and it will look like this: + + :::yaml + #sdk: "/path/to/rhodes_gem" + sdkversion: 5.0.0 + name: My RhoMobile App + version: 1.0 + vendor: rhomobile + build: debug + applog: rholog.txt + iphone: + configuration: Release + sdk: iphonesimulator7.0 + provisionprofile: + codesignidentity: iPhone Developer + entitlements: "" + BundleIdentifier: com.rhoappbuildersinc.myrhodesapp + BundleURLScheme: buildymltest + ApplicationQueriesSchemes: + wp8: + productid: '4ff21ee0-8ef1-0132-ec69-7831c1c374dc' + android: + manifest_template: 'AndroidManifest.erb' + version: 2.3.3 + wm: + #sdk: "MC3000c50b (ARMV4I)" + #sdk: "Windows Mobile 6.5.3 Professional DTK (ARMV4I)" + + extensions: ["rhoconnect-client"] + +### Settings Details + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                            Group\\SettingDescriptionPossible ValuesExample
                                                                            sdkPath to your rhodes gem. This is commented out by default to let rhodes determine the latest gem and use that. If you have multiple rhodes gems and you wish to use one that is not the latest one, specify that here.String"/path/to/rhodes_gem"
                                                                            sdkversionThe version of your Rhodes gem.Rhodes Version5.0.25
                                                                            nameThe name of your app.StringMy RhoMobile App
                                                                            versionThe version of your app.App Version1.0.5
                                                                            vendorThe name that will be set as the vendor of your app. Usually this will be your Company's name.StringRhoApp Builders, Inc.
                                                                            buildBuild configuration of this version of your app.Debug
                                                                            development
                                                                            release
                                                                            development
                                                                            applogName of app log file on the device.Log file name/path/to/log_file.txt
                                                                            iphone\\configurationBuild configuration to pass to XCode.Debug
                                                                            Distribution
                                                                            Release
                                                                            Distribution
                                                                            iphone\\sdkThe version of the sdk used to build. Typically, iphonesimulatorX.X or iphoneosX.X.iPhone SDK Versioniphoneos8.0
                                                                            iphone\\provisionprofileThe UUID of your provisioning profile to use when signing.UUIDxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
                                                                            iphone\\codesignidentityThe name of the code signing identity to use when signing for device.Code Sign Identity, StringrhoAppDevIdentity
                                                                            iphone\\entitlementsProperty list file for entitlements for your build. Typically, Entitlements.plist..plist filemyAppEntitlements.plist
                                                                            iphone\\BundleIdentifierBundle identifier – used in provisioning profile.Stringcom.rhoappbuildersinc.myrhodesapp
                                                                            iphone\\BundleURLSchemeBundle URL scheme of your app (used for opening your application from another application by using custom URL scheme).StringMy Rhodes App
                                                                            iphone\\ApplicationQueriesSchemesWhitelist of URL schemes that can be used by your app to provide a service, pass data or launch another app. URL schemes specified here are added during build to the LSApplicationQueriesSchemes key in the app's info.plist. For more information, refer to the iOS 9-specific Settings section, below.Array of strings["http", "sms", "tel", "facetime"]
                                                                            wp8\\productidA productid GUID to application build.yml.GUID'17d460b0-701f-0131-ea62-482a14303cd5'
                                                                            android\\Manifest TemplateIt is possible to specify manifest erb template file at build.yml.Manifest Template Filemanifest_template: 'AndroidManifest.erb'
                                                                            android\\versionThe version of Android for which you will be building.Android version2.3.3
                                                                            extensionsComma-separated list of extensions your app will be using.Comma-separated list["rhoconnect-client"]
                                                                            + +## Other Build-time Settings +The following are some non-default settings that you may add to the build.yml in certain circumstances. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                            Group\\SettingDescriptionPossible ValuesExample
                                                                            App TypeIf you are building an app for Windows Mobile or Windows CE you must specify the app_type as "rhoelements" in your build.yml file. By default, this value does not exist in the build.yml and is only necessary to specify a RhoElements licensed app."rhoelements"app_type: "rhoelements"
                                                                            Android TitleIf you want your app to hide the default Android title bar, you need to set android_title to '0' in your build.yml file.0 - Hidden
                                                                            1 - Visible
                                                                            android_title: 0
                                                                            JS API BridgeThis option is typically only used for debugging purposes. If your AJAX-based app is not working properly, you can set this to true. If your application code resides on a remote server (as opposed to running locally), the Rhomobile Javascript APIs will not be available when this settings = true.true - Enabled
                                                                            false - Disabled
                                                                            ajax_api_bridge: true
                                                                            JavaScript and CSS ObfuscationTo enable JavaScript and/or CSS code obfuscation of the files in the public folder of your app, just add the following lines to the build.yml: +
                                                                            + obfuscate:
                                                                            +   js: yes
                                                                            +   css: yes
                                                                            +   exclude_dirs: ["jqmobile", "jqtouch", "jquery"]
                                                                            + NOTE: The jqmobile, jqtouch, and jquery folders must be excluded when obfuscation is enabled, because the obfuscated versions of these libraries are there already.
                                                                            If JavaScript or CSS code obfuscation is not required, then just omit js or css line accordingly. + obfuscate:
                                                                            +   js: yes
                                                                            +   css: yes +
                                                                            JavaScript and CSS MinificationTo enable JavaScript and/or CSS code minification of the files in the public folder of your app, just add the following lines to the build.yml: +
                                                                            + minify:
                                                                            +   js: true
                                                                            +   css: true
                                                                            +   exclude_dirs: ["jqmobile", "jqtouch", "jquery"]
                                                                            + NOTE: The jqmobile, jqtouch, and jquery folders must be excluded when minification is enabled. +
                                                                            If JavaScript or CSS code minification is not wanted, then just omit js or css line accordingly. + minify:
                                                                            +   js: false
                                                                            +   css: false
                                                                            +   exclude_dirs: ["jqmobile", "jqtouch", "jquery"] +
                                                                            Building for Intel-Based Processors on AndroidBy default, the build process will build only for ARM-based processors but, Rhodes can be configured to build for Intel-based processors instead. To build for such a device, you must set a flag in your build.yml file. You can also elect to build for both arm AND Intel-based processor by specifying abis: [arm, x86].x86 - Build for Intel Processors
                                                                            arm - Build for arm-based processors
                                                                            android:
                                                                              abis: [x86]
                                                                            Production iOSTo build iOS for production, there are a few settings that need to be added to your build.yml file in order to allow Rhodes correctly configure the build. You'll need to add the mobileprovision file, the certificate_file, and the certificate_password in a production sub-heading in the iphone section of the build.yml as shown below. +
                                                                            + iphone:
                                                                            + ...
                                                                            +   production:
                                                                            +     mobileprovision_file: "./production/PROVISION.mobileprovision"
                                                                            +     certificate_file: "./production/CERTS.p12"
                                                                            +     certificate_password: "PASSWORD" +
                                                                            +
                                                                            you'll need to add your custom information into the appropriate fields here. + mobileprovision_file: "./production/PROVISION.mobileprovision"
                                                                            + certificate_file: "./production/CERTS.p12"
                                                                            + certificate_password: "PASSWORD" +
                                                                            + +## Capabilities +There are two ways of modifying your app's capabilities: + +* Direct Edit - Just open the file and edit it. +* RhoStudio Modification - The RhoStudio IDE provides a GUI for modifying the capabilities using check-boxes. + +### Direct edit +You can easily change specific settings in your build.yml file by simply opening it in you favorite text editor and modifying the text. + +To enable specific device capabilities, edit your application's build.yml as follows: + + :::yaml + capabilities: + - camera + - gps + android: + capabilities: + - network_state + +Rhodes support common plus platform-specific capabilities. They are merged into a single list at build time. + +> Note: Only Android currently recognizes these platform-specific configuration options. Enabling these options across other platforms is planned for a future release. + +List of supported capabilities: + +* **audio** allows use of audio hardware (record audio, modify audio settings) +* **camera** allows use of hardware camera +* **gps** allows use of geo location service +* **network_state** allows read device network state (connected/disconnected) +* **phone** allow make calls/read phone state +* **pim** allow read/modify personal information and contacts +* **push** allows use of PUSH on device +* **record_audio** allows the recording of audio ('audio' implies it) +* **vibrate** allows use of hardware vibration mechanism +* **bluetooth** allows use of bluetooth hardware +* **calendar** allows access to default device calendar +* **sdcard** allows writing to the SD card on Android devices + +## Windows Mobile/CE-specific Settings +You can specify where the `config.xml` file will reside on your device using the `config:` option. + + :::yaml + wm: + rhoelements: + config: "/Config/Config.xml" + +* config : path to the custom [Config.xml](runtime_config#configxml) file to use. This path is relative to the RhoMobile Project. + +
                                                                            +## iOS 9-specific Settings + +Beginning with iOS 9, Apple now requires that apps declare in advance which URL schemes they would like to access when using the 'canOpenURL' method. According to Apple, this improves privacy by preventing an app from scanning a list of 'known' URL schemes on a device in an attempt to compile a list of installed apps. The change is intended to apply only to the 'canOpenURL' method, but the 'openURL' method also might generate a “This app is not allowed to query for scheme [scheme]” syslog entry. To change a URL scheme whitelist, an update must be submitted to Apple. + +URL schemes can be used by an app to provide a service, pass data or launch another app. URL schemes specified as below are added during build to the LSApplicationQueriesSchemes key in the app's `info.plist` parameter list. To specify a whitelist of URL schemes, add a line like the following to the 'iphone' section of your app's `build.yml`: + + + :::yaml + iphone: + ... + ApplicationQueriesSchemes:["http", "sms", "tel", "facetime"] + ... + + + +## Android-specific Settings +The capabilities listed above are directly related to the Android device capabilities that your app will require, and for which the user will be asked to give permission when installing the app. You can add capabilities to your Android app by adding a 'capabilities' section to your `build.yml` in the 'android' heading as below. + +NOTE: To work around build issues related to Android-M, we recommend adding 'version: 4.1.0' in the 'android:' section, as below. + + + + + :::yaml + android: + capabilities: + - hardware_acceleration + mapping: yes + extensions: + - gmaps + version: "4.1.0" + + +* **hardware_acceleration** enables video playback and other resource-intensive apps +* **mapping** enables the use of mapping apps +* **gmaps extension** enables the use of Google maps for mapping + +In RhoStudio, you can double-click on your application's `build.yml` and edit from the text editor, or edit it directly using a text editor of your choosing. + +RhoMobile 5.2.2 will build successfully with Android versions up to and including Android 5.1 (Android L). **For Android builds, please install an Android SDK with API level 22 or lower**. For information about Android API levels, please visit the [Android API documentation](http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels). + +The Android SDK allows you to programatically specify an application's compatibility with one or more versions of the Android platform using an API-Level integer. **The API Level can be specified in the `AndroidManifest.erb`, which must then be specified in the `build.yml`** (see sample, below). Android versions specified here will be compared to that of a given Android target device. + +The **syntax for the Android `` parameter**: + + + :::Ruby + + +For more information about this parameter, please visit the [Android uses-sdk page](http://developer.android.com/guide/topics/manifest/uses-sdk-element.html). + +### Android Keycode Mapping +Keycodes are constants that uniquely identify the ASCII values of device keypresses (hard or soft). On Android devices, the keycode values of certain keys are sometimes not returned as expected or desired. To ensure control and accuracy of key presses, RhoMobile apps for Android can have some or all of their default keycode values assigned from a file when the app starts up. Keycode value(s) can be assigned through the current [KeyCapture 4.x API](../api/keycapture) as well as legacy 2.x versions. The steps below apply to all API versions. + +**This section applies to Android only**. + +The following facts apply generally to keycode mapping: + +* Keycode mapping **requires RhoMobile Suite 5.4** or higher. +* Mapping **requires a KeyCapture API**. [Read more](../api/keycapture). +* Keycode mappings are contained in the `keycodemapping.xml` file. +* The `keycodemapping.xml` file is the same for all versions of the KeyCapture API. +* The mapping file is read each time the RhoMobile app is launched. +* Upon app install, a mapping-file template is placed in the app's installation directory, usually `sdcard0/android/data/com.rhomobile.appName`. +* Keycodes not mapped (or left blank in the mapping file) retain their default values. +* [Additional restrictions](../api/keycapture#Remarks) apply to keycapture and keycode mapping. + +## Mapping Keycodes +To assign custom keycodes to Android hard or soft keys, follow these simple steps: + +1. Deploy the app to the device. + +2. Navigate to the installation directory on the device. +This is usually `sdcard0/android/data/com.rhomobile.appName` + +3. Copy the `keycodemapping.xml` template to a PC and open it for editing. + +The template should look similar to the image below: + + :::xml + + + + + + + + + + + + + +4. Copy and paste the example KEYCODE tag (omitting the comment tags) as shown: + + :::xml + ... + + + + + + + + + ... + +5. Replace the values (within the quotes) for 'name,' 'from' and 'to' fields, as required. + +> **Note**: The 'from' field refers to the key's current keycode value; the 'to' will hold the value that replaces it. In the example above, pressing the '0' key (after mapping) will generate a keycode value of '0x30' instead of its former value of '7.' The 'name' field can hold any value; [standard Android key names](http://developer.android.com/reference/android/view/KeyEvent.html) are recommended. + +NOTE: For help exposing keycodes, see Handling Incorrect Keycodes section below. + +6. Repeat steps 4 and 5 until all required keycodes are mapped. + +For example: + + :::xml + + + + + + + + + + + + + + + +7. Copy the modified `keycodemapping.xml` file to its original location on the device, replacing the template. + +8. Relaunch the app and check that its keycodes are mapped as specified. + +##Handling Incorrect Keycodes +Once it is determined that correct keypresses are generating incorrect keycodes, the incorrect keycode value must be determined before the correct one can be substituted. This process uses JavaScript to expose the keycodes that appear when pressing one or more keys. + +The first step is to confirm that Windows keycodes are not being forced as a result of the <isWindowsKey> tag: + +1. In the app's Config.xml file, **confirm that the <isWindowsKey> tag has a value of 0**. + +2. Using one of the KeyCapture APIs, **reveal the keycodes generated by keypresses** to identify incorrect keycode value(s). The test code might look something like this: + + :::javascript + // KeyCapture API 4.x: + EB.KeyCapture.captureKey(false,'all',function(obj){alert(obj.keyValue) + }); + + // KeyCapture API 2.x: + + + +3. **Map the incorrect keycode values to the correct ones** using the same syntax described in the earlier section: + + :::xml + + +For example, if Step 2 determined that the keycode value being generated is 0x05 and the desired value is 0x06, then the correct mapping statement would be: + + :::xml + + +where "KEYCODE_X" = the desired keycode name. [Standard Android key names](http://developer.android.com/reference/android/view/KeyEvent.html) are recommended. + +4. Relaunch the app and **repeat Step 2 to confirm** that correct code(s) are generated. +##More Information + +* [KeyCapture API](../api/keycapture) +* [Keys that cannot be captured](../api/keycapture#Remarks) +* [Android KeyEvents documentation](http://developer.android.com/reference/android/view/KeyEvent.html) + + +### RhoStudio Modification +You can also edit the capabilities that your app will have access to through RhoStudio. To do this, double click your build.yml in your app's project in the project explorer pane in RhoStudio. + +![img](https://s3.amazonaws.com/rhodocs/guide/build_config/open-build-yml-4.1.png) + +Once you have done this, you should see the following screen wherein you can modify your build.yml settings, mainly, the capabilities. + +![img](https://s3.amazonaws.com/rhodocs/guide/build_config/build-yml-edit-window-4.1.png) + +Click the add button next to the capabilities field to bring up this window and add capabilities by clicking the corresponding check-box. + +![img](https://s3.amazonaws.com/rhodocs/guide/build_config/select-capabilities-rhostudio-none-selected-4.1.png)![img](https://s3.amazonaws.com/rhodocs/guide/build_config/select-capabilities-rhostudio-camera-and-bt-4.1.png) + +You'll notice that as you add capabilities to your app, the build.yml text file will change to reflect these added capabilities. + +![img](https://s3.amazonaws.com/rhodocs/guide/build_config/added-capabilities-in-build-yml-4.1.png) + +## RhoGallery Security Token + +To restrict access to the application you may have it built with a security token. Specify the security token in the build.yml and build the app. Apps built with a security token can be started in normal mode only if you provide this token as a parameter. +If you do not specify the correct security token in the start params, the app will close on start by default. If you want do something instead of exit (for example show special message or run application in limited mode etc.) you can define another start_path for your application in "rhoconfig.txt": + + :::term + invalid_security_token_start_path = '/app/InvalidSecurityTokenStartPage' + +Specify security token in build.yml: + + :::yml + security_token: 123 + +Run application with special parameter: + + :::ruby + System::run_app( 'app_name', "security_token=123" ) + +## Rhobuild.yml Configuration +After installing the RhoMobile Suite, you must tell the software where you have certain files on your machine. To do this, a file called `rhobuild.yml` is built that contains those file locations and other settings. The default version of the file is shown below: + + :::yaml + env: + paths: + java: "C:/Program Files/Java/jdk1.6.0_11/bin" + android: "C:/Android/sdk" + android-ndk: "C:/Android/ndk" + cabwiz: "C:/Program Files (x86)/Windows Mobile 6 SDK/Tools/CabWiz" + msbuild: "C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe" + vcbuild: "C:/Program Files (x86)/Microsoft Visual Studio 9.0/VC/vcpackages/vcbuild.exe" + build: + wmpath: "platform/wm" + wp8path: "platform/wp8" + androidpath: "platform/android" + iphonepath: "platform/iphone" + android: + excludedirs: + all: + # Google API key obtained from http://code.google.com/intl/en/android/add-ons/google-apis/mapkey.html + #apikey: "GOOGLE-API-KEY-FOR-ANDROID" + # This is version of Android platform used to run emulator. If not specified, latest available will be used. + #version: 1.6 + # This enable/disable native geo mapping for Android. Disabled by default + #mapping: yes + # Here data for production certificate located. If file pointed by certificate: does not exist, it will be auto-generated + #production: + # certificate: /path/to/developer/certificate + # password: "password-for-certificate" + # alias: "certificate-alias" + - "**/.*.swo" + - "**/.*.swn" + - "**/.DS_Store" + +### Rhobuild.yml Properties +* **env** - Environment settings. + * **paths** - Paths to necessary build tools. + * **java** - The path to your Java's binary folder. + * **android** - The path to your Android SDK. + * **android-ndk** - The path to your Android NDK. + * **cabwiz** - The path to your Windows Mobile 6 cabwiz file. + * **msbuild** - The path to MSBuild.exe. + * **vcbuild** - The path to vcbuild.exe. + * **build** - This is where the binaries will be stored once they are built for each specified platform. + * **wmpath** - Windows Mobile .cab file path. + * **wp8path** - Windows Phone 8 executable file path. + * **androidpath** - Android .apk file path. + * **iphonepath** - iOS .ipa file path. + * **android** - Settings specific to Android builds. + * **excludedirs** - Directories to exclude from the build. + * **apikey** - Google API key. + * **version** - The version of the Android platform to run in the emulator. If not specified, latest will be used. + * **mapping** - This enable/disable native geo mapping for Android. Disabled by default. + * **production** - Settings used in production builds. + * **certificates** - The path to your developer certificate. + * **password*** - Your developer certificate password. + * **alias** - Your certificate alias. + +### Modifying rhobuild.yml settings +To modify these settings, there are two methods: + +1. Modify these settings in the properties of RhoStudio. +2. Modify the rhobuild.yml file directly. + * On Mac OS X, the file resides in `\rhodes\` + * On Windows, the file resides in `\RhoMobileSuite` + diff --git a/docs/en/5.5/guide/build_ios.md b/docs/en/5.5/guide/build_ios.md new file mode 100644 index 00000000..b3a712d3 --- /dev/null +++ b/docs/en/5.5/guide/build_ios.md @@ -0,0 +1,444 @@ +# Building for iOS +## Setup +Follow the instructions for [setting up the development environment](nativesdksetup#setup-for-ios) for building iOS applications. + +### Building Remotely +Alternatively, you can create the device builds remotely with RhoMobile hosted builds. Refer to our [remote build guide](../../hosted/guide/remote-build-guide) for more info. + +### SDK locations +The iOS SDK that is specified in your build.yml will need to be in the default XCode folder or the build process will not be able to find it. + +Example: + + :::yml + iphone: + SDK: iphoneos7.0 +or + + :::yml + iphone: + SDK: iphonesimulator7.0 + +With these SDKs specified, you need to make sure the SDKs are in the right folder. To find your default XCode installation directory, you can run the command `xcode-select --print-path` in your terminal. This will return something like this: + + :::term + $ xcode-select --print-path + /Applications/Xcode.app/Contents/Developer + +This is the path that the build process will use when looking for your iOS SDKs. If you have an SDK that you will be using but, it's in another folder you'll need to move it to the appropriate folder in this directory. For Example, if I have an iphoneos6.0 SDK that I want to use but it's in my downloads folder, I'll need to move it `/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/`. + +The iphoneos and iphonesimulator SDKs go in two different folders: + +* `/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs` - iPhoneOS SDKs, for running apps on your iOS device. +* `/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs` - iPhoneSimulator SDKs, for running apps in your iOS simulator. + +> Note: These paths are solely for your information, they do not need to be copied into any files to be used. These are simply the directories in which you need to store your SDKs for them to work with the RhoMobile build process. + +## Building and Running Your iOS Application with RhoStudio + +To start the build process, create a Run Configuration: select your project in the Project Explorer, and do one of the following actions. + + * Select Run->Run Configurations... from the main menu, + * Or right-click on your project, and select Run As->Run Configurations from the popup menu. + + + +The Run Configurations window appears. + +To run on the iOS simulator, select iPhone in Platform, Simulator in Simulator type, and select iPhone or iPad. Then click the Run button. + + + +## Build an iOS App with Xcode +### Generating the XCode Project +If you wish to run your RhoMobile application on an iOS device, you need to build and run it using an Xcode project. There are two +ways to do this: + +Both from the command line: + +* run the `run:iphone` rake task + +This will create the xcode project but will also run the app in the iphone simulator. + :::term + $ rake run:iphone + +* run the `build:iphone:setup_xcode_project` rake task: + +If you want to create the XCode project without running your app in the simulator, use this command instead. + :::term + $ rake build:iphone:setup_xcode_project + + +After the app has built, it will create an XCode project and place it in your project folder in the app's root directory. e.g. `/project/iphone/.xcodeproject`. + +### Starting the Project in XCode +Then in XCode open the `/project/iphone/.xcodeproject` project. + +In the Xcode Scheme menu, select the proper scheme before you build and run your project. Click on the Scheme menu. + +xcode scheme + +Select the scheme rhorunner and what platform you would like to build to. + +xcode scheme simulator + +Now you can build and run in Xcode to run your project in the iOS simulator. + +If you are an Apple developer, you can run your RhoMobile application on your iOS device. In Xcode, select your rhorunner target, click on the Build Settings tab, and see that your code signing information that you installed as an Apple developer is set up and selected. + +You should see your app's XCode project listed in the XCode window title. In the case below, my app's name is build-ios-test and the .xcodeproject file is Buildiostest.xcodeproject. + +xcode build settings + +Plug in your iOS device. In Xcode, under Scheme, select iOS device under rhorunner, then build and run. + +xcode scheme device + +For more information on running on your iOS device from Xcode, go to the [Apple developer site](http://developer.apple.com/), go to the iOS Developer Library, and search on "managing devices", or "run applications on a device," or similar. + +You can edit your RhoMobile code for your RhoMobile application in a text editor, save your changes, do a Clean in Xcode so that your changes will register in Xcode, and then rebuild and run your project from Xcode. + +The resulting application package (*.app) is located in your RhoMobile source code folder under /platform/iphone/build/, in a folder named like [Debug/Release]-[iphoneos/iphonesimulator]/rhorunner.app. + +> Note: After any modification to the build.yml file, you'll want to regenerate the XCode project using the command `rake build:iphone:setup_xcode_project`. + +### Changing rhorunner to match your app name +By default, the scheme name, product name, and target name are "rhorunner". This is simply cosmetic at this point but you can change it if you like. To change these items: + +#### Scheme Name +Click the name rhorunner as if to change the scheme. You'll get a dropdown menu with the option "Manage schemes". Click this and you'll be presented with a list of schemes. Click the rhorunner scheme and either click it again or press the Enter key to rename it to your app's name. + +#### Product Name +In the middle pane of XCode, click the "Build Settings" option at the top. In the list of build settings you'll find the heading "Packaging" and in this section, expand the "Product Name" item. You can then click on the name "rhorunner" to change this name to you app's name. + +#### Target Name +In the middle pane of XCode, click the drawer button to expand the drawer and reveal the "Project" and "Target" items. Just as before, you can single-click the highlighted "rhorunner" item to rename it to your app's name. + +Here are the pieces that can be renamed to match your app's name: + +rhorunner renaming + +## Building and Run on devices before iPhone4 and iPad + +From XCode 4.2 on, Apple removed default support of the armv6 architecture. In this case there are two issues. + +Your distribution build should include code for both armv6 and armv7. The XCode projects included with RhoMobile and used for build RhoMobile-based applications for iOS are already fixed for this. + +If you want to build/run/debug your application on devices before iPhone4/iPad (for example, on iPhone 3G), you should manually path all your native extension xcode projects used in your application for Architecture settings. In your project, under Build Settings -> Architectures, click the Debug or Release row (depending on if you are debugging or releasing), and choose "Other". In the pop-up box, modify as follows. + +* Remove `$(ARCHS_STANDARD_32_BIT)` and replace by typing `armv6`. +* Use the plus button to add a new row. Type `armv7`. +* Click Done. + +## Building iPhone Application from the Command Line + +Unlike building the application from the Xcode GUI, when you build the application from the command line, use the rake command from the directory of the application that you had just generated with the rhodes command. + +From the command line, navigate to the folder for your RhoMobile application. + +To run your RhoMobile application in the iPhone simulator, run this rake command: + + :::term + $ rake run:iphone + +## Building the Application for the iOS Device + +After you have modified and debugged your RhoMobile application, you can prepare your application to install to your iOS device. + +### Modifying the build.yml + +First, in your application's build.yml file, change sdk to iphoneos instead of iphonesimulator, configuration to Release instead of Debug, and add information such as codesignidentity. + + iphone: + sdk: iphoneos4.3 + configuration: Release + codesignidentity: "iPhone Developer" + entitlements: "" + +### build.yml settings + +The default build.yml settings generated for iphone are: + + name: myapp + version: 1.0 + iphone: + provisionprofile: + sdk: iphonesimulator3.0 + entitlements: + codesignidentity: + configuration: Debug + emulator: 3.0 + emulatortarget: iphone + BundleIdentifier: com.yourcompany.yourapp + BundleURLScheme: yourapp + entitlements_file: "./production/Entitlements.plist" + production: + app_plist_title: "myapp" + app_plist_subtitle: "myapp" + app_plist_icon_url: "www.yourcompany.com/icon.png" + app_plist_ipa_url: "www.yourcompany.com/myapp.ipa" + ipa_itunesartwork_image: "./production/image.jpg" + + +* name: name of your application. Will show on screen (iPhone application bundle display name) +* version: version of your application. iPhone application bundle version +* provisionprofile: The UUID of your provisioning profile to use when signing. +* sdk: The version of sdk used to build. Typically iphonesimulatorX.X or iphoneosX.X +* entitlements: propertylist file for entitlements for your build. Typically is Entitlements.plist +* codesignidentity: The name of the code signing identity to use when signing for device. +* configuration: Debug/Release/Distribution +* emulator: version of emulator for run application +* emulatortarget: device family for simulator (iphone/ipad) +* BundleIdentifier: bundle identifier - used in provisioning profile +* BundleURLScheme: bundle URL scheme of your app (used for opening your application from another application by using custom URL scheme) +* entitlements_file: path of your custom Entitlements.plist (if you want use own instead of default) - you also can just put Entitlements.plist file into root folder of your application and it will be automatically used during build +* production: section used only for Ad Hoc distribution, contain some specific options for prepare .plist and *.ipa files etc. +* app_plist_title: title in plist file (application name by default) +* app_plist_subtitle: subtitle in plist file (application name by default) +* app_plist_icon_url: icon url written in plist file +* app_plist_ipa_url: IPA file url written in plist file +* ipa_itunesartwork_image: path to iTunesArtwork image included into IPA file (must be 512x512 JPG image) + + +** > Note: BundleIdentifier and BundleURLScheme can contain only next symbols : "a"-"z", "A"-"Z", "0"-"9", "-", "." ! + +Here is an example of the iPhone settings in build.yml for a finished application: + + name: JS App + version: 1.0 + iphone: + provisionprofile: E5931D39-CA68-48E4-A3AF-BB538E1C8CE6 + sdk: iphoneos4.2 + codesignidentity: "iPhone Developer: John Smith (MF99RW67WY)" + entitlements: "" + configuration: Release + emulator: 4.2 + emulatortarget: ipad + BundleIdentifier: com.johnsmithcompany.jsapp + BundleURLScheme: jsapp + +### Creating Your Application Package + +Now you can create your .app file with this rake command: + + :::term + $ rake device:iphone:production + +The package named your application name.app will be placed to `/bin/target/iOS/[sdkname]/[configuration]/[your application name].app` if you are using RhoMobile from 2.2.4 version. + +Result package named rhorunner.app will be placed to `/platform/iphone/build/[Debug/Release/Distribution]-[iphoneos/iphonesimulator]/rhorunner.app` if you are using RhoMobile before 2.2.4 version. + +## Installing Your Application Package to Your iOS Device +Use iTunes for installing your application package (your_application_name.app) to the iOS device: + +* Open iTunes. +* Under Library, select Apps. +* Drag and drop your application package into the Apps screen. +* Connect your device to iTunes. +* Under Library, select your device. +* Select the Apps tab in your iTunes device screen. +* In the Sync Apps list, check your application. +* Perform a sync. Your application is installed to your device. + +## Building the application for the Apple App Store + +After you have tested your RhoMobile application on your iOS device and tweaked it as required, you can prepare your application for publishing to the App Store. + +### Modifying the build.yml + +Update your application's `build.yml` file, change configuration to Distribution, and make sure `sdk` is set to to iphoneos and add information such as codesignidentity. + +Here is an example of the iPhone settings in build.yml for distribution: + + :::yaml + name: JS App + version: 1.0 + iphone: + provisionprofile: E5931D39-CA68-48E4-A3AF-BB538E1C8CE6 + sdk: iphoneos4.2 + codesignidentity: "iPhone Developer: John Smith (MF99RW67WY)" + entitlements: "" + configuration: Distribution + BundleIdentifier: com.johnsmithcompany.jsapp + BundleURLScheme: jsapp + +### Setting your application name, icons and loading screen + +You will need to provide a name and icon for the application that the user will see on the device. You can also customize the loading screen that is shown while your application is launching. Refer to the [Application Icon and Splash Screen](app_icon_splash) guide for detailed information. + +You must also include the following icon sizes for your app in order for it to pass App Store requirements: + +* icon57 +* icon60 +* icon76 +* icon72 +* icon114 +* icon120 +* icon144 +* icon152 +* icon180 + +In addition to these, you need to also add icons for iTunes artwork images to be shown in iTunes and the AppStore application. Rhodes now generates iOS apps with the following image files: + +* "iTunesArtwork" - 512x512 PNG +* "iTunesArtwork@2x" - 1024x1024 PNG + +Simply put your images in place of these with the same names to customize the images. + +### Turn off developer options + +Update your application's configuration files to make sure developer / debug / profile options are turned off. + +The below values can be used as a guide for `rhoconfig.txt`, skip any setting which is not already present. + + MinSeverity = 3 + LogToOutput = 0 + net_trace = 0 + log_skip_post = 0 + +The below values can be used as a guide for `build.yml`, skip any setting which is not already present. + + profiler: 0 + +### Creating your application package + +Once you have finished configuration, you can run: + + :::term + $ rake device:iphone:production + +The signed package named `[app-name].app` will be created in `/bin/target/iOS/[sdkname]/Distribution/`. + +## Publishing on the Apple App Store + +When your application is ready to be distributed to other users, either for beta testing or for deployment, you have several options: + +* Sending the application to users directly, also called Ad-Hoc distribution (for testing purposes only, some limitations apply) +* Uploading your application to the public App Store +* Distributing it under the iOS Enterprise Distribution program (for in-house use only) + +All options require you to be enrolled in one of [Apple's iOS Developer Programs](https://developer.apple.com/programs/start/ios/) and to have created signing certificates. iOS code signing and certificate management are often a stumbling block for newcomers to the platform; refer to [About App Distribution](https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/Introduction/Introduction.html) and read the instructions carefully. + +### Ad-Hoc distribution + +For application testing purposes, Apple allows you to designate up to 100 devices that will be able to install your application. When you have the devices signed up in iTunes Connect (Apple's app management portal), create a distribution certificate and ad-hoc provisioning profile. Together, these two files allow you to digitally sign your application and install it on the registered devices. + +See the section called [Beta Testing Your iOS App](http://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/TestingYouriOSApp/TestingYouriOSApp.html#//apple_ref/doc/uid/TP40012582-CH8-SW1) in Apple's documentation for the details. + + +### Getting a distribution provisioning profile + +You need a "distribution provisioning profile" to sign your application before it can be submitted to the App Store. See [Creating Store Provisioning Profiles](http://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/SubmittingYourApp/SubmittingYourApp.html#//apple_ref/doc/uid/TP40012582-CH9-SW8) for steps to create and download a distribution provisioning profile. + +### Prepare for App Review + +To ensure that your application passes the app store approval process go through the [Guidelines](https://developer.apple.com/appstore/guidelines.html) carefully. + +Many applications can benefit from using [native UI elements](native_ui_elements), like the [native tab bar](../api/NativeTabbar), to better integrate with the rest of the platform. There are plenty of [RhoMobile applications on the App Store](http://pinterest.com/motosolutions/rhomobile-apps/) available already; in general, if your application follows the [iOS Human Interface guidelines](http://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/Introduction/Introduction.html) and does not otherwise violate any App Store rule, it will be accepted. + +### Submitting your application + +When you are ready to submit your application, you can do it [using XCode](http://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/SubmittingYourApp/SubmittingYourApp.html#//apple_ref/doc/uid/TP40012582-CH9-SW20) or [using Application Loader](https://itunesconnect.apple.com/docs/UsingApplicationLoader.pdf) + +Once your application is submitted successfully you can view its review status by referring to [these](http://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/UsingiTunesConnect/UsingiTunesConnect.html#//apple_ref/doc/uid/TP40012582-CH22-SW8) steps. + +## Differences building for iOS7+ +### System Status Bar +
                                                                            +
                                                                            +

                                                                            + In iOS7, the system status bar does not have a size and does not shift the application window down, because it is transparent and always drawn over the application window. This can be an issue for older applications because the system status bar is drawn over the WebView content located at the top. +

                                                                            +

                                                                            + To resolve this issue we reserve some room at the top of the application (with a gray color fill) and shift the WebView down, as with the old status bar. In this case all applications using an SDK older that iOS7 will work without content placing/showing issues. +

                                                                            +

                                                                            + If you want to use the whole space for the WebView you can use the following special build.yml parameter which works only for applications using the iOS 7.0 S +

                                                                            +

                                                                            To enable the new iOS7 look for the status bar, simply add iphone_use_new_ios7_status_bar_style: 1 to your build.yml file. +

                                                                            +
                                                                            +
                                                                            enabled
                                                                            +
                                                                            + +
                                                                            +
                                                                            +
                                                                            +
                                                                            disabled
                                                                            +
                                                                            + +
                                                                            +
                                                                            +
                                                                            + +### Native Toolbar + +
                                                                            +
                                                                            +

                                                                            Background Color

                                                                            + iOS7's new Toolbar has a flat design. You can setup only background color and color for icons (new iOS7 feature). + Options for background color the same with old API; integer value.
                                                                            + Example for Ruby hash: `Rho::NativeToolbar.create(:buttons => toolbar, :background_color => 0xFFFF00)` +

                                                                            Icon Color

                                                                            + The new option for icon color is alos an integer value. This only works for applications using the iOS7 SDK. + Example for Ruby hash: `Rho::NativeToolbar.create(toolbar, :iOS7IconColor => 0xFFFF00)` +
                                                                            +
                                                                            +
                                                                            :background_color => 0xFFFF00
                                                                            + +
                                                                            +
                                                                            +
                                                                            :iOS7IconColor => 0xFFFF00
                                                                            + +
                                                                            +
                                                                            + +
                                                                            +
                                                                            +

                                                                            Colored Icon Flag

                                                                            + The colored icon flag is still working as it did in earlier versions RhoElements. +
                                                                            Example for Ruby hash:`toolbar = {:action => :home, :icon => '/public/images/bar/colored_btn.png', :colored_icon => true}`
                                                                            +
                                                                            +
                                                                            +
                                                                            :colored_icon => true
                                                                            + +
                                                                            +
                                                                            +
                                                                            :colored_icon => true
                                                                            + +
                                                                            +
                                                                            + +### Native Tabbar +
                                                                            +
                                                                            + iOS7's TabBar now also has a flat design. You can setup only background color and selected color for icons (new iOS7 feature). + Previous Rhodes API feature for selecting a color for each icon separately (selected_color property) is not supported when using the iOS7 SDK. +

                                                                            Background Color

                                                                            + Options for background color are the same as with the previous Rhodes API: integer value. + Example for Ruby hash:`:background_color => 0x00004F` +

                                                                            Icon Color

                                                                            + New options for selected icon color: integer value. This works only for applications usinf the iOS7 SDK. + Example for Ruby hash :`:iOS7SelectedColor => 0xFFFF00` +
                                                                            +
                                                                            +
                                                                            :background_color => 0x00004F and :iOS7SelectedColor => 0xFFFF00
                                                                            + +
                                                                            +
                                                                            + +### Loading Splash Screen +Newer iPhones (iPhone 5 and up) have larger screen (longer screen), so applications that want to use whole screen should have a special loading splash screen image - `loading-568h@2x.png` with 640 x 1136 size. Only applications with this loading image use the whole screen. Other applications that detect that the device is older that iPhone 5 should start with reduced screen size splash which is appropriate for that device, most likely equal to old phones' resolution, 640x960. + +## ARM v7 Issue + +Any RhoMobile app originally built with 4.1 and then later rebuilt with 5.1 to target Apple iPhone 5, 5C or other Apple devices that incorporate the ARM v7 instruction set, might return the error: + +"**Undefined symbols for architecture armv7 lD: symbol(s) not found for architecture armv7**" + +Although support for the ARMv7 architecture was implemented in RMS 5.1, apps built with previous versions contain incompatible components that will cause the app to fail when rebuilt. + +To solve the problem: + +* **Delete the project and bin folders** under the app folder of the project in question +* **Perform a clean build** of the app \ No newline at end of file diff --git a/docs/en/5.5/guide/build_win.md b/docs/en/5.5/guide/build_win.md new file mode 100644 index 00000000..386f52ec --- /dev/null +++ b/docs/en/5.5/guide/build_win.md @@ -0,0 +1,200 @@ +# Build for Windows + +## Introduction +This guide documents the use of Microsoft Visual Studio 2012 or 2008 to build RhoMobile apps for Windows desktop editions, including Windows XP and XP Embedded (XPE). Visual Studio is required to build apps that target 'big' Windows, and along with the RhoMobile Suite should be installed prior to starting this guide. If RhoMobile is already installed, it must be configured according to the [native SDK setup instructions](nativesdksetup#setup-for-windows-desktop) for building Windows apps. + +Building apps for Windows also relies on the Qt cross-platform application framework. As of RMS 5.3, the following Qt versions are supported: + +* **Qt 5.5.0.0** (new in RMS 5.3) +* Qt 5.1.1.0 (required for XP and XPE) + +NOTE: Qt 5.1.1.0 exhibits inconsistent behavior when a finger or stylus is used for input. + + +###Prerequisites + +* [Microsoft Visual Studio](https://www.visualstudio.com/en-us/visual-studio-homepage-vs.aspx) 2012 or 2008 +* [RhoMobile Suite 5.3](http://rhomobile.com/download/) (RMS 5.2 if targeting only Windows XP or XPE) +* RhoMobile [configured for native development](nativesdksetup#setup-for-windows-desktop) + +## Set up development host +###Step 1- Download and install Qt + +_**About Windows XP target support**: Qt 5.1.1.0 is the only Qt version supported for making RhoMobile apps with Visual Studio 2008 or 2012 that target Windows XP and XPE. Zebra has built binaries from Qt source to make them compatible with Windows XP and to support zlib, SSL, .png, .jpg, FreeType fonts, etc. These freely distributable binaries are linked against OpenSSL and implement the HTTPS protocol. If additional or different binaries are required for your app, please refer to Qt's documentation for [Configure Options](http://doc.qt.io/qt-5/configure-options.html) and [Building from Source](http://doc.qt.io/qt-5/windows-building.html)._ + +1. **Create the directory `C:\Qt\Qt5-ssl`** on the development host. +2. **Download the appropriate version of Qt**: + * **To target Windows XP/XPE with Visual Studio 2008**, [download Zebra's Qt 5.1.1.0 VS2008 binaries](http://rhomobile-suite.s3.amazonaws.com/Qt/Qt5-vs2008.7z). + * **To target Windows XP/XPE with Visual Studio 2012**, [download Zebra's Qt 5.1.1.0 VS2012 binaries](http://rhomobile-suite.s3.amazonaws.com/Qt/Qt5-rhoxp.7z). + * **To target modern Windows versions with Visual Studio 2012**, [download Qt's 5.5.0.0 binaries](http://download.qt.io/official_releases/qt/5.5/5.5.0/qt-opensource-windows-x86-msvc2012-5.5.0.exe).
                                                                            _Note: In this scenario, a separate set of Zebra OpenSSL libraries implement the HTTPS protocol, and are included automatically when performing a production build (see [Build sections](#build), below)_. +3. **Extract (or install Qt's binaries) into the directory** created in Step 1.1. + +###Step 2- Add the QTDIR System Variable + +1. On the Windows Desktop, **right-click 'Computer' and select -> Properties**. + +2. **Select 'Advanced System Settings'** in the System Properties window. + +3. **In the 'Advanced' tab, click the 'Environment Variables' button** to bring up a window similar to the one below: + + + + +4. **Click the lower 'New...' button** to create a new System Variable. (If a variable called 'QTDIR' already exists, double-click to edit it). + +5. **Enter 'QTDIR' in the Variable name field**. + +6. **Enter `C:\Qt\Qt5-ssl` in the Variable value field**. + +7. **Click 'OK' to close the dialog** and OK again to close and save the setting. + +8. **Restart the system** for changes to take effect. + +If the development host has just a single version of Visual Studio installed, skip to the [Build section](#build); the system is now ready to build. + +###Step 3- Select a Visual Studio version +If more than one version of Visual Studio is installed, the system by default will build the application using the newest supported version (2012 or 2008). To explicitly specify the version of Visual Studio to use, add an `msvc` parameter to the `win32` section of your `build.yml` and specify `2012` or `2008`: + + :::yaml + win32: + msvc: 2012 + + +The system is now ready to build with the selected Visual Studio edition. + + +## Build from the command line +###Building for Windows +To build and run the application, execute the following command: + + :::term + $ rake run:win32 + +To clean all temporary and binary files, execute the following command: + + :::term + $ rake clean:win32 + +To build an installer bundle: + + :::term + $ rake device:win32:production + +After the build process is finished you will find an installer bundle named:
                                                                            + `-setup.exe`
                                                                            + in the folder:
                                                                            + `/bin/target/win32` + +###Building for Windows XP Embedded + After the development host has been configured for Windows XP Embedded according to the [Setup section](#setup) above, use the following commands to build for XPE. To optimize the size of the XPE executable and its runtime footprint, please refer to [Minimize the target footprint](#optimize), below. + + + + +Clean out temporary and binary files by executing the following command: + + :::term + $ rake clean:winxpe + +Build an installer bundle: + + :::term + $ rake device:winxpe:production + +After the build process is finished you will find an installer bundle named:
                                                                            + `-setup.exe`
                                                                            + in the folder:
                                                                            + `/bin/target/win32` + + +##Minimize the target footprint (optional) +The size of the Windows executable can be minimized by excluding Qt and/or Visual C runtime libraries, and the target configured to execute multiple apps from a single shared instance of those DLLs. + +**Important: Optimized apps will not run on the target unless it has been configured as described this section; excluded DLLs must be installed separately on every target**. Zebra simplifies this process with a set of target runtime installers that automatically install all required Qt DLLs into a shared location and configure target path settings accordingly. Alternatively, Qt5 DLLs can be copied to a folder on the target, the path to which must be added to the `PATH` environment variable and the `QTDIR` system variable removed. + +NOTE: Zebra runtime installers include Zebra's Qt library builds, and should not be used if different Qt DLLs are required. + +###Step 1- Specify DLL exclusions + +1. **Add one or both of the boolean parameters** `deployqt` and `deploymsvc` to the `win32` section of your `build.yml` and exclude the corresponding runtimes by setting their values to 0, as below: + + + :::yaml + win32: + deployqt: 0 + deploymsvc: 0 + +2. **Rebuild the app**; the resulting executable will exclude the specified DLLs. + +###Step 2- Install RhoRuntime Qt installer +RhoRuntime Qt installers optimize memory footprint by installing a single instance of the Qt runtime libraries and define a path on the target to allow sharing of the libraries by multiple applications. + +1. **On the target(s)**, download and execute the appropriate installer: + +* **[RhoRuntime for QT 5.1.1.0 for Visual Studio 2008](http://rhomobile-suite.s3.amazonaws.com/Qt/RhoRuntimeQt5-VS2008Setup.exe)** +* **[RhoRuntime for QT 5.1.1.0 for Visual Studio 2012](http://rhomobile-suite.s3.amazonaws.com/Qt/RhoRuntimeQt5-setup.exe)** +* **[RhoRuntime for QT 5.5.0.0 for Visual Studio 2012](http://rhomobile-suite.s3.amazonaws.com/Qt/RhoRuntimeQt5.5.0.0_VS2012-Setup.exe)** (not compatible with Windows XP/XPE) + +2. **Restart the target** to activate new path settings. + +###Step 3- Install the Microsoft runtime + +[Download the Microsoft Visual C++ runtime](http://www.microsoft.com/en-sg/download/confirmation.aspx?id=5582) and install it. The installer configures the target to allow sharing of the runtime by multiple applications. + + + +## Create an app installer (optional) + +The Nullsoft Scriptable Install System (NSIS) is an open source platform for creating installation files for Windows apps. Follow these instructions to make an installer for your app: + +1. **Download and install the** [NSIS installer tool](http://nsis.sourceforge.net/Download). + +2. **Add path to the NSIS complier** in your `rhobuild.yml` file, which is in the `\rhodes` folder: + +On 32-bit platform: + + env: + paths: + nsis: C:/Program Files/NSIS/makensis.exe + +On 64-bit platform: + + env: + paths: + nsis: C:/Program Files (x86)/NSIS/makensis.exe + +### Readme, license and Icon +3. **To present a user license agreement**, place the license in a file called `LICENSE.txt` in the root of application folder. This will be displayed on separate page during installation and allows the installer to accept the license. + +4. **To present a Readme file**, place the readme text in a file called README.html in the root of application folder. It will be displayed by the installer when the installation concludes. + +For more information, please refer to the [NSIS User Guide](http://nsis.sourceforge.net/Docs/Contents.html). + +## Logging + +The application log 'Rholog.txt' is placed in `\rho` + +##Switching Qt versions +RhoMobile applications can be built only with Visual Studio 2008 or Visual Studio 2012, and only with Qt 5.1.1.0 or Qt 5.5.0.0. If after following the steps above a different version of Qt is desired, follow these steps to make the switch: + +1. Go to the Qt website and download and install the desired Qt version for Visual Studio 2008 or Visual Studio 2012. +2. Verify the Qt installation path. It should be something like: C:\Qt\\ +3. Close RhoStudio and all command-prompt windows. +4. Update or create a system variable called 'QTDIR' with the directory verified in Step 2. +5. Update the `msvc` parameter in the `Build.yml` to reflect the desired Visual Studio version, if necessary. +6. Be sure the `deployqt` and `deploymsvc` parameters in the `build.yml` both contain a value of 0. +7. Start building the application. +8. Prepare a target system for testing the newly built application (**which must not be the development host**): + 9. On the test target, install the Microsoft Visual C++ Runtime for 2008 or 2012 to coincide with the version being used for the build. + 10. Install the same Qt version on the target system as installed in Step 1, above. + 11. Add the installed Qt directory from Step 2 to the 'PATH' environment variable (use a semicolon to append to the end of the path). + 12. When the build finishes, copy the contents of `/bin/target/win32/tmp` from the development host to the `C:\` of the target. This is the newly built application. + 13. Close any command-prompt windows that might be open on the target. + 14. Double click application on the target: C:\\.exe. +15. Observe, test and explore the application with the new version of Qt. + + diff --git a/docs/en/5.5/guide/build_wm.md b/docs/en/5.5/guide/build_wm.md new file mode 100644 index 00000000..c9660242 --- /dev/null +++ b/docs/en/5.5/guide/build_wm.md @@ -0,0 +1,183 @@ +# Build for Windows Mobile +## Setup +Follow the instructions for [setting up the development environment](nativesdksetup#setup-for-windows-mobile) for building Windows Mobile applications. + +> Note: When Building for Windows Mobile or Windows CE, it is necessary that you set `app_type: "rhoelements"` in your app's build.yml file as shown [here](build_config#buildyml-file). + +## Add Paths to Cab Wizard and Visual Studio +In RhoStudio Windows -> Preferences, right-click on Rhomobile->Windows Mobile to show the rhobuild.yml preferences. Check that the Cab wizard path (which is contained in your Windows Mobile 6 SDK program installation) is correct. + + + +Also check that the vcbuild path is shown in the rhobuild.yml file. The rhobuild.yml file is located in the RhoMobile folder (example location: `C:/RhoStudio/ruby/lib/ruby/gems/1.8/gems/rhodes-3.1.1`). + + :::yaml + env: + paths: + vcbuild: C:/Program Files/Microsoft Visual Studio 9.0/VC/vcpackages/vcbuild.exe + cabwiz: C:/Program Files/Windows Mobile 6 SDK/Tools/CabWiz + +On 64-bit installations: + + :::yaml + env: + paths: + vcbuild: C:/Program Files (x86)/Microsoft Visual Studio 9.0/VC/vcpackages/vcbuild.exe + cabwiz: C:/Program Files (x86)/Windows Mobile 6 SDK/Tools/CabWiz + +## Setup target SDK and emulator +By default 'Windows Mobile 6 Professional SDK (ARMV4I)' SDK and "Windows Mobile 6 Professional Emulator" are used. To change edit build.yml: + + :::yaml + wm: + sdk: + emulator: + +* 'target_sdk' may be: + + "MC3000c50b (ARMV4I)" - for Zebra CE devices. Install MC3000c50b PSDK from [Symbol support site](http://support.symbol.com) + + "Windows Mobile 6.5.3 Professional DTK (ARMV4I)" for latest Windows Mobile SDK. + +* 'target_emulator' may be: "Windows Mobile 6.5.3 Professional VGA Emulator" for VGA emulator , or any other installed Windows Mobile emulator + +## Building and Running Your Windows Mobile Application with RhoStudio +To start the build process, create a Run Configuration: select your project in the Project Explorer, and either: + +* select Run->Run Configurations... from the main menu, +* or right-click on your project, and select Run As->Run Configurations from the pop-up menu. + + + +The Run Configurations window appears. + +> Note: In the RhoStudio Run Configurations window, when you choose the Windows Mobile platform and any of the platform types (such as 6.0, 6.5.3, CE5.0), this platform setting overrides the SDK settings for Windows Mobile in the application build.yml file. This override does NOT affect RhoMobile Production Build, or using rake (without RhoStudio) to build and run a Windows Mobile app; these options use the Windows Mobile SDK settings in the build.yml file. + +### Running on the Windows Mobile Simulator in RhoStudio +To run on the Windows Mobile simulator, select Windows Mobile in Platform and Simulator in Simulator type. Then click the Run button. + + + +### Running on a Windows Mobile Device in RhoStudio +To run on a Windows Mobile device, connect your device to your computer with a USB cable. + +In the Run Configurations window, select Windows Mobile in Platform, and Device in Simulator type. + +## Build and Run from the Command Line +On computers without RhoStudio, you can build and run from the command line. + +Navigate to your RhoMobile application directory. To build and run application on emulator, run: + + :::term + $ rake run:wm + +To build cab-file, install it, and run application on emulator, run: + + :::term + $ rake run:wm:cab + +Before you install the application on your Windows Mobile device, first connect your device via USB cable. Then check that your device is connected with ActiveSync on Windows XP or with Windows Mobile Device Center on Windows Vista or above. + +Navigate to your RhoMobile application directory. To build and run application on device, run: + + :::term + $ rake run:wm:device + +> Note: Starting in version 4.1 of RhoElements, no .cab file is generated within the project when running rake run:wm:device + +To build cab-file, install it, and run application on device, run: + + :::term + $ rake run:wm:device:cab + +After the build process completes, the device will ask you to install the app. Disconnect the USB cable from the device before you install. + +## Build application cab-file for the device + + :::term + $ rake device:wm:production + +If you want the application to be signed automatically during the build process, please add the 'wmsign' key with full path to your code signing certificate to the 'build' section of rhobuild.yml file: + + :::yaml + wmsign: + +You can find more information about Windows Mobile code signing at: +[http://msdn.microsoft.com/en-us/windowsmobile/dd569132.aspx](http://msdn.microsoft.com/en-us/windowsmobile/dd569132.aspx) + +## Deploy application on device +First, connect your device to your computer. You can use USB-cable, bluetooth or any other method. To use computer internet, start ActiveSync or Windows Mobile Device Center. + +You can use rake tasks to deploy the application. See the previous section, 'Build application from the command line.' The device should be connected via USB-cable. + +Manually copy the .cab file to the device. For example, you can use the device File Explorer to display the .cab file that is on the computer. Click on that .cab file and the installation process will be started; after it is finished, you should see the app icon on your device in Programs. + +### Allow DMA Connections +On Windows XP, open ActiveSync and open the File menu; on Windows Vista and above, open Windows Mobile Device Center and click Mobile Device Settings. + +Select Connection Settings, then select the checkbox "Allow connections to one of the following." + +Select "DMA" from the list box. DMA Connection is required to work with the Windows Mobile emulator. + +### Debugging on Windows Mobile devices connected to PC +On Windows Vista and Windows 7 the Windows Mobile Device Center (WMDC) may start automatically upon connection of the WM device. +If it is not happening, then you're lucky and most probably you wouldn't need to do anything to be able to run and debug Rhodes application on the device +while it is connected to PC. + +The problem is that WMDC locks the file system of the mobile device and prevents Rhodes application from running +(because the application usually writes data to files located within the application folder). +So if WMDC is starting when you connect the device to PC, you need to shutdown WMDC completely to be able to run Rhodes application +on Windows Mobile device. + +To shutdown WMDC open the Task Manager, find wmdc.exe (Windows Device Mobile Center) and +WmdHost.exe (Windows Mobile Device Center Sync Host) processes and end them. + +Then disconnect the device and connect it again to PC -- WMDC should not appear this time. +Now you may run and debug Rhodes applications on Windows Mobile devices connected to PC from both RhoStudio and command line. + +## Build from Visual Studio IDE +Checkout the Rhodes source code from GitHub (you have this source code already if you installed RhoStudio). + +Open `\platform\wm\rhodes.sln` in Visual Studio (example location for : `C:/RhoStudio/ruby/lib/ruby/gems/1.8/gems/rhodes-3.1.1`). + +In Visual Studio, select Windows Mobile 6 Professional and build Release configuration. + +Edit the file `rhobuild.yml` in the RhoMobile folder: + +* Check that the path to Cabwiz is defined, for example, `C:/Program Files/Windows Mobile 6 SDK/Tools/CabWiz`. +* Define the path to your application folder. + +Run + + :::term + $ rake build:wm:devrhobundle + +Make sure you cradle your emulator (menu Tools/Device Emulator Manager/Select Running Emulator/Actions/Cradle) + +Copy `rhodes.exe` and `rhobundle` (located at `\platform\wm\bin\win32\rhodes\Debug\rho`) created at the previous step to the device: `My Computer\Mobile Device` and folder in Program Files on that device (for example, `\Program Files\rhodes`). You can first delete the contents of `\Program Files\rhodes\rho` folder on your device if you want to ensure there are no old files left over. + +If you changed your application, then recompile your application code by running the following command again, and copying `rhobundle` and `rhodes.exe` again: + + :::term + $ rake build:wm:devrhobundle + +If you changed your application and built it using rake tasks, then to compile your application: + + :::term + $ rake device:wm + +Copy `\bin\target\rhodes.cab` content to `\My Documents\` on your device or the emulator, execute that .cab to install the app, and then run the installed app to see the changes. + +## Logging +To read the log file from the emulator or your device: + +* Connect to the device or emulator using ActiveSync or Windows Mobile Device Center. +* Press explore on ActiveSync window, File Management on Windows Mobile Device Center. +* Navigate to `My Device\Program Files\\rho\rholog.txt` + +## Remarks +### Cab File Will Not Install +You may encounter an issue wherein your .cab file will fail to install on Windows CE devices and presents the error message: +> The file "" is not a valid Windows Embedded Compact Setup file. + +If you receive this dialog you'll need to check the number of files located in your .cab file. The installation will fail if the number of files compressed in the .cab is more than 998 files. This is due to a limitation of .cab files on Windows CE as documented by Microsoft [here](http://support.microsoft.com/kb/839561). diff --git a/docs/en/5.5/guide/build_wp8.md b/docs/en/5.5/guide/build_wp8.md new file mode 100644 index 00000000..139d14ad --- /dev/null +++ b/docs/en/5.5/guide/build_wp8.md @@ -0,0 +1,101 @@ +# Build for Windows Phone 8 + +## Setup +Follow the instructions for [setting up the development environment](nativesdksetup#setup-for-windows-phone-8) for building Windows Phone 8 applications. + +### Building Remotely +Alternatively, you can create the device builds remotely with RhoMobile hosted builds. Refer to our [remote build guide](../../hosted/guide/remote-build-guide) for more info. + +## Application changes + +* Add a productid GUID to application build.yml . For example: + + wp: + productid: 632621d0-5ecb-012e-2c97-482a1411c191 +NOTE: When you use the `rhodes app` command to generate an application, a productid is generated automatically + +## Build and run using Rhodes gem + +* Install Rhodes gem + +* Run application simulator: + + $rake run:wp8 + +NOTE: You may use your computer keyboard with Windows Phone 8 emulator. By default it is disabled, but you can enable it pressing **PgUp** key. While it is enabled a device rotation simulation is not supported. To rotate device you need to disable keyboard support pressing **PgDown** key. Look [MSDN page](http://msdn.microsoft.com/en-us/library/ff754352(v=vs.92).aspx) for much more details on this topic. + +* Run application device: + + $rake run:wp8:device + +* See log in application folder : rholog.txt + +NOTE: When running on device you may need to disconnect USB cable from device to see log + +* After Application code modifications, run rake commands. DO NOT close simulator! + +## Build from sources +* Checkout rhodes source code from github + +## Build from IDE +### Rhodes +* Open `rhodes\platform\wp8\rhodes.sln` in VS 2013 or VS Express 2013 for Windows Phone. +* Select Debug or Release configuration, Windows Phone 8 Emulator target and build solution. +* Run emulator by pressing Start Debugging or Start Without Debugging +* After Application code modifications , build Rhodes solution and Start Debugging. DO NOT close emulator! +* See log in VS output console (Debug mode only) + +## Building the application for the Windows Phone Store + +### Setting your application name, icon and loading screen + +You will need to provide a name and icon for the application that the user will see on the device. You can also customize the loading screen that is shown while your application is launching. Refer to the [Application Icon and Splash Screen](app_icon_splash) guide for detailed information. + +### Turn off developer options + +Update your application's configuration files to make sure developer / debug / profile options are turned off. + +The below values can be used as a guide for `rhoconfig.txt`, skip any setting which is not already present. + + MinSeverity = 3 + LogToOutput = 0 + net_trace = 0 + log_skip_post = 0 + +The below values can be used as a guide for `build.yml`, skip any setting which is not already present. + + profiler: 0 + +### Creating your application package + +Once your `build.yml` is set up, you can run: + + :::term + $ rake device:wp8:production + +The compiled application .xap file will be located in `\bin\target\wp8` + +### Deploying application to Windows Phone 8 device + +To deploy application .xap file to WP8 device: + +1. Windows Phone 8 device should be [registered for development](http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769508.aspx). +2. Connect WP8 device to your development Windows 8.x PC via USB +3. On the PC go to Start screen and search for `Application Deployment` +4. Run Application Deployment tool, specify Target=Device, select your XAP file and click Deploy. + +## Publishing on Windows Phone Store + +### Getting a Windows Phone Dev Center account + +To publish your app on Windows Phone Store you need a [Dev Center account](http://dev.windowsphone.com/en-us/join). + +### Uploading and Publishing your application + +Publishing your application on Windows Phone Store is a simple two step process: + +* First [create your app info](http://msdn.microsoft.com/library/windowsphone/help/jj206733%28v=vs.105%29.aspx). This includes information like pricing, application category (business, entertainment, etc.) + +* Next [upload and describe your XAP](http://msdn.microsoft.com/en-us/library/windowsphone/help/jj206723%28v=vs.105%29.aspx). This includes details like the application description, icon and screenshots etc. + +Refer to the [official docs](http://msdn.microsoft.com/en-us/library/windowsphone/help/jj206736%28v=vs.105%29.aspx) for all details about publishing to the Windows Phone Store. diff --git a/docs/en/5.5/guide/camera.md b/docs/en/5.5/guide/camera.md new file mode 100644 index 00000000..3616cf1c --- /dev/null +++ b/docs/en/5.5/guide/camera.md @@ -0,0 +1,326 @@ +# Camera +From version 5.1 of RhoMobile Suite, you can access the device's Camera capabilities by using the [Camera API](../../latest/api/camera) + + +## Enabling The Camera API +To use the [Camera API](../../latest/api/camera), include the following extension in your `build.yml` + :::ruby + extensions: ["mediacapture"] + +After building with this extension, you will have access to the API from within your code + + + +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            + 	Rho.Camera.takePicture({}, picture_taken_callback);    	
                                                                            +	
                                                                            +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +	Rho::Camera.takePicture({}, :picture_taken_callback)
                                                                            +	
                                                                            +
                                                                            +
                                                                            + + +## Choosing the Camera +On most devices there are both front and rear facing cameras. By default, the rear camera is chosen and can be used by calling the `Rho.Camera` namespace. However, the Camera API also supports defining instances of the Camera object in a variety of different ways. This allows you greater control and flexibility in using the API. + +### Specifying By Name +One way you can ensure the use of a certain camera on a device is by naming an instance of that camera with the `getCameraByType` method: + + + +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            + 	var frontCam = Rho.Camera.getCameraByType('front');
                                                                            + 	frontCam.takePicture({}, picture_taken_callback);    	
                                                                            +	
                                                                            +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +	frontCam = Rho::Camera.getCameraByType('front');
                                                                            + 	frontCam.takePicture({}, :picture_taken_callback)
                                                                            +	
                                                                            +
                                                                            +
                                                                            + +>Note: On Windows Mobile/CE the options are `color` for the camera and `imager` for the B/W 2D Imager + +## Finding All Cameras +You can also use the `enumerate` method to identify all cameras available on the device. This method will return an array of Camera instances: + + + +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            + 	var cameras = [];
                                                                            + 	cameras = Rho.Camera.enumerate();
                                                                            +
                                                                            + 	// each object in the cameras array will be a Camera object
                                                                            + 	// and can use the properties and methods available
                                                                            +
                                                                            +	
                                                                            +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +	$cameras = Rho::Camera.enumerate
                                                                            +
                                                                            + 	# each object in the cameras array will be a Camera object
                                                                            + 	# and can use the properties and methods available
                                                                            + 	
                                                                            +	
                                                                            +
                                                                            +
                                                                            + +## Capturing a Picture +The `takePicture` method is used to capture an image and optionally pass in an options object as the first parameter that can control the behavior of the API. The second parameter shown in the example is the executed callback function: + + + +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            + 	// These properties can also be set individually on the instance
                                                                            + 	// In this example we are setting the properties when 
                                                                            + 	// executing the takePicture method
                                                                            +
                                                                            + 	Rho.Camera.takePicture({
                                                                            + 		compressionFormat : "png",
                                                                            + 		desiredWidth :1024,
                                                                            + 		desiredHeight :768,
                                                                            + 		flashMode: "on"
                                                                            + 	}, picture_taken_callback);
                                                                            +
                                                                            +	
                                                                            +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            + 	# These properties can also be set individually on the instance
                                                                            + 	# In this example we are setting the properties when 
                                                                            + 	# executing the takePicture method
                                                                            +
                                                                            + 	Rho::Camera.takePicture({
                                                                            + 		compressionFormat => "png",
                                                                            + 		desiredWidth =>1024,
                                                                            + 		desiredHeight =>768,
                                                                            + 		flashMode=> "on"
                                                                            + 	}, picture_taken_callback);
                                                                            + 	
                                                                            +	
                                                                            +
                                                                            +
                                                                            + + +### Callback Status +The callback function will always be executed and will contain an object that will have different properties depending on the result. The `status` property should always be checked to see if the call was successful or if the user canceled the action. + + + +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            +
                                                                            +    function picture_taken_callback(params){
                                                                            +
                                                                            +    	// params.status
                                                                            +    	// ok: picture was taken
                                                                            +    	// error: an error occured
                                                                            +    	// cancel: user canceled the action
                                                                            +
                                                                            +    	if(params.status =='ok'){
                                                                            +
                                                                            +    	}
                                                                            +
                                                                            +        if(params.status =='error'){
                                                                            +
                                                                            +        }
                                                                            +
                                                                            +        if(params.status =='cancel'){
                                                                            +
                                                                            +        }
                                                                            +
                                                                            +    }
                                                                            + 	
                                                                            +
                                                                            +	
                                                                            +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +    def picture_taken_callback
                                                                            +
                                                                            +    	// params.status
                                                                            +    	// ok: picture was taken
                                                                            +    	// error: an error occured
                                                                            +    	// cancel: user canceled the action
                                                                            +    	
                                                                            +    	if (@params["status"]=="ok")
                                                                            +
                                                                            +    	end
                                                                            +
                                                                            +    end
                                                                            + 	
                                                                            +	
                                                                            +
                                                                            +
                                                                            + + +### Retrieving the Image File +In the callback of the `takePicture` method, a parameter called `imageUri` will contain the location of the caputered image + + + +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            +    Rho.Camera.takePicture({},
                                                                            +    	function(params){
                                                                            +    		console.log(params.imageUri)
                                                                            +
                                                                            +    		//Ex on Android: 
                                                                            +    		// -> /data/data/com.rhomobile.rms51/rhodata/db/db-files/IMG_20150512_081051.jpg 
                                                                            +    	});
                                                                            +	
                                                                            +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +    Rho::Camera.takePicture({},
                                                                            +    	lambda{ |params|
                                                                            +    		puts(params.imageUri)
                                                                            +
                                                                            +    		//Ex on Android: 
                                                                            +    		// -> /data/data/com.rhomobile.rms51/rhodata/db/db-files/IMG_20150512_081051.jpg 
                                                                            +    	});
                                                                            + 	
                                                                            +	
                                                                            +
                                                                            +
                                                                            + +### Retrieving the Image as DataUri +In some cases, you may want to store the image as a DataURI string instead of an actual file. This is useful when the image size required is a lower resolution and you want to store it directly in a database. To accomplish this, you need to first specify the output format you would like by using the `outputFormat` property. You should specify the ouptput format before you execute the `takePicture` method. The `imageUri` paramter of the callback of the `takePicture` method will contain the dataUri string representation of the image that was captured. + + + +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            +    Rho.Camera.takePicture({
                                                                            +    		outputFormat:Rho.Camera.OUTPUT_FORMAT_DATAURI
                                                                            +    	},
                                                                            +    	function(params){
                                                                            +    		console.log(params.imageUri)
                                                                            +
                                                                            +    		// ->data:image/jpeg;base64,/9j/4WaXRXhpZgAATU0AKgAAA....
                                                                            +    	});
                                                                            +	
                                                                            +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +    Rho::Camera.takePicture({
                                                                            +    		outputFormat =>Rho::Camera.OUTPUT_FORMAT_DATAURI
                                                                            +    	},
                                                                            +    	lambda{ |params|
                                                                            +    		puts(params.imageUri)
                                                                            +
                                                                            +    		#data:image/jpeg;base64,/9j/4WaXRXhpZgAATU0AKgAAA....
                                                                            +    	});
                                                                            + 	
                                                                            +	
                                                                            +
                                                                            +
                                                                            + +### Saving to the Gallery +You can also save the image to the device's photo gallery by setting the `saveToDeviceGallery` property to `true`: + + + +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            +    Rho.Camera.takePicture({
                                                                            +    		saveToDeviceGallery:true
                                                                            +    	},
                                                                            +    	function(params){
                                                                            +    		//check status
                                                                            +    	});
                                                                            +	
                                                                            +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +    Rho::Camera.takePicture({
                                                                            +    		saveToDeviceGallery=>true
                                                                            +    	},
                                                                            +    	lambda{ |params|
                                                                            +    		
                                                                            +    		#check status
                                                                            +    	});
                                                                            + 	
                                                                            +	
                                                                            +
                                                                            +
                                                                            + +## Useful Properties + +### compressionFormat : STRING + +#### Description +The format of the captured image in subsequent calls to takePicture(). If you do not define this property when you use choose_picture with iOS, the type of image in Gallery will be recognized, and the same format will be used for saving the image to applications data. In windows and WP8 devices the format will be always jpg type. +This Property shall accept/return one among the values mentioned in constant section which starts with [COMPRESSION_FORMAT_](http://docs.rhomobile.com/en/edge/api/camera#Constants) + +#### Params +Default: jpg + +#### Access + +* Instance: This property can be accessed via an instance object of this class: + `myObject.compressionFormat` + +* Default Instance: This property can be accessed via the default instance object of this class + +Javascript: `Rho.Camera.compressionFormat` + +Ruby: `Rho::Camera.compressionFormat` + +### flashMode : STRING + +#### Description +Specifies the flash behavior when taking a picture. +This Property shall accept/return one among the values mentioned in constant section which starts with [FLASH_](http://docs.rhomobile.com/en/edge/api/camera#Constants) + +####Access + +* Instance: This property can be accessed via an instance object of this class: `myObject.flashMode` + +* Default Instance: This property can be accessed via the default instance object of this class + +Javascript: `Rho.Camera.flashMode` + +Ruby: `Rho::Camera.flashMode` \ No newline at end of file diff --git a/docs/en/5.5/guide/controlling_webview_behavior.md b/docs/en/5.5/guide/controlling_webview_behavior.md new file mode 100644 index 00000000..b5cbf7a0 --- /dev/null +++ b/docs/en/5.5/guide/controlling_webview_behavior.md @@ -0,0 +1,173 @@ +# Controlling WebView behavior +## What is WebView? +[WebView](../api/webview) is the RhoMobile component responsible for rendering your application's HTML interface, showing it to the user and allowing them to interact with the application that normally occupies most of the screen. + +At its core, WebView is a web browser, capable of making requests both to the embedded server that runs your application as well as any other server that speaks HTTP. It can execute modern JavaScript code and libraries such as JQuery and JQuery Mobile, both of which are included by default in new projects (see below for platform-specific limitations regarding JavaScript). You can expect it to support the same features as the default browser of each platform, including AJAX, hardware-accelerated rendering, cookies, etc. + +### The two types of WebView available + +There are two implementations of `WebView` available. The default implementation (`native_browser`) delegates all rendering and interaction to the native browser component provided by the operating system; that means on iOS, it will behave like Safari, on Android it uses the same engine as the browser included with the device, etc. + +The native browser in Windows Mobile, however, is too limited for today's web development standards. If you need more power than what Pocket Internet Explorer provides, there is an alternative implementation of `WebView`, developed by Zebra which you can enable in your `build.yml` file, by adding the `motorola_browser` capability. + + :::yml + capabilities: + - motorola_browser + +While the Zebra browser is also available for Android, its use is discouraged in RhoMobile 5.0 and intended only for Windows Mobile. + +> Note: Although this alternative implementation is capable of supporting modern features, performance will be limited by the underlying hardware. + +> Note: In RhoMobile 2.0 and prior, using the Zebra browser was the only way to access RhoElements (licensed) APIs from your application but, this is no longer the case. Except on Windows Mobile, all APIs, licensed or not are available in the default browser. + +## Communication between WebView and Ruby code + +A Rhodes application works very similarly to a traditional web browser + web server scenario, only with both components running on the same device. There are times, however, when it is convenient for code in one language to interact with the other; `WebView` provides ways to enable two-way communication between Ruby and JavaScript code. + +## Calling JavaScript from Ruby + +In a typical MVC scenario, once a request is received, your Ruby code will process it and end by returning a view for `WebView` to render. Instead of (or in addition to) that, Ruby code can invoke any JavaScript function present on the current page by calling `executeJavaScript`. + + :::ruby + Rho::WebView.executeJavaScript("alert('This alert was called from Ruby')") + +Any valid JavaScript code can be used in `executeJavaScript`, but if the code is built dynamically or contains expansions or data from the user, care must be taken to escape it properly. + +For example, if any of your parameters can contain newline characters (`\n`), semicolons (`;`), quotes or any other special characters, they must be escaped or the call may not work. Therefore, it is a good practice to escape all parameters being passed to JavaScript functions. + + + :::ruby + # This will not work if message contains \n + Rho::WebView.executeJavaScript("alert('#{message}')") + + # We must escape newlines for passing to JavaScript + message = message.to_json + + # Now this will work even if message contains \n + Rho::WebView.executeJavaScript("alert('#{message}')") + +You are not limited to single values, using this syntax you can also pass hashes with as many parameters as necessary. Given the following JavaScript function: + + + :::javascript + function greet_user(params) { + alert("Hello, "+params["name"]+", welcome to "+params["place"]); + } + +You would call it from Ruby by sending a hash with the appropriate keys: + + :::ruby + greeting_parameters = { + :name => 'John Doe', + :place => 'RhoMobile' + }.to_json + + Rho::WebView.executeJavaScript("greet_user(#{greeting_parameters})") + +> Note: The JavaScript code you call must have been loaded _before_ your ruby code executes. It is not enough for it to be on the same view that is going to be rendered when the action returns, it has to be already in the page, that is, it must have been included by the previous action. In practice this means that JavaScript code you intend to call from Ruby cannot be called from the same action that loads it the first time. To avoid this pitfall, you should reference JavaScript files from `layout.erb` so that the code is available at all times. Including `` + +**Copy and paste the example string (above) into the `barcode_enumerate.html` file (or the corresponding file for your app). Then copy your *actual* URL string referenced earlier and use it to replace the *example* URL. Be sure to leave the quote marks on either side of the URL**. + +>TIP: In RhoStudio, the default double-click action for an HTML file is to open its browser representation in the editor. To edit the HTML itself, right-click the file, select 'Open With' and choose 'Text Editor' as shown below. + + + +Here's what the line should look like in the HTML: + + + +###4- Start the debug client UI +**Start Weinre's debug interface by clicking the link under `Access Points` in the Weinre Console**: + + + +#### Debug Client UI + +The image below shows the 'Remote' tab of Weinre's Debug Client UI. The 'Targets' and 'Clients' sections contain one device each, and the green text indicates that both devices are communicating. + +The inset image is a screenshot from the target Android device that's being displayed by an app called [Droid@Screen](http://droid-at-screen.ribomation.com/). This useful screencasting tool uses USB and [ADB](http://developer.android.com/tools/help/adb.html) to stream screen shots to the development host. + + + +At this point, can inspect your app just as you would with the Web Inspectors of RhoSimulator or Chrome. The Elements tab shown below demonstrates two-way communication between the device and the development host. Clicking on an element in the HTML will cause that element to be highlighted on the device's UI. + + + +The Elements tab can be used for on-the-fly changes to CSS styling, API and method calls and any and all app UI settings. In the example below, the button text was changed from 'Enumerate' to 'Changed!' simply by editing the test in the Elements tab. + +
                                                                            +
                                                                            +
                                                                            +

                                                                            Button text 'Enumerate'

                                                                            + +
                                                                            +
                                                                            +

                                                                            Button text 'Changed!'

                                                                            + +
                                                                            +
                                                                            +
                                                                            + +### Issuing API calls with Console + +One of the most versatile components of Weinre is its Console. Not only does it offer classic capabilities such as device visibility and monitoring during operation, but the Weinre Console also can access all of a device's hardware fearures, issue commands and report how the device reacts. + +The example below shows results from an attempt to use the JavaScript API to check the target platform, use the camera to scan a barcode, and issue a command to the [ScreenOrientation API](http://127.0.0.1:9393/en/edge/guide/screen_orientation) (which returned an error). + + + +In the example, I used the Console to verify that my JavaScript APIs are functioning properly. A return of the correct system platform of 'Android' proves that the System API is working. A return of the correct scanned barcode value likewise proves that the Barcode module is working properly. + +>**There's another important benefit of the Weinre console.**
                                                                            +Notice that when the barcode callback handler function is executed, we are using the form `console.log(e)`, where `e` is the callback return object. That allows us to inspect the object right in the console. This simplifies validation because we see that it contains a `barcode` property and a `status` property, exactly as described in the [Barcode.take( )](../api/barcode#mtake) method description. Alternative means--such as adding code for outputting to a log, then for seaching and retrieving the information from the device--can be time consuming, tedious and error-prone. + +### Extension Inclusion + +Now we turn to the error thrown by the [ScreenOrientation](../api/screenorientation) API call: `TypeError: cannot call method 'normal' of undefined.`
                                                                            + +This indicates that it cannot find the module, and reminds us that the ScreenOrientation API is not included in RhoMobile apps by default. To include it in our build, it must be listed in the extensions section of the app's build.yml before the app is rebuilt: + + + +
                                                                            +
                                                                            +

                                                                            + Since we did not remove the target script line from the HTML, the app should connect to Weinre as soon as it is rebuilt and activated. And now that the module is included and the framework is now aware of this module, the module name will auto-complete as it's typed into the Console. And instead of returning an error, the API call will change the orientation of the screen and return what it is supposed to: VOID, which in the console is represented by a null return. +

                                                                            +

                                                                            + To determine which extensions you'll need to add to your build.yml, please see the API Summary Page in our docs and click on the API you wish to use. The resulting module page will describe what needs to be done to use any given API. +

                                                                            +
                                                                            +
                                                                            +

                                                                            Auto-Completing Code

                                                                            + +

                                                                            Extension Working properly

                                                                            + +
                                                                            +
                                                                            + + + + + +## On-Device Debugging With Chrome + +If you're building an Android app and have a device with Android KitKat 4.4 or higher, [Google Remote Debugging](https://developer.chrome.com/devtools/docs/remote-debugging) is an alternative to Weinre that's a bit easier to install and offers some fine visuals for testing, debugging and fine-tuning your app while it's running on the device. + +Google Remote Debugging works with native Android apps that use WebView--such as those built with RhoMobile--as well as purely browser-based apps. It includes live screencasting from the remote unit to the development host, and supports port forwarding and virtual host mapping in case your device needs to access a development server. + +###Requirements + +* Mac OS X or Windows development host +* Chrome 32 or later installed +* A USB cable for connecting the target to the dev. host +* A target device running Android 4.4 (KitKat) or later +* USB debugging enabled on target +* An app configured for WebView debugging + +###1. Enable Device Debugging +The target device must have USB debugging enabled. This feature is found in **Settings >> Developer Options** panel, which is hidden by default. + +![Developer Options](http://rhodocs.s3.amazonaws.com/guide/debugging_js/Android_developerOptions.png) + +Here's how to **unhide Developer options** (if neccessary) **and enable USB debugging**: + +1. Go to **Settings >> About Phone** +2. **Go to the 'Build Number' box** (by scrolling all the way to the bottom) +3. **Tap the Build Number box seven times** +4. Then, go back to Settings and **tap Developer Options** +5. **Enable USB Debugging** by checking its box + +###2. Discover Device (in Desktop Chrome) +If you haven't already done so, **connect your device to an available USB port on the development host** and **enable device detection in Chrome**: + +>![Developer Options](http://rhodocs.s3.amazonaws.com/guide/debugging_js/Chrome_detect_USB.png) + +1. Open a browser window and **enter 'chrome://inspect'** in the address bar. You should see a screen similar the one above. + +2. **Check the 'Discover USB Devices' checkbox**. Your mobile device should appear along with an alert on the device. + +3. **Tap OK on the device** to complete the connection + +4. Linux- and Mac-based developers can skip to the next step. **Developers on Windows must install a USB driver** to make a USB-attached Android device visible. Visit [Google's USB Driver page](http://developer.android.com/tools/extras/oem-usb.html) for instructions and links to OEM drivers for your brand of hardware. + +5. The final step is to **configure WebView for debugging**, which must be done from within the app. Fortunately, RhoMobile developers can skip this step too because the WebView components used by the RhoMobile Suite are automatically configured for debugging when deployed to devices with debug mode enabled. + +6. At this point you should be ready to begin debugging. Once your app is deployed and running on the device, the chrome://inspect page should look something like the one shown below, with your device and a link to its debug-enabled WebViews. **To begin debugging, click an inspect link.** + +
                                                                            + +## Running RhoSimulator From the Command Line + + RhoSimulator can be executed from the command line and thereby integrated with your favorite IDE or inspected with alternative tools. To run RhoSimulator from the command line, use one of the following platform-specific commands from within the folder containing the app to be simulated: + +* Android + + rake run:android:rhosimulator + +* iOS + + rake run:iphone:rhosimulator + +* Windows Phone 8 + + rake run:wp8:rhosimulator + +* Windows Mobile + + rake run:wm:rhosimulator + +* Windows (desktop) + + rake run:win32:rhosimulator + + diff --git a/docs/en/5.5/guide/debugging_ruby.md b/docs/en/5.5/guide/debugging_ruby.md new file mode 100644 index 00000000..9fdee47e --- /dev/null +++ b/docs/en/5.5/guide/debugging_ruby.md @@ -0,0 +1,71 @@ +# Debugging Ruby +## Starting a debug session +Before debugging any RhoMobile app using RhoStudio, you must first make sure your app is setup to run in a debug session. + +Ensure that your application is configured properly and successfully runs in [RhoSimulator from the command line](#running-rhosimulator-from-command-line) + +* In RhoStudio, select your RhoMobile project from the Project Explorer. +* Select 'Run' -> 'Debug Configurations' from the main menu. The Debug Configurations window appears. +* Find 'RhoMobile Application' section on the left and add new (or modify existing) configuration. + +## Debugging Ruby with RhoSimulator +To use RhoSimulator along with RhoStudio debugger to debug the Ruby code in your RhoMobile application: + +* Select the required platform. +* Select "RhoSimulator" for simulator type to debug using RhoSimulator. +* Click 'Debug' to start the debugger. + +![RhoSimulator Debug Configuration](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/debug-configuration.png) + +RhoStudio will, by default, switch to the 'Debug' perspective, and it will establish a connection with RhoSimulator so that you can: + +* Set breakpoints. +* Step through code. +* Inspect variables when the application is stopped at a breakpoint in the Variables window. +* View log messages in the Console window. + +![RhoSimulator Debugging](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/rhostudio-debug-ruby.png) + +> Note: As the name implies, RhoSimulator *simulates* not *emulates* different platforms. The RhoSimulator uses QT Webkit internally to render the view portion of your application. Whilst the view will be a very close approximation to how your application will appear on your device please bear in mind that different rendering engines will render pages slightly differently, depending on the actual page content. For example, on Android we use the stock Webview control (Webkit or Blink, depending on the Android version) and on Windows Mobile / CE we use our custom developed Webkit based rendering engine. The use of RhoSimulator is encouraged for testing and debugging, but you still need to test on a physical device (or, at the very least, the platform's native *emulator*) to make sure your application behaves as you expect + +## Debugging an App on an Android Device +To use RhoStudio to debug a RhoMobile application running on your Android device you'll want to make sure that your computer can "see" your android device using the adb command. So make sure your device's USB debugging is on and run the adb command in your terminal or command prompt and confirm that your device shows up. Once you have ensured that your computer recognizes your device, follow these steps: + +***NOTE: The device also needs to be on the same WiFi as the build machine. In the case where the build machine is connected to multiple networks, you may also need to put a parameter in your `rhoconfig.txt` : `debughosturl='your build machine ip address'`*** + +* Select "Android" for the platform. +* Select "Device" for simulator type to debug on your device using RhoSimulator. +* Click 'Debug' to start the debugger. + +![Android Device Debug Configuration](https://s3.amazonaws.com/rhodocs/guide/debugging_ruby/android_device_debug_config.png) + +RhoStudio will, by default, switch to the 'Debug' perspective, and it will establish a connection with RhoSimulator so that you can: + +* Set breakpoints. +* Step through code. +* Inspect variables when the application is stopped at a breakpoint in the Variables window. +* View log messages in the Console window. + +This is what you will see once you start to debug your app. + +![Debugging Android Device](https://s3.amazonaws.com/rhodocs/guide/debugging_ruby/debug_android_device.png) + +## Debug an App in the iOS Emulator +To use RhoStudio to debug a RhoMobile application running on your Android device: + +* Select "iPhone" for the platform. +* Select "Simulator" for simulator type to debug in the iOS emulator using RhoSimulator. +* Click 'Debug' to start the debugger. + +![Android Device Debug Configuration](https://s3.amazonaws.com/rhodocs/guide/debugging_ruby/ios_emulator_debug_config.png) + +RhoStudio will, by default, switch to the 'Debug' perspective, and it will establish a connection with RhoSimulator so that you can: + +* Set breakpoints. +* Step through code. +* Inspect variables when the application is stopped at a breakpoint in the Variables window. +* View log messages in the Console window. + +This is what you will see once you start to debug your app. + +![Debugging iOS Emulator](https://s3.amazonaws.com/rhodocs/guide/debugging_ruby/debug_ios_emulator.png) \ No newline at end of file diff --git a/docs/en/5.5/guide/devenvironment.md b/docs/en/5.5/guide/devenvironment.md new file mode 100644 index 00000000..0a1e8404 --- /dev/null +++ b/docs/en/5.5/guide/devenvironment.md @@ -0,0 +1,28 @@ +# Developer Environments + +RhoStudio is a complete integrated development environment (IDE) that includes a code editor, debugger, simulator and tools for building platform-specific runtimes. The RhoMobile Suite centers around the Rhodes open-source framework for building cross-platform apps. + +Rhodes-based projects can be created in several ways: From within RhoStudio (an Eclipse-based environment included with the [RhoMobile Suite installation](rhomobile-install)), from within Visual Studio or another IDE of your choosing, from a command line, or in the cloud. Under the hood, RhoStudio invokes the Rhodes command-line tools anyway, so those approaches are equivalent. + +## Developing with RhoStudio +RhoStudio includes everything needed to build *hybrid* apps for Android, iOS and Windows Mobile/CE from start to finish. To build *native* applications locally for one or more specific mobile platforms, the developer also must [install native SDK(s)](nativesdksetup) on the development host for each mobile platform to be targeted. Once these have been set up and linked to RhoStudio, the build process takes place completely within RhoStudio. + +>NOTE: For Android builds, please install an Android SDK with API level 22 or lower. RhoMobile 5.2.2 will build successfully with Android versions up to and including Android 5.1 (Android L). For more information, please visit the [Android API documentation](http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels). + + +Since it's based on the extensible Eclipse framework, the RhoStudio IDE permits developers to customize and enhance its functionality by adding their own Eclipse plug-ins. The web contains plenty of documentation for building Eclipse Plug-ins. The Eclipse Foundation's [Creating a Plug-in Project](http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.rse.doc.isv%2Fguide%2Ftutorial%2FpdeProject.html) is a good a place to start. + +## Developing with Visual Studio +A [Visual Studio plug-in](visualstudio) is available that allows developers to build RhoMobile applications that target devices running Windows Phone 8. The plug-in permits Visual Studio developers to generate the application structure, construct data models, edit all code, and build, deploy and run the apps. + +## Using Other IDEs and Editors +RhoMobile applications use HTML and CSS code for the user interface layer, and JavaScript and/or Ruby for adding functionality and accessing device hardware. Any text editor or IDE can be used to create and maintain a RhoMobile app's code files. As applicable, some of those same tools also can be used to execute RhoMobile's command line options to build, deploy and run apps or conduct application scaffolding activities. + +For more information about accessing RhoMobile's command line options with alternative toolsets, please refer to the guide on [Developing Without RhoStudio](nonrhostudio). + +## Building in the cloud +[RhoMobile Remote Build](../../hosted/guide/remote-build-guide) (formerly known as RhoHub) provides a cloud-based method of building and packaging apps from code generated on a local development host. This can be useful if, for example, you'd like to build an app that runs natively on an Apple iPad or iPhone but your organization doesn't have any Macs. Remote Build provides a hosted environment for all supported native SDKs, including Android, iOS and Windows Mobile, and removes the need to install and maintain those SDKs on your orginization's local development hosts. + +Remote Build is accessed with a single click from within RhoStudio, a single command at the commamnd line or directly at [rhomobile.com](http://www.rhomobile.com). The hosted tool is integrated with GitHub, and works easily with third-party code editors; simply push code changes to your organization's GitHub repository and let Remote Build do the rest. + +To learn more about how to set up and use Zebra's hosted built tools, and about its several limitations, please visit the [RhoMobile Remote Build Guide](../../hosted/guide/remote-build-guide). \ No newline at end of file diff --git a/docs/en/5.5/guide/device_hardware_key_handling.md b/docs/en/5.5/guide/device_hardware_key_handling.md new file mode 100644 index 00000000..9ac3cb8c --- /dev/null +++ b/docs/en/5.5/guide/device_hardware_key_handling.md @@ -0,0 +1,156 @@ +# Device Hardware Key Handling + +**NOTE: This guide covers the keyboard backlight and other notification capabilities such as vibration and LEDs. If you are looking for information on capturing or recognizing keypresses, look at [KeyCapture API](../api/keycapture)** + +## Notification + +### What is a Notification + +A [Notification](../api/Notification) is the means of informing the user that some event has occurred that requires their attention. For example, it could be the arrival of an Email/SMS or an alarm clock going off. A notification could be in the form of a popup, a sound played over the device speaker, using a hardware capability of the device (i.e., vibration) or a combination of these. + +### The types of Notification + +#### Audio file + +You can playback an MP3 or WAV audio file if the device supports it. + +Ruby syntax: + :::ruby + Rho::Notification.playFile('/sdcard/media/ringtone.mp3') + +JavaScript syntax: + :::javascript + Rho.Notification.playFile("/sdcard/media/ringtone.mp3"); + +#### Beep + +If the device is equipped with a hardware beeper, it can be made to sound at a specified frequency, volume and duration + +Ruby syntax: + :::ruby + Rho::Notification.beep({ :frequency => 4000, :volume => 3, :duration => 1000 }) + +JavaScript syntax: + :::javascript + Rho.Notification.beep({ frequency: 4000, volume: 3, duration: 1000 }); + +#### Vibrate + +The device can be made to vibrate for a specified duration + +Ruby syntax: + :::ruby + Rho::Notification.vibrate(1000) + +JavaScript syntax: + :::javascript + Rho.Notification.vibrate(1000); + +#### LED + +A device might have one or more LEDs on it; these can be controlled with the [LED](../api/Notification.Led) API + +##### LED On/Off + +A LED on the device can be turned "On" or "Off" as required + +Ruby syntax: + :::ruby + # get the list of LEDs available on the device + leds = Rho::Notification::Led.enumerate + + # turn one of the LEDs on + led = leds[0] + led.illuminate + +JavaScript syntax: + :::javascript + // get the list of LEDs available on the device + var leds = Rho.Notification.Led.enumerate(); + + // turn one of the LEDs on + var led = leds[0]; + led.illuminate(); + +##### LED Flashing + +A LED on the device can be made to cycle "On" and "Off" a specified number of times + +Ruby syntax: + :::ruby + # get the list of LEDs available on the device + leds = Rho::Notification::Led.enumerate + + # flash one of the LEDs + leds[0].flash({ :onDuration => 1000, :offDuration => 500, :numberOfCycles => 10 }) + +JavaScript syntax: + :::javascript + // get the list of LEDs available on the device + var leds = Rho.Notification.Led.enumerate(); + + // flash one of the LEDs + leds[0].flash({ onDuration: 1000, offDuration: 500, numberOfCycles: 10 }); + +#### Popup + +You can bring the application to the foreground and show a message in a popup window. The message can be passed as a string or a hash. The popup window closes after you click on the button or you can close it by using the `hidePopup` method + +Ruby syntax: + :::ruby + # simple message string + Rho::Notification.showPopup("Hello!") + + # custom tite and icon with the message string + Rho::Notification.showPopup({ :title => "Greeting", :message => "Hello!", :icon => "/sdcard/images/icon.png" }) + + # hide the current popup + Rho::Notification.hidePopup() + +JavaScript syntax: + :::javascript + // simple message string + Rho.Notification.showPopup("Hello!"); + + // custom tite and icon with the message string + Rho.Notification.showPopup({ title: "Greeting", message: "Hello!", icon: "/sdcard/images/icon.png" }); + + // hide the current popup + Rho.Notification.hidePopup(); + +#### Status message + +You can display a window containing a status message. The window closes after the user clicks on its hide button. + +Ruby syntax: + :::ruby + Rho::Notification.showStatus("The Title", "This is the status message", "Close") + +JavaScript syntax: + :::javascript + Rho.Notification.showStatus("The Title", "This is the status message", "Close"); + +### Example scenarios for using Notification + +Your approach to notifications should correspond to the importance of the event you are notifying. For example, an incoming e-mail may be well served with a single beep or vibration, while a pager alert may have a high severity and warrant periodic notifications until the user acknowledges the message. Here are some high-level guidelines, make sure to adapt them to your situation: + +#### In an email/messaging/newsfeed/twitter or similar type of application + +* Use the `Beep` and/or `Vibrate` only once for notifying the user immediately on the arrival of a new message. +* Use a flashing `LED` to serve as a reminder to the user about the message after the initial `Beep`/`Vibrate` notification till the user views/acknowledges the message. + +#### Alarm clock or countdown timer + +* Use a long `Beep` and/or `Vibrate` till user stops/cancels the alarm/timer. + +### Best practices + +* `Popup` notifications can be annoying to the user if used frequently. Try not to interrupt the user's operational flow if you can help it. +* The `Beep` and `Vibrate` notifications can be annoying to the user and others around them if used frequently or for prolonged durations but for that same reason, they can be very effective if the message deserves it. +* `LED` notification can be made to blink for a reasonably long time (even hours after the event initially happens) with little disturbance. They are very popular for information that is good to know but does not require immediate action. + + +## Related reading + +* The [Notification API reference](../api/Notification) has all the details on the parameters applicable to each notification type. +* The [LED Notification API reference](../api/Notification.Led) contains the documentation about using device LEDs. diff --git a/docs/en/5.5/guide/device_information_and_abilities.md b/docs/en/5.5/guide/device_information_and_abilities.md new file mode 100644 index 00000000..0f3bfa6f --- /dev/null +++ b/docs/en/5.5/guide/device_information_and_abilities.md @@ -0,0 +1,343 @@ +# Device information and abilities + +When creating applications that need to run on a varied range of device hardware and software versions, you might want to enable or disable features based on the presence of certain abilities in the device. You can do that by making use of the [System API](../api/system) to query for device information and various capabilities + +## Platform and version + +Your RhoMobile application can run without modifications on multiple platforms, but you may still want to add some platform specific enhancements or have to interact with the OS directly for certain functionality. In these circumstances, you can check which platform the application is running on and act accordingly. + +Ruby syntax: + :::ruby + platform = Rho::System.platform + +JavaScript syntax: + :::javascript + var platform = Rho.System.platform; + +The platform can be one of the following string values: + + +* WINDOWS +* ANDROID +* APPLE +* WP8 +* WINDOWS_DESKTOP + +In addition to getting the platform, it is also possible to retrieve the Operating System version. For example, you can get back version strings like ‘5.0’ (iPhone), ‘2.2’ (Android) + +Ruby syntax: + :::ruby + os_version = Rho::System.osVersion + +JavaScript syntax: + :::javascript + var os_version = Rho.System.osVersion; + +## Screen information + +### Touch screen + +If the application is running on a touch screen device, you can selectively activate some features or show some UI elements (for example: buttons). + +Ruby syntax: + :::ruby + touch_screen = Rho::System.hasTouchscreen + if touch_screen + # show some buttons for the user to directly trigger some actions + end + +JavaScript syntax: + :::javascript + var touch_screen = Rho.System.hasTouchscreen; + if (touch_screen) { + // show some buttons for the user to directly trigger some actions + } + +### Screen dimensions + +The size of the device screen is typically used to customize the application UI for a better user experience instead of a fixed one-size-fits-all approach. Knowing the screen width and height can also be useful when using the [Keystate](../api/keystate) and [Battery](../api/battery) APIs, which can set a visible icon on the screen at a particular position. CSS media queries can often result in a more maintainable solution than manually altering the UI in code, but the capability is there if you need it. + +There are two sets of sizes for a device screen: + +* logical pixels size - use this measure for setting coordinates on screen +* real pixels size - actual number of pixels in the screen + +Ruby syntax: + :::ruby + screen_width = Rho::System.screenWidth + screen_height = Rho::System.screenHeight + real_screen_width = Rho::System.realScreenWidth + real_screen_height = Rho::System.realScreenHeight + +JavaScript syntax: + :::javascript + var screen_width = Rho.System.screenWidth; + var screen_height = Rho.System.screenHeight; + var real_screen_width = Rho.System.realScreenWidth; + var real_screen_height = Rho.System.realScreenHeight; + +It is also possible to calculate the physical size of the screen by querying for the PPI (Pixels Per Inch) value. + +Ruby syntax: + :::ruby + real_screen_width = Rho::System.realScreenWidth + real_screen_height = Rho::System.realScreenHeight + physical_screen_width = real_screen_width / Rho::System.ppiY + physical_screen_height = real_screen_height / Rho::System.ppiX + +JavaScript syntax: + :::javascript + var real_screen_width = Rho.System.realScreenWidth; + var real_screen_height = Rho.System.realScreenHeight; + var physical_screen_width = real_screen_width / Rho.System.ppiY; + var physical_screen_height = real_screen_height / Rho.System.ppiX; + +### Screen orientation + +The orientation of the device screen can be used to change the UI layout programmatically (although it is also possible to use CSS media queries to do this) + +The platform can be one of the following strings: + +* portrait +* landscape + +Ruby syntax: + :::ruby + screen_orientation = Rho::System.screenOrientation + +JavaScript syntax: + :::javascript + var screen_orientation = Rho.System.screenOrientation; + +### Screen auto rotate + +You can check if auto rotation is enabled on the device. + +Ruby syntax: + :::ruby + auto_rotate = Rho::System.screenAutoRotate + +JavaScript syntax: + :::javascript + var auto_rotate = Rho.System.screenAutoRotate; + +## Device Identification + +There are certain properties of the device that your application can use to uniquely identify the device even across reinstalls. + +* phoneId – returns hardware based id. It depends on capabilities configured for an application and has to remain same even across application uninstall/install. +* deviceOwnerEmail – primary email of phone owner (works only on Android) +* deviceOwnerName – name(account name) of phone owner (works only on Android) + +Ruby syntax: + :::ruby + phone_id = Rho::System.phoneId + device_owner_email = Rho::System.deviceOwnerEmail + device_owner_name = Rho::System.deviceOwnerName + +JavaScript syntax: + :::javascript + var phone_id = Rho.System.phoneId; + var device_owner_email = Rho.System.deviceOwnerEmail; + var device_owner_name = Rho.System.deviceOwnerName; + +## Detecting the presence of hardware features + +### Camera + +If you want to detect the presence of a camera, your application needs to enable the `camera` capability. Do this by adding that capability to the build.yml file: + + :::yaml + capabilities: + - camera + +Then you can check if the device has a camera: + +Ruby syntax: + :::ruby + has_camera = Rho::System.hasCamera + if has_camera + # do something with camera + end + +JavaScript syntax: + :::javascript + var has_camera = Rho.System.hasCamera; + if (has_camera) { + // do something with camera + } + +### Cell network / Wifi + +The device running your application may be offline or connected to a cellular, Wifi or other network. You can query the network status by using the [Network API](../api/Network) + +Ruby syntax: + :::ruby + has_network = Rho::Network.hasNetwork + if has_network + has_cell_network = Rho::Network.hasCellNetwork + has_wifi_network = Rho::Network.hasWifiNetwork + end + +JavaScript syntax: + :::javascript + var has_network = Rho.Network.hasNetwork; + if (has_network) { + var has_cell_network = Rho.Network.hasCellNetwork; + var has_wifi_network = Rho.Network.hasWifiNetwork; + } + +### Sensors + +The device might provide sensors from the types listed below: + +* accelerometer +* tilt angle +* device orientation +* motion +* eCompass +* mangetometer +* gyroscope +* ambient light +* proximity +* proximity long range +* pressure +* temperature +* humidity +* gravity +* linear acceleration +* rotation +* orientation + +To check if a particular sensor is supported by the device, try creating an instance of the sensor using the [Sensor API](../api/sensor); if the sensor exists in the device, the return value will not be `nil`. + +For example: + +Ruby syntax: + :::ruby + + sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_ACCELEROMETER) + if sensor != nil + # do something with the sensor + + sensor.stop + end + +JavaScript syntax: + + var sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_ACCELEROMETER); + if (sensor) { + // do something with the sensor + + sensor.stop(); + } + +### Barcode + +You can use the camera or dedicated barcode scanner in the device to scan barcodes. + +In order to use this API you must include the following extension in your `build.yml` + :::ruby + extensions: ["barcode"] + +The `barcode` extension is also included automatically if you specify the following in your `build.yml` + :::ruby + app_type: "rhoelements" + +Then you can use the [Barcode API](../api/barcode) `enumerate` method to get a list of barcode scanners on the device + +Ruby syntax: + :::ruby + Rho::Barcode.enumerate(url_for(:action => :enumerate_callback)) + +JavaScript syntax: + :::javascript + Rho.Barcode.enumerate(enumerate_callback) + +### CardReader + +RhoMobile supports integrated and add-on magnetic stipe card readers on Zebra Technologies devices. The [CardReader API](../api/cardreader) `enumerate` method allows you to get a list of the available card readers. + +Ruby syntax: + :::ruby + Rho::CardReader.enumerate(url_for(:action => :enumerate_callback)) + +JavaScript syntax: + :::javascript + Rho.CardReader.enumerate(enumerate_callback) + +### Bluetooth + +Bluetooth allows you to create short-range wireless connections between the device your application is running on and another bluetooth enabled device like phone, tablet, PC, or external Bluetooth device (for example external Bluetooth GPS device). + +To access bluetooth functions in your application, you need to enable the bluetooth capability in your build.yml file: + + :::yaml + capabilities: + - bluetooth + +Then you can use the [BluetoothManager API](../rhodesapi/bluetoothmanager-api) `is_bluetooth_available` method to check if Bluetooth is available on the device + +Ruby syntax: + :::ruby + Rho::BluetoothManager.is_bluetooth_available + +JavaScript syntax: + :::javascript + Rho.BluetoothManager.is_bluetooth_available() + +**NOTE: on iOS, Bluetooth connectivity is only allowed with another device also running iOS or an accessory that has been officially approved by Apple** + +### Zebra Device + +You can check if the device running the application is a Zebra device which has additional device capabilities such as hardware barcode scanner, magnetic stripe reader, etc. + +Ruby syntax: + :::ruby + is_motorola_device = Rho::System.isMotorolaDevice + if is_motorola_device + # do something with Zebra device specific capabilities + end + +JavaScript syntax: + :::javascript + var is_motorola_device = Rho.System.isMotorolaDevice; + if (is_motorola_device) { + // do something with Zebra device specific capabilities + } + +### RhoSimulator + +You can check if the application is running on the RhoSimulator and enable certain code during developement (for example, you can show extra alerts to help with debugging only inside the simulator but not on a real device or avoid showing a login screen). + +Ruby syntax: + :::ruby + is_rho_simulator = Rho::System.isRhoSimulator + if is_rho_simulator + # do something special for the simulator + end + +JavaScript syntax: + :::javascript + var is_rho_simulator = Rho.System.isRhoSimulator; + if (is_rho_simulator) { + // do something special for the simulator + } + +### Emulator + +It is also possible to check if the application is running on the platform emulator. + +Ruby syntax: + :::ruby + is_emulator = Rho::System.isEmulator + if is_emulator + # do something special for the emulator + end + +JavaScript syntax: + :::javascript + var is_emulator = Rho.System.isEmulator; + if (is_emulator) { + // do something special for the emulator + } diff --git a/docs/en/5.5/guide/device_sensors.md b/docs/en/5.5/guide/device_sensors.md new file mode 100644 index 00000000..22be8c89 --- /dev/null +++ b/docs/en/5.5/guide/device_sensors.md @@ -0,0 +1,1607 @@ +# Device Sensors + +## Prerequisite + +Before you can make use of any sensors on the device, you need to include the `sensor` extension in your `build.yml` + + :::yaml + extensions: ["sensor"] + +## General procedure + +The `Sensor` API supports many different types of sensors but, irrespective of the type, there is a common sequence of steps that you must follow in your code. + +### Create a sensor instance + +To retrieve values from a sensor, first you must create an instance of the sensor by using `makeSensorByType` passing it the sensor type as parameter + +Ruby syntax: + :::ruby + # create an instance of an accelerometer sensor + sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_ACCELEROMETER) + if @sensor != nil + # start data collection + else + # the sensor is not present, show error message + end + +JavaScript syntax: + :::javascript + // create an instance of an accelerometer sensor + var sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_ACCELEROMETER); + if (sensor != null) { + // start data collection + } else { + // the sensor is not present, show error message + } + +### Reading the sensor data periodically + +#### Setting sensor time period + +Set `minimumGap` to the minimum amount of time (specified in milliseconds) between two sensor update events. + +Ruby syntax: + :::ruby + # set to 500 milliseconds + sensor.minimumGap = 500 + +JavaScript syntax: + :::javascript + // set to 500 milliseconds + sensor.minimumGap = 500; + +#### Start data collection + +Call `start` on the instance returned from `makeSensorByType` to initiate data retrieval. + +Your callback method will be invoked with a `hash` containing several [sensor callback parameters](http://edgedocs.rhomobile.com/api/sensor#mstart). + +Ruby syntax: + :::ruby + sensor.start(url_for(:action => :my_sensor_callback)) + + def my_sensor_callback + # @params["status"] contains either "ok" or "error" depending on whether the sensor could be accessed or not + # In an error occurred, @params["message"] contains an informative message + # The rest of the hash depends on the type of sensor. For example, the accelerometer will have + # @params["accelerometer_x"] + # @params["accelerometer_y"] + # @params["accelerometer_z"] + # + # while a tempterature sensor provides instead + # @params["temperature_value"] + end + +JavaScript syntax: + :::javascript + sensor.start(my_sensor_callback); + + function my_sensor_callback(params) { + // params.status contains either "ok" or "error" depending on whether the sensor could be accessed or not + // In an error occurred, @params.message contains an informative message + // The rest of the hash depends on the type of sensor. For example, the accelerometer will have + // params.accelerometer_x + // params.accelerometer_y + // params.accelerometer_z + // + // while a tempterature sensor provides instead + // params.temperature_value + } + +#### Stop data collection + +Once you are done using a sensor, you must stop listening for updates. Call `stop` on the sensor instance to stop the callbacks. + +Ruby syntax: + :::ruby + sensor.stop + +JavaScript syntax: + :::javascript + sensor.stop(); + +### Reading the instantaneous sensor data + +To get the instantaneous value from an sensor, use the `readData` method. + +The return value is a `hash` containing [Callback Returning Parameters](http://edgedocs.rhomobile.com/api/sensor#mstart). + +Ruby syntax: + :::ruby + data = sensor.readData + +JavaScript syntax: + :::javascript + var data = sensor.readData(); + +### Checking sensor status + +The `hash` returned from `readData` or `start` method callback, contains two values that you can use to check the status of the sensor. + +* `status` contains the string `ok` or `error` +* `message` contains the error message, only if status=error + +Ruby syntax: + :::ruby + data = sensor.readData + if data['status'] == 'error' + # process the error: log it or inform the user + puts data['message'] + end + +JavaScript syntax: + :::javascript + var data = sensor.readData(); + if (data['status'] === 'error') { + // process the error: log it or inform the user + console.log(data['message']); + } + +## Accelerometer + +The accelerometer sensor returns data about the acceleration forces on the device. This can be motion, gestures, even rotate and tilt movements. + +The output of the `Accelerometer`, `Gravity` and `Linear Acceleration` sensors must obey the following relation: + + acceleration = gravity + linear_acceleration + +Usage Examples: + +* Gesture based UI interactions, for example: shake to reload +* Motion driven games + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_ACCELEROMETER) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The accelerometer detects the following forces along the three spatial axes:" + puts "X is #{data['accelerometer_x']} m/s^2" + puts "Y is #{data['accelerometer_y']} m/s^2" + puts "Z is #{data['accelerometer_z']} m/s^2" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_ACCELEROMETER); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The accelerometer detects the following forces along the three spatial axes:"); + console.log("X is " + data['accelerometer_x']+" m/s^2"); + console.log("Y is " + data['accelerometer_y']+" m/s^2"); + console.log("Z is " + data['accelerometer_z']+" m/s^2"); + } + +## Tilt Angle Sensor + +The tilt sensor can measure the tilting of the device. + +Usage Examples: + +* 3D display which adjusts the view based on the tilt angle, for example: maps with buildings +* Input for games + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_TILT_ANGLE) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The tilt sensor detects the following orientation of the device in space:" + puts "X is #{data['tiltangle_x']} degrees" + puts "Y is #{data['tiltangle_y']} degrees" + puts "Z is #{data['tiltangle_z']} degrees" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_TILT_ANGLE); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The tilt sensor detects the following orientation of the device in space:"); + console.log("X is " + data['tiltangle_x']+" degrees"); + console.log("Y is " + data['tiltangle_y']+" degrees"); + console.log("Z is " + data['tiltangle_z']+" degrees"); + } + +## Device Orientation Sensor + +The device orientation sensor returns the orientation of the device in string form, "vertical" or "horizontal". This is different from the `Orientation Sensor` which returns the orientation along each axis in degrees. + +Usage Examples: + +* Handle screen rotation + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_DEVICE_ORIENTATION) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "Device orientation is #{data['deviceorientation_value']}" # either "horizontal" or "vertical" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_DEVICE_ORIENTATION); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("Device orientation is " + data['deviceorientation_value']); // either "horizontal" or "vertical" + } + +## Motion Sensor + +The motion sensor returns data about the motion of the device. In most devices the motion sensor is the same as the accelerometer. + +Usage Examples: + +* Gesture based UI interactions, for example: wave to navigate back or forward in browser +* Input for games + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_MOTION) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "Motion detected: #{data['motion_value']}" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_MOTION); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("Motion detected: " + data['motion_value']); + } + +## eCompass + +The Zebra eCompass is a tilt compensated electronic compass utilizing an accelerometer and a magnetometer. It returns data about the orientation of the device in relation to the magnetic north of the Earth. + +Usage Examples: + +* Maps / navigation application +* Real estate - obtain the orientation of a property + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_ECOMPASS) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "Compass reading is #{data['ecompass_value']}" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_ECOMPASS); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("Compass reading is " + data['ecompass_value']); + } + +## Magnetometer + +The magnetometer returns data about the compass direction. + +Usage Examples: + +* Maps / navigation application +* Real estate - obtain the orientation of a property + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_MAGNETOMETER) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The magnetometer detects the following magnetic fields in space:" + puts "X is #{data['magnetometer_x']} microTesla" + puts "Y is #{data['magnetometer_y']} microTesla" + puts "Z is #{data['magnetometer_z']} microTesla" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_MAGNETOMETER); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The magnetometer detects the following magnetic fields in space:"); + console.log("X is " + data['magnetometer_x']+" microTesla"); + console.log("Y is " + data['magnetometer_y']+" microTesla"); + console.log("Z is " + data['magnetometer_z']+" microTesla"); + } + +## Gyroscope + +The gyroscope returns data about the motion of the device. In most devices the gyroscope is the same as the accelerometer. + +Usage Examples: + +* UI interactions, for example: even if the device is rotated, keep the view constant +* Input for games + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_GYROSCOPE) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The gyroscope detects the following movement" + puts "X is #{data['gyroscope_x']} radians/second" + puts "Y is #{data['gyroscope_y']} radians/second" + puts "Z is #{data['gyroscope_z']} radians/second" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_GYROSCOPE); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The gyroscope detects the following movement"); + console.log("X is " + data['gyroscope_x']+" radians/second"); + console.log("Y is " + data['gyroscope_y']+" radians/second"); + console.log("Z is " + data['gyroscope_z']+" radians/second"); + } + +## Ambient Light Sensor + +The ambient light sensor returns data about the light level around the device. + +Usage Examples: + +* Automatic screen dimming + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_AMBIENT_LIGHT) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "Ambient light is #{data['ambientlight_value']}" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_AMBIENT_LIGHT); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("Ambient light is " + data['ambientlight_value']); + } + +## Proximity Sensor + +The proximity sensor returns data about the presence of objects close to the device. + +Usage Examples: + +* Turn off phone screen during calls if user holds it near the ear + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_PROXIMITY) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The proximity sensor reports: #{data['proximity_value']}" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_PROXIMITY); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The proximity sensor reports: " + data['proximity_value']); + } + +## Proximity Long Range Sensor + +The long range proximity sensor returns data about the presence of objects close to the device, but at a range beyond that of the Proximity Sensor. + +Usage Examples: + +* As a mechanism to turn on the camera in response to an approaching object + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_PROXIMITY_LONG_RANGE) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The long-range proximity sensor reports: #{data['proximitylongrange_value']}" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_PROXIMITY_LONG_RANGE); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The long-range proximity sensor reports: " + data['proximitylongrange_value']); + } + +## Pressure Sensor + +The pressure sensor returns data about the barometric or atmospheric pressure around the device. + +Usage Examples: + +* Weather application + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_PRESSURE) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The atmospheric pressure is #{data['pressure_value']}" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_PRESSURE); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The atmospheric pressure is " + data['pressure_value']); + } + +## Temperature Sensor + +The temperature sensor returns data about the atmospheric temperature around the device. In general, readings from sensors should be understood as approximations, but the temperature sensor in particular is prone to additional inaccuracies in several scenarios: some devices get warm while charging, and their temperature may tend to approximate that of the human body after being held or carried in a pocket for a period of time. + +Usage Examples: + +* Weather application + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_TEMPERATURE) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "Temperature is #{data['temperature_value']} degrees Celsius" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_TEMPERATURE); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("Temperature is " + data['temperature_value']+" degrees Celsius"); + } + +## Humidity Sensor + +The humidity sensor returns data about the atmospheric humidity level around the device. + +Usage Examples: + +* Weather application + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_HUMIDITY) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "Humidity is #{data['humidity_value']}" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_HUMIDITY); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("Humidity is " + data['humidity_value']); + } + +## Gravity Sensor + +The gravity sensor returns data about the acceleration due to gravity when the device is at rest or moving slowly. + +The output of the `Accelerometer`, `Gravity` and `Linear Acceleration` sensors must obey the following relation: + + acceleration = gravity + linear_acceleration + +Usage Examples: + +* Orientating application UI +* Input for games + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_GRAVITY) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The gravity sensor detects the following acceleration:" + puts "X is #{data['gravity_x']} m/s^2" + puts "Y is #{data['gravity_y']} m/s^2" + puts "Z is #{data['gravity_z']} m/s^2" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_GRAVITY); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The gravity sensor detects the following acceleration:"); + console.log("X is " + data['gravity_x']+" m/s^2"); + console.log("Y is " + data['gravity_y']+" m/s^2"); + console.log("Z is " + data['gravity_z']+" m/s^2"); + } + +## Linear Acceleration Sensor + +The linear acceleration sensor returns data about acceleration on the device due to motion (excluding the effect of gravity). + +The output of the `Accelerometer`, `Gravity` and `Linear Acceleration` sensors must obey the following relation: + + acceleration = gravity + linear_acceleration + +Usage Examples: + +* Input for UI interactions, for example: wave phone to go back or forward in a browser +* Input for games + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_LINEAR_ACCELERATION) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The linear accelerator sensor detects the following forces:" + puts "X is #{data['linearacceleration_x']} m/s^2" + puts "Y is #{data['linearacceleration_y']} m/s^2" + puts "Z is #{data['linearacceleration_z']} m/s^2" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_LINEAR_ACCELERATION); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The linear accelerator sensor detects the following forces:"); + console.log("X is " + data['linearacceleration_x']+" m/s^2"); + console.log("Y is " + data['linearacceleration_y']+" m/s^2"); + console.log("Z is " + data['linearacceleration_z']+" m/s^2"); + } + +## Rotation Sensor + +The rotation sensor returns data about the rotation of the device along the three dimensional axes. + +Usage Examples: + +* Input for UI interactions +* Input for games + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_ROTATION) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The rotation sensor detects the following rotation on each axis:" + puts "X is #{data['rotation_x']} degrees" + puts "Y is #{data['rotation_y']} degrees" + puts "Z is #{data['rotation_z']} degrees" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_ROTATION); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The rotation sensor detects the following rotation on each axis:"); + console.log("X is " + data['rotation_x']+" degrees"); + console.log("Y is " + data['rotation_y']+" degrees"); + console.log("Z is " + data['rotation_z']+" degrees"); + } + +## Orientation Sensor + +The orientation sensor returns the orientation of the device in 3D space. It is different from the Device Orientation Sensor in that it returns a value for each axis, instead of only the strings `"horizontal"` or `"vertical"` + +Usage Examples: + +* Input for UI interactions +* Input for games + +Ruby syntax: + :::ruby + def make_sensor + @sensor = Rho::Sensor.makeSensorByType(Rho::Sensor::SENSOR_TYPE_ORIENTATION) + if @sensor == nil + # do something if the sensor is not present, for example: show error message + end + end + + def read_sensor + if @sensor != nil + data = @sensor.readData + print_data(data) + end + end + + def start_sensor + if @sensor != nil + @sensor.minimumGap = 500 + @sensor.start(url_for(:action => :sensor_callback)) + end + end + + def stop_sensor + if @sensor != nil + @sensor.stop + end + end + + def sensor_callback + print_data(@params) + end + + def print_data(data) + puts "The orientation sensor detects the following values for each axis:" + puts "X is #{data['orientation_x']} degrees" + puts "Y is #{data['orientation_y']} degrees" + puts "Z is #{data['orientation_z']} degrees" + end + +JavaScript syntax: + :::javascript + function make_sensor() { + sensor = Rho.Sensor.makeSensorByType(Rho.Sensor.SENSOR_TYPE_ORIENTATION); + if (sensor == null) { + // do something if the sensor is not present, for example: show error message + } + } + + function read_sensor() { + if (sensor != null) { + var data = sensor.readData(); + print_data(data); + } + } + + function start_sensor() { + if (sensor != null) { + sensor.minimumGap = 500; + sensor.start(sensor_callback); + } + } + + function stop_sensor() { + if (sensor != null) { + sensor.stop(); + } + } + + function sensor_callback(data) { + print_data(data); + } + + function print_data(data) { + console.log("The orientation sensor detects the following values for each axis:"); + console.log("X is " + data['orientation_x']+" degrees"); + console.log("Y is " + data['orientation_y']+" degrees"); + console.log("Z is " + data['orientation_z']+" degrees"); + } + +## Related reading + +* The [Sensor API reference](../api/sensor) contains more details about device sensors diff --git a/docs/en/5.5/guide/devskills.md b/docs/en/5.5/guide/devskills.md new file mode 100644 index 00000000..a10ddb48 --- /dev/null +++ b/docs/en/5.5/guide/devskills.md @@ -0,0 +1,16 @@ +#Developer Skills Used + +You will use traditional Web skills when developing RhoMobile Applications including JavaScript, HTML, CSS and Ruby. Native programming languages like C++ on Windows Mobile and Java on Android, may be used through implementing RhoMobile Native Extensions to expose some functionality that the framework does not inherently support. + + +##HTML +RhoMobile applications run inside the native webkit supported webview control on modern platforms like Android and iOS as well as the Zebra Webkit on Windows Mobile/CE. RhoMobile supports modern HTML5 features, however like with standard browsers there may be differences in behavior. + +##JavaScript +JavaScript can be used in the traditional sense for either application logic and/or for user interface using modern JavaScript frameworks. RhoMobile also provides a full set of framework and device capability APIs that can be accessed in JavaScript by including the RhoMobile JavaScript library. + +##Ruby +Ruby may optionally be used in your application in a vareity of ways. When using RhoStudio' Generator for your application or data models, Ruby is used by default in the model views (.erb files) as well as the controller files (.rb). + +##CSS +CSS is used to define how to display HTML elements in your page and thus will control how your application looks and is formatted. Since RhoMobile applications are running on top of Webkit, it supports modern CSS3 attributes. Some developers choose to write there own CSS styles, while others choose to leverage some 3rd party UI frameworks like JQuery Mobile or Twitter Bootstrap. \ No newline at end of file diff --git a/docs/en/5.5/guide/geolocation.md b/docs/en/5.5/guide/geolocation.md new file mode 100644 index 00000000..f111b34d --- /dev/null +++ b/docs/en/5.5/guide/geolocation.md @@ -0,0 +1,139 @@ +# Geolocation + +## Overview +Geolocation information is available in two ways: as an asynchronous service through Ajax calls to a predefined local URL, or in a controller using Ruby calls to the Geolocation class. + +You need to enable the GPS capability to use Geolocation. This is done by adding the following line to build.yml: + + :::yaml + capabilities: + - gps + +See the [Configuration](build_config) section for more details. + +The GPS receiver consumes a significant amount of energy, and should be switched off most of the time in order to preserve the device's battery life. +Any call to Geolocation method or notification call back will power up the GPS receiver. +The GPS receiver will be switched off automatically after some time (see [Configuration](build_config) for parameters) or explicitly by Geolocation.turnoff. +Also note that it usually takes a while to acquire the device's current position; in some cases, it may take several minutes and may not work at all indoors. + +Note that in old rhodes versions (up to 2.3.1) this feature uses only GPS location provider. In more recent rhodes, it also uses network based location determination. Network based location +is not as precise as GPS, but in most cases it consumes less power and returns results faster than GPS. +Rhodes will update location using network data until the GPS signal has been received; then only GPS will be used for more precise data. + +There are two ways to use Geolocation: + + * Synchronous call to Geolocation module for particular value. + * Set Geolocation notification (geoLocation.set_notification) and track location by the notification callback. In this case all location values are passed to notification as parameters in a @param variable. + +Note that Geolocation is switched off automatically when the application goes into the background, and is switched on as the application goes back to foreground. +However it is possible to switch on location services as usual while the application is in background. + +## Asynchronous Ajax calls + +The Rhodes framework provides a simple HTML tag for accessing Geolocation information. To use it, include the appropriate JavaScript library on your page: + +* For iPhone, Android: `/public/jquery/jquery-1.6.2.min.js` and `/public/js/rhogeolocation.js` +* For Windows Mobile: `/public/js/rhogeolocation-wm.js` + +Then add one of the following tags in the appropriate location in your HTML: ``, `` or ``. The included JavaScript will query a predefined URL and fill these tags with location information. + +`` - returns a string in the form `[formatted position];[latitude];[longitude]`. + +For example: 37.3317° North, 122.0307° West;37.331689;-122.030731 + +`` - returns just the latitude
                                                                            +`` - returns just the longitude + +## Geolocation API + +Refer to the [Geolocation API](../api/geolocation) for the methods to access geolocation information from your device. + +* [accuracy](../api/geolocation#accuracy) - Returns the estimated accuracy of the fix. +* [altitude](../api/geolocation#altitude) - Returns the altitude if available, if not available 0 is returned. +* [haversine_distance](../api/geolocation#haversinedistance) - Returns the distance between two points in miles. +* [known_position?, is_known_position](../api/geolocation#knownposition-isknownposition) - Returns true if the location system is up and running, false otherwise, null if this feature is not supported on the device platform. +* [latitude](../api/geolocation#latitude) - Returns current latitude in degrees. +* [longitude](../api/geolocation#longitude) - Returns current longitude in degrees. +* [satellites](../api/geolocation#satellites) - Returns the number of satellites used to determine the fix. If this information isn't available, null is returned. +* [set_notification](../api/geolocation#setnotification) - Set callback to track location changes. +* [set_notification_ex](../api/geolocation#setnotificationex) - Extended notification which encompasses the recently added features. +* [speed](../api/geolocation#speed) - Returns the speed if it is available. If the speed is not available, 0.0 is returned. +* [turnoff](../api/geolocation#turnoff) - Turn off Geolocation. + +**NOTE: On iOS and Android, real GPS starts working after the first access to the Geolocation module. Real GPS hardware is switched off after a call to Geolocation.turnoff. But keep in mind - any call to Geolocation, such as getting latitude, starts the hardware GPS again!** + +## Testing Geolocation + +While developing your application on Windows Mobile emulator, you may find the [FakeGPS](http://msdn.microsoft.com/en-us/library/bb158722.aspx) utility useful. + +To provide Mock Location Data on Android, see [here](http://developer.android.com/guide/topics/location/index.html) + +## Samples + +Here are some examples of Geolocation Ruby code. + +### Tracking location all the time +You may decide to keep track of your position right after application starts. To do that, add following to your application.rb: + + :::ruby + class AppApplication < Rho::RhoApplication + def on_activate_app + #start geolocation + Geolocation.set_notification("/app/Settings/geo_callback", "", 3) + end + end + +Callback points to the `geo_callback` in the Settings controller.rb: + + :::ruby + class SettingsController < Rho::RhoController + def geo_callback + puts "geo_callback : #{@params}" + # do something on position changes + #... + end + end + +### Requiring location only on a specific view + + :::ruby + def show_location + # check if we know our position + if !Geolocation.known_position? + # wait till GPS receiver acquire position + Geolocation.set_notification( url_for(:action => :geo_callback), "") + redirect url_for(:action => :wait) + else + # show position + render + end + end + + def geo_callback + # navigate to `show_location` page if GPS receiver acquire position + if @params['known_position'].to_i != 0 && @params['status'] =='ok' + + Geolocation.set_notification '', '', 2 + WebView.navigate url_for(:action => :map_all) + end + end + +### Turning off Geolocation as soon as the app goes off the device front page + +In this code sample, /Geolocation/ has to be replaced with an appropriate regular expression to detect the controller. This code is called from geo_callback. This decision allows you to switch off Geolocation from a single code point in case geo_callback is set. + + :::ruby + def geo_callback + puts "geo_callback : #{@params}" + + if WebView.current_location !~ /Geolocation/ + puts "Stopping geo location since we are away of geo page: " + WebView.current_location + Geolocation.turnoff + return + end + end + +If the app does not need location updates, and Geolocation should still remain active, you can send an empty notification. + + :::ruby + Geolocation.set_notification "", "", 30 \ No newline at end of file diff --git a/docs/en/5.5/guide/handling_local_files.md b/docs/en/5.5/guide/handling_local_files.md new file mode 100644 index 00000000..97e4f6d1 --- /dev/null +++ b/docs/en/5.5/guide/handling_local_files.md @@ -0,0 +1,181 @@ +# Handing local files + +## Overview + +A RhoMobile application typically contains two different sets of files - one comprises the code for the application and another contains assets of different types: images, data files, etc. + +Files that are only needed for rendering as-is in the [WebView](../api/webview) (such as images or stylesheets) can be placed anywhere within the `public` folder and referenced in your layout or view files as appropriate. + +Data files required by the application at runtime must be accessed in two steps: + +* obtain the path to the file +* process the information as required + +You should always use the `Application.*Folder` properties and `RhoFile.join` to construct file paths because some platforms will not allow you to access files outside of your application bundle. In particular: + +* do not hardcode paths such as `/sdcard/*' even if your application only runs on Android +* do not concatenate strings with `\` or `/` characters manually in order to build paths with several components - use [RhoFile.join](../api/File#mjoin) instead + + +## Reading other files bundled with your application +The [Application API](../api/Application) allows you to find where each part of your application is stored on the filesystem. Together with [RhoFile.join](../api/File#mjoin) this lets you construct paths to all relevant files of your app. + +Ruby: + + :::ruby + # Get the various app folders + appFolder = Rho::Application.appBundleFolder + appsBundleFolder = Rho::Application.appsBundleFolder + databaseBlobFolder = Rho::Application.databaseBlobFolder + publicFolder = Rho::Application.publicFolder + userFolder = Rho::Application.userFolder + + +JavaScript: + + :::javascript + // Get the various app folders + var appFolder = Rho.Application.appBundleFolder; + var appsBundleFolder = Rho.Application.appsBundleFolder; + var databaseBlobFolder = Rho.Application.databaseBlobFolder; + var publicFolder = Rho.Application.publicFolder; + var userFolder = Rho.Application.userFolder; + +Each folder stores a particular type of content: + +* `appBundleFolder` points to your application's `app` folder +* `appsBundleFolder` is one level up from `app` +* `databaseBlobFolder` is where database blobs are stored (i.e. images and other binary content) +* `publicFolder` is your `public` folder, every file found here (or in a subfolder) can be accessed directly by [WebView](../api/webview) +* `userFolder` is the only folder where you have write permissions. You are free to create or delete as many files as you need inside `userFolder` + + +Once you know where a file is stored, you can read it with the [RhoFile API](../api/File), which allows you to work with text files from both Ruby and JavaScript (note that binary files are not supported) + +Ruby: + :::ruby + filename = Rho::RhoFile.join(Rho::Application.publicFolder, 'sample.txt') # build the path + contents = Rho::RhoFile.read(filename) # read the file into a variable + +JavaScript: + :::javascript + filename = Rho.RhoFile.join(Rho.Application.publicFolder, 'sample.txt') // build the path + contents = Rho.RhoFile.read(filename) // read the file into a variable + + +## Saving files from the network to the device + +**NOTE: the only directory you have write rights to is `userFolder` - other folders may work on some platforms but not others; in particular, iOS restricts writing files to any folder other than `userFolder`.** + +You can download files from an external server and store them on your device. The [Network API](../api/Network) lets your application download files using the [Network.downloadFile](../api/Network#mdownloadFile) method: + +Ruby: + + :::ruby + def download_file + #Download a file to the specified filename. + downloadfileProps = Hash.new + downloadfileProps["url"]='http://www.google.com/images/icons/product/chrome-48.png' + downloadfileProps["filename"] = Rho::RhoFile.join(Rho::Application.userFolder, "sample.png") + downloadfileProps["overwriteFile"] = true + Rho::Network.downloadFile(downloadfileProps, url_for(:action => :download_file_callback)) + end + + def download_file_callback + if @params["status"] == "ok" + Rho::Notification.showPopup({ + :message => "Download Success. File saved to " + Rho::RhoFile.join(Rho::Application.userFolder, "sample.png"), + :buttons => ["OK"] + }) + else + Rho::Notification.showPopup({ + :message => "Download Failed", + :buttons => ["OK"] + }) + end + end + +JavaScript: + + :::javascript + function download_file_callback(params) { + if (params["status"] == "ok") { + alert("Download Succeeded. File saved to "+Rho.RhoFile.join(Rho.Application.userFolder, "sample.png")); + } else { + alert("Download Failed"); + } + } + + function download_file() { + // Download a file to the specified filename. Be careful with the overwriteFile parameter! + downloadfileProps = { + url: "http://www.google.com/images/icons/product/chrome-48.png", + filename: Rho.RhoFile.join(Rho.Application.userFolder, "sample.png"), + overwriteFile: true + }; + Rho.Network.downloadFile(downloadfileProps, download_file_callback); + } + +## Exporting the database for backup purposes + +The [Database API](../api/Database) allows your application to export the contents of the current database to a zip archive which you can then upload to a server, copy to a memory card or otherwise make available for the user to backup. + +Ruby: + + :::ruby + # open default database + db = Rho::Database.new(Rho::Application.databaseFilePath("user"),"user") + # export database + export_path = db.export + db.close + Rho::Notification.showPopup({ + :message => "Export path - #{export_path}", + :buttons => ["OK"] + }) + + +JavaScript: + + :::javascript + // open default database + var db = new Rho.Database(Rho.Application.databaseFilePath('user'), 'user'); + // export database + var db = open_db(); + var export_path = db.export(); + db.close(); + alert("Export path - " + export_path); + + + +## Zipping and unzipping files + +RhoMobile has built-in support for zip archives. The [System API](../api/System) helps your application to zip or unzip any files. Make sure to observe the restriction that you should not be writing outside `Application.userFolder`. + +Ruby: + + :::ruby + # zip list of files + local_path_to_zip = Rho::RhoFile.join(Rho::Application.userFolder, "sample.zip") + local_path_to_file = Rho::RhoFile.join(Rho::Application.publicFolder, "sample.txt") + Rho::System.zipFile(local_path_to_zip, local_path_to_file) + + # unzip a file + local_path_to_zip = Rho::RhoFile.join(Rho::Application.userFolder, "sample.zip") + Rho::System.unzipFile(local_path_to_zip) + + +JavaScript: + + :::javascript + // zip list of files + var local_path_to_zip = Rho.RhoFile.join(Rho.Application.userFolder, "sample.zip"); + var local_path_to_file = Rho.RhoFile.join(Rho.Application.publicFolder, "sample.txt"); + Rho.System.zipFile(local_path_to_zip, local_path_to_file); + + // unzip a file + var local_path_to_zip = Rho.RhoFile.join(Rho.Application.userFolder, "sample.zip"); + Rho.System.unzipFile(local_path_to_zip); + + + + diff --git a/docs/en/5.5/guide/hardware_accleration.md b/docs/en/5.5/guide/hardware_accleration.md new file mode 100644 index 00000000..7332451d --- /dev/null +++ b/docs/en/5.5/guide/hardware_accleration.md @@ -0,0 +1,21 @@ +# Hardware Acceleration + +Hardware accleration is available on devices that have a dedicted CPU for handling graphics. This will come into play when generally for rendering application interfaces as well as when using certain CSS3 attributes typically for animation or transitions. + +## Android + +Support android:hardwareAccelerated attribute at AndroidManifest.xml for main Rhodes activity. + +To set android:hardwareAccelerated='true' at Androidmanifest.xml for RhodesActivity enable the hardware_acceleration capability. This is done by adding the following lines to build.yml: + + :::yaml + android: + capabilities: + - hardware_acceleration + +## Windows Mobile/CE +Windows Mobile or Windows CE devices do not have the capability of running applications with dedicated CPU processing for graphics. This is due to both platform and hardware constraints. Running graphic intensive operations will still run without failure, but performance may not be acceptable. + +## iOS + +RhoMobile applications running on iOS run inside of the stock Webkit (Safari) for that particular version of iOS. You should consult Apple's website for support of hardware accleration for particular OS versions. There may also be other techniques for using specific CSS attributes to force hardware acceleration like `-webkit-transform: translateZ(0);` and `-webkit-transform: translate3d(0, 0, 0);` diff --git a/docs/en/5.5/guide/html5.md b/docs/en/5.5/guide/html5.md new file mode 100644 index 00000000..6916c3df --- /dev/null +++ b/docs/en/5.5/guide/html5.md @@ -0,0 +1,47 @@ +# Using Hyperlinks for Email, Phone Dialing, SMS and others + +You can allow your users to send email messages, call phone numbers and send SMS messages using the hyperlink (``) syntax. Please note not all of these examples could work on simulators! Use real devices for test. Examples are shown below. + +To make phone calls enable the phone capability. This is done by adding the following lines to build.yml: + + :::yaml + capabilities: + - phone + +##mailto + :::html + Mailto +Note, even for an empty address, you must add the @ symbol: Mailto + +Blackberry: if you need cc, bcc fields, use rhomailto scheme: + :::html + Send e-mail to test@host.com + +##tel + :::html + Tel + Work Tel + Home Tel +Note, the WML tel description can be found [ here](http://na.blackberry.com/eng/devjournals/resources/journals/oct_2004/wml_101.jsp). + +##sms: + :::html + Send SMS to us + +Open link in external application (browser for http:// links): + :::html + Open Google in external browser + +Open appstore on iphone: [http://wiki.akosma.com/IPhone_URL_Schemes#App_Store](http://wiki.akosma.com/IPhone_URL_Schemes#App_Store) + +## Using from Ruby +When using jQuery and/or jQuery Mobile in application code, you cannot use usual html links for hyperlinks. You need to call controller action and call WebView.navigate from there: + + #Ajax call of controller method: + $.get("/app/TestController/send_mail",function(data) {}); + + #TestController method: + def send_mail + WebView.navigate( 'mailto:test@host.com' ) + #to open url in external application you can use System.open_url + end \ No newline at end of file diff --git a/docs/en/5.5/guide/intent.md b/docs/en/5.5/guide/intent.md new file mode 100644 index 00000000..95a6f4ec --- /dev/null +++ b/docs/en/5.5/guide/intent.md @@ -0,0 +1,259 @@ +# Intent API Guide + +The Intent API class allows your app to communicate with other apps on the device. With this API, you'll be able to communicate between two RhoMobile applications as well as between RhoMobile and a native application. + +**NOTE: To us this class, you should first read up on the [Intent API](../api/Intent) in our API docs so that the concepts mentioned here are more familiar.** + +## What are Intents? +Before we start sending or receiving intents, we first need to answer the question, "What are intents?". Intents are a mechanism setup and used by the Android operating system that allow application components to request functionality from other Android components. Intents allow you to interact with components from the same application as well as with components contributed by other applications. + +On other platforms, like iOS, there are concepts like [URL Schemes](https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html). Although [URL Schemes](urlschemes) have been supported by RhoMobile, this approach practically only allows launching of other applications and services and has some limitations. Intents, however, allow for a more robust cross-application communication that allows passing of data objects as well as two-way communication. + + +### Why Do I Want to Send or Receive Intents? +When we talk about "sending" or "receiving" an intent, we are referring to the action of sending an object to the OS that can be interpreted by the OS and turned into a native device command. For instance, if we send an intent with the "uri" of **"geo:37.422, -122.084"**, the Android OS knows to launch it's default maps app (since we did not specify an appName), and pinpoint Google's Mountain View headquarters. This is useful since we don't want to have to write our own mapping program that may not be as good as Google's provided mapping app. + +Another example, may be where you want something returned by the secondary application like when you want to take a picture or choose one from the gallery. This allows the application developer some freedom in not having to write code to handle this task. It is possible that the device has multiple applications with different abilities to take pictures and in that case the user would be presented with a choice to pick one. + +When it comes to having multiple RhoMobile applications running on a device, you may want to write a core service apps that listens for intents from secondary apps. This approach may be more efficient in managing your applications instead of replicating this code in all of the applications. + +You can also read up on intents on Google's [Android docs regarding intents](http://developer.android.com/guide/components/intents-filters.html). + +## Constructing an Intent +As you may have gleaned from our [Intent API docs](../api/Intent), there are only three methods available: + +* send +* startListening +* stopListening + +This is basically because you are either sending an intent or receiving one. Since Intents involve multiple applications, you need to first decide what role your RhoMobile application is going to participate as. Does your application need to send an Intent to another RhoMobile application? Does it need to send an Intent to a common Android native application? Does it expect any information back from the Intent or are you trying to just launch an application or service? Maybe you want your application to enable listening in order to respond to Intents from other applications. Understanding the required configuration between the two sides is crucial in getting the expected behavior you are looking for. + +Applications register for receiving events typically by a combination of multiple parameters: + +* action - A string that specifies the generic action to perform (such as view or select). +* categories - A array of strings containing additional information about the kind of component that should handle the intent +* uri - A string that may be needed to launch a particular application (such as tel://5551212) +* mime_type - A string representing the type of data being passed (such as textr/plain) +* data - A set of Key,Value pairs that allow for sending data to the Intent (Android calls these `EXTRAS`) + +If you don't know the right combination of parameters, then your Intent will never be received. Let's use a simple example, the one listed above regarding sending a GeoLocation coordinate to the maps app. For Android, I would check the [Android docs](http://developer.android.com/guide/components/intents-common.html#Maps) to see that an `action` and `data-uri` are the only components that are required. + +***NOTE: When the Android docs reference a constant, we will need to use the actual string that it refers. For example, when the Android docs show ["ACTION_VIEW"](http://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW), we need to instead use `"android.intent.action.VIEW"`, which can be retrieved by clicking on the constant name in the Android docs.*** + +## Sending Intents +### Assemble the Parameters +Now that we know the different pieces we'll need, let's put the intent together. These are the parameters that we need to send to open the maps app and plot the location of Google's Mountain View HQ. + +* action => "android.intent.action.VIEW" +* intentType => Rho::Intent::START_ACTIVITY (RUBY) +* intentType => Rho.Intent.START_ACTIVITY (JS) +* uri => "geo:37.422, -122.084" + +### Send the Intent +Now that we have these, we simply need to put them into a hash and use the Rho [Intent API method](../api/Intent#msend) `Intent.send()` to send the intent. This api takes two parameters. The first one is an object that represents the intent options that the intent receiver application is expecting. The second optional parameter is a callbackhandler for Intent call. In our example, we have chosen to not handle a callback. + + + +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +def send_geo
                                                                            +  intent_params = { :action     => "android.intent.action.VIEW",
                                                                            +                    :intentType => Rho::Intent::START_ACTIVITY,
                                                                            +                    :uri        => "geo:37.422, -122.084" }
                                                                            +
                                                                            +  Rho::Intent.send intent_params
                                                                            +end
                                                                            +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            +function sendGeo(){
                                                                            +  var intentParams = {action    : "android.intent.action.VIEW",
                                                                            +                     intentType : Rho.Intent.START_ACTIVITY,
                                                                            +                     uri        : "geo:37.422, -122.084"};
                                                                            +
                                                                            +  Rho.Intent.send(intentParams);
                                                                            +}
                                                                            +
                                                                            +
                                                                            + +This intent will send the string "geo:37.422, -122.084" to the Android OS and request that it start the activity that handles geolocation coordinates. If there are multiple different apps on the device that provide geolocation services, an app chooser will pop up asking the user to choose which app they want to open the coordinates in. + +### Handling Intent Response +The response that will be sent from the intent will be the same as the data that was sent from the intent that is sent. For instance, if you send intent Parameters that contain an extra called dataFromSender defined as such `{ data => { dataFromSender => "Example Data" } }`, you would access this data using the following syntax: + + + +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +def callback
                                                                            +  Alert.popup @params['data']['dataFromSender']
                                                                            +end
                                                                            +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            +function callback(){
                                                                            +  alert(params['data']['dataFromSender']);
                                                                            +}
                                                                            +
                                                                            +
                                                                            + +## Receiving Intents +Ok, we can send intents, great! But what if what you want to do is send an intent to another one of your apps, or receive an intent from another app? We can also use the Rho Intent API for this but it requires a bit more work than the sending did. + +There are a few things we need to do to receive an intent: + +* Add an intent receiver to the AndroidManifest.erb (Android Only) +* Add the code to start listening for incoming intents. +* Add a callback handler to handle the data coming in from an intent. + +### Add an Intent Receiver to the AndroidManifest.erb +When an app is installed on an Android device, it's Android manifest gets registered with the OS so that the OS knows whether or not the app is going to accept incoming intents. We need to make sure that our app's Android manifest is formatted correctly to let our app receive intents. The AndroidManifest.erb is held in the root directory of your app's project. + +NOTE: This was handled differently prior to version 4.1 - Any application project that was created prior to 4.1, should manually add a file called `AndroidManifext.erb` in the root of the project as well as add an entry to your `build.yml` file `android: manifest_template: 'AndroidManifest.erb'`. If you create a new project using RhoStudio's application wizard, you will see this performed automatically. + + +This is what our intent-filter will look like to receive a simple, plain text, intent from another app: + +`` + :::xml + + ... + + + + + + + + ... + + +Let's explain a few of the items here: + +`receiver android:name` + +This should always say `com.rho.intent.IntentReceiver`. For Android, we are basically setting up a [Broadcast Receiver](http://developer.android.com/reference/android/content/BroadcastReceiver.html) that will receive any intents that are sent as a `broadcast`. + +`intent-filter` + +* `action android:name` - This is the intent action that our app will expect from intents the it receives. +* `category android:name` - This is the category of intents that our app will expect. A value of default will accept all categories +* `data android:mimeType` - This is the data type that our app will be expecting to handle in intents that it receives. + +***NOTE: For Android, this is common syntax for an [intent-filter element].(http://developer.android.com/guide/topics/manifest/intent-filter-element.html). Also, We could have easily used any custom string that we wanted for our `action` and `category` fields. By using standard Android strings, our application will be presented as a choice when another app uses the same signature for sending an intent.*** + +### Add Code to Start Listening for Intents +Now, before we can start sending intents to this app, we need to add some code that will allow us to tell the app to start listening for intents. We do this with the Rho [Intent API method](../api/Intent#mstartListening) `Intent.startListening()`. + + + +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +def start_listening
                                                                            +  Rho::Intent.startListening "/app/Intent/listening_for_intent_callback"
                                                                            +end
                                                                            +

                                                                            You can see here that we have specified a callback handler but we have not yet defined the callback handler, we'll do that next.

                                                                            +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            +Rho.Intent.startListening(function(params){
                                                                            +  // Your callback code here
                                                                            +  console.log(params.responseCode);
                                                                            +});
                                                                            +        
                                                                            +

                                                                            You can see here that we have specified a callback handler and defined the callback handler in an anonymous function. All that's left is to fill in the code to handle the callback, we'll do that next.

                                                                            +
                                                                            +
                                                                            + +### Add a Callback Handler +We can now receive intents but, without a callback handler, receiving an intent is meaningless. + + + +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +def listening_for_intent_callback
                                                                            +  Rho::Notification.showPopup({ :message => @params['data']['dataFromSender'],
                                                                            +                                :title => "Alert!",
                                                                            +                                :buttons => ["ok"] })
                                                                            +  puts @params.responseCode
                                                                            +end
                                                                            +
                                                                            +
                                                                            +
                                                                            :::javascript
                                                                            +Rho.Intent.startListening(function(params){
                                                                            +    alert(params['data']['dataFromSender']);
                                                                            +    
                                                                            +    console.log(params.responseCode);
                                                                            +});
                                                                            +
                                                                            +
                                                                            + +All we are doing with the received data is showing a pop-up with the data that is passed in through the `uri` parameter. + +With these pieces complete, we should be able to compile an intent to send to this app and display the data that we send. + +### Construct Intent to be Received +From whatever other app you want to send an intent to this app, you must construct an intent to send to it. When creating the intent to send to the intent receiver, you must make sure the sent intent's parameters match the parameters that the intent receiver is looking for. In our case, we need to make sure we use a SEND action, some data with the text/plain mimeType, and use the DEFAULT category. We will also use a BROADCAST intentType. + + + +
                                                                            +
                                                                            +
                                                                            :::ruby
                                                                            +def send_intent
                                                                            +  intent_params = { :action      => "android.intent.action.SEND",
                                                                            +                    :intentType  => Rho::Intent::BROADCAST,
                                                                            +                    :data        => { "android.intent.extra.TEXT" => "Text to send to receiving app." },
                                                                            +                    :mimeType    => "text/plain",
                                                                            +                    :categories  => "android.intent.category.DEFAULT" }
                                                                            +
                                                                            +  Rho::Intent.send intent_params
                                                                            +end
                                                                            +
                                                                            +
                                                                            +
                                                                            +        :::javascript
                                                                            +function sendIntent(){
                                                                            +  var intentParams = {action      : "android.intent.action.SEND",
                                                                            +                      intentType  : Rho.Intent.BROADCAST,
                                                                            +                      data        : { "android.intent.extra.TEXT" : "Text to send to receiving app." },
                                                                            +                      mimeType     : "text/plain",
                                                                            +                      categories  : "android.intent.category.DEFAULT"}
                                                                            +
                                                                            +  Rho.Intent.send(intentParams);
                                                                            +}
                                                                            +    
                                                                            +
                                                                            +
                                                                            +
                                                                            :::java
                                                                            +public void sendIntent() {
                                                                            +    Intent intentRho = new Intent("android.intent.action.SEND");
                                                                            +    intentRho.addCategory("android.intent.category.DEFAULT");
                                                                            +    intentRho.setType("text/plain");
                                                                            +    intentRho.putExtra("android.intent.extra.TEXT": "Text to send to receiving app.");
                                                                            +
                                                                            +    sendBroadcast(intentRho);
                                                                            +}
                                                                            +
                                                                            +
                                                                            \ No newline at end of file diff --git a/docs/en/5.5/guide/interfacing_with_the_network.md b/docs/en/5.5/guide/interfacing_with_the_network.md new file mode 100644 index 00000000..50c95c1e --- /dev/null +++ b/docs/en/5.5/guide/interfacing_with_the_network.md @@ -0,0 +1,151 @@ +# Interfacing with the network + +The network is usually a core part of every RhoMobile application, as it is used for data transfer. However, mobile devices have very different constaints than traditional desktop systems; for example, we cannot assume that the network will always be available or reliable. To provide a good user experience, your application should detect the state of the network connection before attempting to use it + +## Detecting network availability and changes in it + +The [Network API](../api/Network) allows your application to be notified when the connection becomes available or unavailable, as well as to query whether there is a Wi-Fi or cell connection. `startStatusNotify` lets you install a callback that will be invoked whenever a change in network availability is detected: + +Ruby: + + :::ruby + def install_network_callback + # Request the system to check every 3 seconds and call us back if there is a change in network connectivity + Rho::Network.startStatusNotify(3000, url_for(:action => :status_notify_callback)) + end + + def status_notify_callback + connection_status = @params["current_status"] # either "connected" or "disconnected" + previous_status = @params["prev_status"] + + if (connection_status == "connected") + # We have a network connection! Now we can transfer data + else + # The device lost the connection + end + end + +JavaScript: + :::javascript + function install_network_callback() { + Rho.Network.startStatusNotify(3000, status_notify_callback); + } + + function status_notify_callback(params) { + var connection_status = params.current_status // either "connected", "disconnected" or "unknown" + var previous_status = params.prev_status; + alert("Connection status changed from "+previous_status+" to "+connection_status); + } + +## Triggering synchronization only when the network is likely to be reliable + +If your device has a Wi-Fi connection available, you can use the [SignalIndicators API](../api/signalindicators) on some platforms to find out the strength of the signal: + +Ruby: + :::ruby + wlan_status = Rho::SignalIndicators.wlanStatus + + signal_strength = wlan_status["signalStrength"] # returns a value between 0 and 100 + + if signal_strength > 30 + # The network should be reliable enough for data transfer. We can trigger synchronization or download large files + Rho::RhoConnectClient.doSync + else + # We may encounter some connectivity issues. It may not be a good time to start a large download now + end + +JavaScript: + :::javascript + var wlan_status = Rho.SignalIndicators.wlanStatus(); + var signal_strength = wlan_status.signalStrength; + if (signal_strength > 30) { + // The network should be reliable enough for data transfer. We can trigger synchronization or download large files + } else { + // We may encounter some connectivity issues. It may not be a good time to start a large download now + } + + +If your application is heavily dependant on synchronization or external data sources, you can leverage this knowledge of the network to make sophisticated decisions about the best moment to start transmitting data. There is of course no guarantee that the network conditions will remain the same during use; however, you will improve the way your users perceive your application if your network-heavy operations are performed when they are more likely to succeed. + +## Connecting to known networks + +Your application may need to access a server that is only available through a WAN connection, either through the Internet or via a VPN tunnel. The [Network API](../api/Network) provides you with the `connectWan` method, which lets your application request that a named connection be established. + +You can request that the default Internet connection of the device be brought up: +Ruby: + :::ruby + # Connect to the Internet + Rho::Network.connectWan("Internet", :wan_connection_callback) + +JavaScript: + :::javascript + // Connect to the Internet + Rho.Network.connectWan("Internet", wan_connection_callback); + +Or you can also ask for a particular network connection by name, as long as it has been previously configured in the Connection Manager: + +Ruby: + :::ruby + # Connect to a particular VPN + Rho::Network.connectWan("Work VPN", :wan_connection_callback) + + def wan_connection_callback + # At this point, the connection to the VPN has been attempted, but we need to check if it succeeded + # See the next section called "Detecting remote server availability" + end +JavaScript: + :::javascript + // Connect to a particular VPN + Rho.Network.connectWan("Work VPN", wan_connection_callback); + + function wan_connection_callback(params) { + // At this point, the connection to the VPN has been attempted, but we need to check if it succeeded + // See the next section called "Detecting remote server availability" + } + +**NOTE: This feature is a convenience method for your users to connect to the appropriate network with little or no interaction from their side. If you are dealing with sensitive data, do not use it as a substitute for SSL encryption** + + +## Detecting remote server availability + +If your server is not normally reachable with the default configuration of the device (for example, because you need to establish a VPN tunnel first) or the connection can be expected to be unreliable (devices in remote locations with spotty coverage), you can check whether a server can be accessed by invoking `detectConnection`. This lets you test connectivity between your application and a particular port of a server: + +Ruby: + :::ruby + Rho::Network.detectConnection( { + :host => "www.example.com" + :port => 443 + }, :detect_connection_callback) + + def detect_connection_callback + if @params["connectionInformation"]=="Connected" + # the server can be reached on port 443, trigger synchronization + Rho::RhoConnectClient.doSync + else + # the server is unavailable + end + end + +JavaScript: + :::javascript + Rho.Network.detectConnection( { + host : "www.example.com", + port : 443 + }, detect_connection_callback); + + function detect_connection_callback(params) { + if (params.connectionInformation == "Connected") { + // the server can be reached on port 443, trigger synchronization + Rho.RhoConnectClient.doSync(); + } else { + // the server is unavailable + } + } + +Once you have determined that the server is reachable, you can be reasonably sure that a connection will succeed and you can either notify the user that synchronization is available or even start it automatically. + +## Related reading + +* The [Network API](../api/Network) and [SignalIndicators API](../api/signalindicators) documentation pages provide all the details on detecting the status of the network. + +* [RhoConnect Client](../api/RhoConnectClient) is the new API to call when you want to synchronize data between your application and a remote RhoConnect server. diff --git a/docs/en/5.5/guide/kitchensink.md b/docs/en/5.5/guide/kitchensink.md new file mode 100644 index 00000000..371c1ab7 --- /dev/null +++ b/docs/en/5.5/guide/kitchensink.md @@ -0,0 +1,244 @@ +# RhoMobile Suite KitchenSink + +KitchenSink is a sample application and developer tool full of code snippets that show you how to use the APIs of RhoMobile 5.0 If you are new to RhoMobile, it is an excellent starting point to see how to start interacting with the different features of the platform and if you are an experienced user, it will quickly show you how to start getting the maximum value out of the new Ruby and JavaScript APIs. + +This document will be your step-by-step guide to how some specific features of KitchenSink were built. Along the way you will learn a few tricks on: + +* How to better organize your own applications using partials +* Using custom fonts +* JavaScript scoping +* and more + +## Download the Project +The KitchenSink source code can be found at [https://github.com/rhomobile/rho-samples/tree/master/kitchensink](https://github.com/rhomobile/rho-samples/tree/master/kitchensink) + +## Download the App +* [Android](https://s3.amazonaws.com/rhomobile-suite/4.0/Kitchen+Sink-Android.apk) +* [Windows Mobile](https://s3.amazonaws.com/rhomobile-suite/4.0/Kitchen+Sink_WM.cab) + +## Filesystem Layout + +KitchenSink 4 is a regular RhoMobile application like any other. Refer to [project structure](creating_a_project#project-structure) to know more about a typical RhoMobile project layout. In addition to the standard folders, however, KitchenSink 4 also contains: + +* `public/fonts` with the font called "OpenSans" in the appropriate format for use within a browser. Read on to see how to [convert and use fonts](#fonts) +* `app/partials`. You will learn more about [partials](#partials) in this guide +* `public/js/samples` contains the code for each sample + + +## JavaScript + +All JavaScript samples in KitchenSink 4 follow the same pattern: There is a global `KitchenSink` object, which contains a member object for each API and these objects in turn contain the functions that invoke the sample code. + +Take for instance `js/samples/notification.js`, the file that contains the samples for the new [Notification API](../api/Notification): + + :::javascript + KitchenSink.Samples.Notification = KitchenSink.Samples.Notification || (function() { + + function beep() { + ... + } + + function popup() { + ... + } + + function popup_with_multiple_buttons() { + ... + } + + function popup_callback(params) { + ... + } + + return { + beep : beep, + popup : popup, + popup_with_multiple_buttons : popup_with_multiple_buttons + }; + + })(); + +**NOTE: The rest of this section explains how to use anonymous functions to avoid polluting the global namespace. If you are already familiar with this idiom, feel free to skip to the next section.** + + +If you have not seen this type of construct before it can seem strange at first but once you analyze it step by step, it turns out to be quite straightforward. We will inspect it from the outside first and peel off its different layers until we reach the innermost code. Starting with the first line, we see that `KitchenSink.Samples.Notification` is going to be assigned a value: + + :::javascript + KitchenSink.Samples.Notification = KitchenSink.Samples.Notification || (function() { + +Which value will it take? Forget for a minute the specifics of the example and focus only on the structure: + + :::javascript + left_side = expression_a || expression_b + +`||` is the "logical or" operator. It returns `expression_a` if it can be converted to true, otherwise it returns `expression_b`. Which values can be converted to true? Every value can be converted to true except for: + +* `false` +* The number `0` +* an empty string `""` +* `null` +* `undefined` +* `NaN` (Not A Number) + +These are called "falsy" values, because within JavaScript's automatic type conversion, they can be converted into the boolean `false`, while all other values are converted into the boolean `true` and are considered "truthy" values. + +Back to the example, this construct: + + :::javascript + KitchenSink.Samples.Notification = KitchenSink.Samples.Notification || (function() { + +protects the code against accidentally loading the `notification.js` JavaScript more than once. The first time it code runs, `KitchenSink.Samples.Notification` is `undefined`, which is a "falsy" value as we just saw, and the `||` operator returns the result of the expression located to its right. If for some reason we included the `notification.js` file again, the second time this code runs `KitchenSink.Samples.Notification` will have a "truthy" value and the assignment will have no visible effect. + +Let's examine now the right-side expression; if we remove the body of the function and focus only on the structure, we are left with: + + :::javascript + KitchenSink.Samples.Notification = KitchenSink.Samples.Notification || + ( // open grouping brackets + + function() { // declare an anoymous function + + } + ) // close grouping brackets + (); // call a function with no parameters + +When the JavaScript interpreter parses the right operand, it will follow approximately this process: +* find the brackets +* evaluate what is inside them + - inside the brackets is a function + - there is nothing else +* the brackets are now evaluated, their value is a function. +* a function followed by opening and closing brackets mean to invoke the function + +The end result is that the function is called and the benefit from this approach is that, by encapsulating the function in this way, it does not need to have a name and therefore, there is no possibility that its name can conflict with any other code in the application. If we had used a named function instead, the expression could have been something like this: + + + :::javascript + function initialize() { + ... + } + + KitchenSink.Samples.Notification = KitchenSink.Samples.Notification || initialize(); + +However, we would have to be very careful throughout our whole application not to name any other function `initialize` or there would be conflicts in our code. That is somewhat easy if you have little code, but as soon as your application starts to grow beyond a handful of functions, using anonymous functions when possible is a good choice. + +Lastly, let's focus on the contents of the function itself: + + :::javascript + function() { + + function beep() { + ... + } + + function popup() { + ... + } + + function popup_with_multiple_buttons() { + ... + } + + function popup_callback(params) { + ... + } + + return { + beep : beep, + popup : popup, + popup_with_multiple_buttons : popup_with_multiple_buttons + }; + } + +What the function does is it declares some other functions and returns a hash. In JavaScript, each function creates a `scope`, which at a high level means that code outside the function is isolated from code inside. It is not possible for code outside this function to call any of the functions defined inside. We can take advantage of this fact and export some of the functions and not others: if you look closely, the function `popup_callback` is not present in the hash. You can have any number of functions declared inside another and only export those you want to be accessible, while keeping others private, with the benefit that you need not worry about name collisions. As long as they are declared in different scopes, there can be multiple functions with the same name and they will not interfere with each other. + +**NOTE: Use this pattern whenever you want to keep some functions "private" and not visible to the outside world** + +Finally, we see that in the end, the `KitchenSink.Samples.Notification` object is being set to a hash containing several functions, equivalent to the following code: + + :::javascript + KitchenSink.Samples.Notification = { + beep: function() { + ... + }, + popup: function() { + ... + }, + popup_with_multiple_buttons: function() { + + } + } + +with the following added advantages: + +* we have additional, internal functions that cannot cause conflicts anywhere else +* before the `return` statement we could include initialization code if required, calling functions or setting default values +* if we loaded the same file multiple times, initialization code would not run more than once for the same page, because the `||` operator guards the assignment as previously seen + + +## Partials + +It is very common for an application to have fragments of HTML code that are the same or very similar across different pages. One typical example of the way that RhoMobile helps fight repetition is by having a `layout.erb` file with the parts of a page that are common in all pages of an application and then individual files for each view, which are merged with the layout to produce the full HTML document. For example, when loading the `display_log_file` view from the `Log` controller, this is what happens: + + :::code + app/layout.erb app/Log/display_log_file.erb + + /---- + |
                                                                            + |
                                                                            + ... |

                                                                            Log file

                                                                            + |
                                                                            + | + |
                                                                            + | <%= @logFileContent %> + is replaced by |
                                                                            + <%= @content %> <---------------------------| + |
                                                                            + \----- + + + +Another way to reuse HTML code is by using something called `partials`. The concept is similar to that of functions, in the sense that whenever you have a piece of code that you want to call from different places, you do not simply copy and paste it but instead extract it into its own function and call the new function whenever necessary. Partials work the same way, you take a snippet of HTML code and extract it into its own file that you can later call from multiple places. + +KitchenSink 4 uses partials in several places. The first one is the main navigation menu where you see the list of APIS and samples. Open `app/index.erb` and you will find this line: + + :::ruby + <%= render :partial => "/partials/navmenu" %> + +This is the simplest example of using partials: specify the file, call `render` and print the result. Partials are stored in `/app/partials` and their filenames start with an underscore and end with the `.erb` extension. In this case, the partial called `navmenu` is stored in `/partials/_navmenu.erb`. + +**Partials can be nested to arbitrary depths**: within a partial, you can invoke another partial which in turn might invoke another and so on. This is a very powerful pattern to use when you have several common sections across pages. If you split your HTML code into partials as much as reasonably possible, you will make your application easier to update when the time comes to make changes to its design or structure. + +**Partials accept parameters**. Very similarly to how a function can receive parameters and use them to produce its resulting value, a partial accepts `locals`, which it can use. Here is an excerpt from `app/Log/confirm_read_log.erb`: + + :::ruby + <%= render :partial => "/partials/example_header", :locals => {:title => "Read log file", :description => " + This example will show you the Log information + " } + %> + +In this case, apart from specifying which partial to render, we are also passing it values for `title` and `description`. If you look inside `app/partials/_example_header.erb` you can see where these values are used in <%= => tags. + + :::html +
                                                                            + <%= description %> +
                                                                            + +This technique gives you a tremendous amount of flexibility to structure your partials for maximum reuse; if you start to see snippets of code in your application that are repeated frequently, consider converting them into partials. + +## Fonts and Colors + +By default, each device has a predefined set of fonts you can use but thanks to advances in CSS support, it is now possible to embed your own fonts and use them in your application. As of this writing, [Google fonts](http://www.google.com/fonts) contains a large collection of open-source fonts you can use for any purpose, including commercial. You can browse the collection and download any fonts you like. Do not import the fonts using Google's instructions, however: those instructions are designed for regular web pages. What you want to do instead is convert the font to a web-ready format and bundle it with your application so that it is not downloaded from the network. + +Once you have the files on your computer, there are several sites that can do the conversion for you. Two examples are [Font Squirrel](http://www.fontsquirrel.com/tools/webfont-generator) and [Font2Web](http://www.font2web.com/). Simply take the output from one of those sites, include it in your application and link to it like any other .css file. + +**NOTE: Rendering too many different fonts on the same page requires a significant amount of processing resources and can make your application feel slow. Try to limit the amount of fonts, especially on Windows Mobile devices. ** + +Now that the font is available for use in your application, you have two options to start using it: one is to manually create a .css file and use the `font-family` property to manually assign the font to particular elements in your application. This gives you the most flexibility and control, at the expense of added complexity. The most straightforward option, and what was used in KitchenSink 4, is to use jQuery Mobile's [ThemeRoller](http://jquerymobile.com/themeroller/?ver=1.3.1) to build a custom jQuery Mobile theme. In the theme settings column, open "Font Family" and enter `Open Sans`. That will set the default font for the whole application. + +If you want to experiment with changing the look of KitchenSink, import `public/jqmobile/rms40.css` into ThemeRoller (there is a button at the top of the page labeled "Import or upgrade") and play with the different colors and settings. Once you like the preview, download your new theme and overwrite the .css file with your new version. Make sure the jQuery Mobile version selector in ThemeRoller is set to match the version included with KitchenSink (currently 1.3.1) + + +## Related reading + +* [App architecture](appdesign) +* [User Interface architecture](uichoices) \ No newline at end of file diff --git a/docs/en/5.5/guide/licensing.md b/docs/en/5.5/guide/licensing.md new file mode 100644 index 00000000..8717458a --- /dev/null +++ b/docs/en/5.5/guide/licensing.md @@ -0,0 +1,47 @@ +# Licensing +Licensing in RMS 5.x has changed considerably. Most significant is the requirement to maintain a subscription to [rhomobile.com](http://www.rhomobile.com) before building any app. While you can still build an unlimited number of local apps for free, pricing models apply for cloud-based builds and for most apps that will use RhoConnect or RhoElements. + +## Subscriptions +Zebra's new subscription licensing model offers three levels: Free, Silver and Gold. The the plans are detailed below. + + + +NOTE: The free subscription is limited to local builds using Rhodes and RhoStudio only. + +## Applying Your Subscription Plan +Once you have signed up for a subscription on [rhomobile.com](http://www.rhomobile.com/content/rhopricing.html), you'll need to apply your new plan to your copy of RhoStudio. This can be done through the IDE or the command line. Either method allows the registered user to sign into their rhomobile.com account in advance or at build time. Both methods are detailed below. + +### Signing In With the Command Line +
                                                                            +
                                                                            +

                                                                            To apply your subscription plan using the command line run the command:

                                                                            +
                                                                            $ rake cloud:login
                                                                            + +

                                                                            This will prompt for a username and password, log into the rhomobile.com account and download the API token to the local machine.

                                                                            Token storage:

                                                                            On Mac OS X- ~/.rhomobile/token

                                                                            On Windows- /Users/<username>/.rhomobile/token

                                                                            +
                                                                            +
                                                                            + +
                                                                            +
                                                                            + +### Signing In Through RhoStudio + +
                                                                            +
                                                                            +

                                                                            To apply your subscription plan using the RhoStudio IDE:

                                                                            +
                                                                              +
                                                                            1. Open the preferences pane (⌘, on Mac OS, Ctrl+P on Windows)
                                                                            2. +
                                                                            3. Select RhoMobile -> RhoMobile.com and click the "login to rhomobile.com" button
                                                                            4. +
                                                                            5. Enter username and password when prompted
                                                                            6. +
                                                                            +

                                                                            Once valid credentials are entered, an API token will be downloaded and stored on the local machine.

                                                                            Token storage:

                                                                            On Mac OS X- ~/.rhomobile/token

                                                                            On Windows- /Users/<username>/.rhomobile/token

                                                                            +

                                                                            If you don't have an account while going through these steps, you'll be prompted to sign up on the fly. Just click the "Signup" link in the login prompt and your browser should open and point to RhoMobile.com.

                                                                            +
                                                                            + +
                                                                            + +
                                                                            +
                                                                            + +### Done! +Once you've applied your license you shouldn't be prompted to log in again. You're now free to use the tools as often as you like. **So let's start building**! \ No newline at end of file diff --git a/docs/en/5.5/guide/live-update.md b/docs/en/5.5/guide/live-update.md new file mode 100644 index 00000000..17e2494f --- /dev/null +++ b/docs/en/5.5/guide/live-update.md @@ -0,0 +1,355 @@ +# Live Update +## Overview +Live Update is a **new feature in [RhoMobile Suite 5.1](http://rhomobile.com)** that instantly displays changes to many parts of a RhoMobile app on-device without the need to manually recompile and redeploy. This enables on-the-fly programming and debugging on multiple mobile devices at the same time. It supports Android, iOS, the Apple iOS simulator, and Windows Mobile/CE in any combination. + +Live Update works by monitoring files in the **/apps** and **/public** folders of your RhoMobile app and builds a complete or partial update bundle that can either deploy immediately or on command. Once notified of an update, the target device(s) download the bundle from the development host (on which Live Update embeds a web server), apply it and refresh the Webview to display the changes. Live Update works through RhoStudio or from the command line. + +This guide provides an overview of the Live Update setup process from within RhoStudio's Project Explorer and text editor. **Once it's familiar, this process should require just a few minutes to complete**. Some of the steps also can be performed from the command line and/or using your favorite text editor. + +##Live Update Modes +Live Update has four modes of operation: + +* **Partial Update** packages the portions of a project that have changed and notifies devices that a download is available. This on-command feature works only from the command line and must be initialized before each debugging session. Use this mode when you want to make multiple changes and see them applied on command instead of each time a file is saved. + +* **Full Update** packages all files in a project regardless of whether they've been changed and notifies devices. This on-command feature works only from the command line and does not require initialization. + +* **Auto Update** monintors all files in a project and automatically packages the app and notifies devices every time changes are saved. This mode is invoked by pressing the 'Enable Live Update' button in the Live Update Settings page in RhoStudio or using the CLI command below. It can be monitored and stopped from the Progress tab or using the CLI command below. + +* **Build and Notify** mode is intended for use when integrating Live Update with an external build system. This CLI-only feature is invoked with the '**rake dev:update:build_and_notify**' command. + +**Live Update receives change info from** two files stored in the project's root level: + +* `upgrade_package_add_files.txt` lists the project's new or modified files +* `upgrade_package_remove_files.txt` lists files removed from the project + + +##Requirements +**Live Update works only on 'RhoElements' apps built with [RhoMobile Suite 5.1](http://rhomobile.com)** or higher. + +###Live Update is supported on: + +* Mac OS X development hosts
                                                                            +* Windows development hosts (currently in beta)
                                                                            +* Android
                                                                            +* iOS
                                                                            +* Apple iOS simulator
                                                                            +* Windows Mobile/CE
                                                                            +* **Apps created with the RhoElements option box checked** + +###Live Update is *not* supported on: + +* RhoSimulator
                                                                            +* Android emulators
                                                                            +* Apps built on RhoMobile.com (formerly Rhohub)
                                                                            +* Deployed apps lacking the “development” extension
                                                                            +* Apps with [build: "release"] in their `build.yml` file
                                                                            +* Apps built without the RhoElements option box checked + +###Live Update acts on changes to: + +* HTML
                                                                            +* CSS
                                                                            +* JavaScript
                                                                            +* Ruby
                                                                            +* Embedded Ruby
                                                                            +* Images
                                                                            +* Other files in **/app** and **/public** folders (only)
                                                                            + +## Enable Live Update +###Quick Setup: +Here's a quick overview of the steps required to enable Live Update on a new or existing RhoElements app. When setting it up for the first time, we recommend using the detailed instructions that follow. Once it's familiar, this process should require just a few minutes to complete using these quick-setup steps. + +1. Confirm that `build.yml` contains the line **'build: debug'**
                                                                            +2. **Add '- development' to extensions:** line in `build.yml`
                                                                            +3. Establish that **all devices are on same Wi-Fi subnet** as dev host
                                                                            +4. **Build, deploy and launch** app(s) to device(s)*
                                                                            +5. In Project Explorer, R-click and **view 'Live Update Settings'**
                                                                            +6. In upper section of Settings, **double-click subnet** to discover device(s)
                                                                            +7. In Project Explorer, **R-click project and select 'Refresh'**. The file `dev-config.yml` will appear in project
                                                                            +8. **Open `dev-config.yml` with text editor and add 'refresh: 1'** (not indented) after device section(s) to enable Live Update for all
                                                                            +9. In Live Update Settings, **press "Enable Live Update" button** + +**Following this process, an update will occur each time a file is saved, placed in or removed from the /app or /public folders**. If you're having trouble, refer to the detailed instructions or troubleshooting section below.
                                                                            + +NOTE: The first Live Update in a session could take several minutes to appear; subsequent updates generally occur after a few seconds. + +######(*) A USB cable is required for initial application deployment; RhoStudio does not support deployment over Wi-Fi. + +##1- Modify the build.yml +This section contains detailed instructions for configuring Live Update on a development host. It follows the same general sequence as the Quick Setup above. + +Live Update works only on apps built with the RhoElements option box checked (as below). To confirm that your app is compatible, check for the line **app_type: "rhoelements"** in its `build.yml` file (as in the image that follows, below). + +![RhoElements Checkbox](http://rhodocs.s3.amazonaws.com/guide/LiveUpdate/01_RhoElements_checkbox.png) +
                                                                            + +###How to modify the Build.yml: +** *After* ** your app is created but ** *before* ** it's built and deployed to the device: + +* **Locate your project** in Project Explorer and expand its file tree +* **Right-click** the `build.yml` file and select **"Open With > Text Editor"** +* Confirm that `build.yml` **contains the line 'build: debug'** (quotes will be inserted automatically when it's built) +* **Locate the 'extensions:' line and add '- development' on a new indented line** +* **Save your changes** but ** *do not build yet* ** + +![Build.yml extensions](http://rhodocs.s3.amazonaws.com/guide/LiveUpdate/02_Build.yml_extensions.png) + +##2- Establish Single Wi-Fi Subnet + +**Skip this step if your Wi-Fi network consists of a single subnet (most common).** + +Live Update requires that subscriber device(s) be on the same Wi-Fi subnet as the development host. That means that the first three figures of a device's IP address match those of every other device as well as those of the development host, and that the fourth figure does not. Setting this up it might require help from your IT department. + +To try it yourself: + +* **Open your devices' Wi-Fi control panel(s)** and verify that they're on the same subnet. +* **Make a note** of the IP address(es) +* **Change the IP address of the development host to match device(s)** + +![Mac OS X Wi-Fi prefs panel](http://rhodocs.s3.amazonaws.com/guide/LiveUpdate/04_Mac_Wi-Fi_prefs.png) + +The screenshot above shows the **Network Preferences panel of Mac OS X** after entering the Wi-Fi section, clicking the Advanced… button and selecting the TCP/IP tab. In the case, the machine's subnet is "10.186.6" and it's using DHCP. Click on the drop-down (indicated by the arrow) and **select "Use DHCP with manual address**" to allow a user-assigned IP address that's in the same subnet as the target device(s). + +NOTE: CAUTION: Manually editing IP addresses can lead to address conflicts and interruptions in service. We recommend consulting with IT before making changes. + +##3- Build, Deploy and Run the App + +* From the **Run Menu**, select **> Run Configurations** +* Above the **left pane** click the **New Configuration button** (see image below) +* **Enter a name** for your build configuration +* From the drop-downs, **select the relevant project, platform, simulator and build type** +* Check the 'Clean before build' box (only necessary for first-time builds or after the `build.yml` has beed edited) +* **Click the Run button** to build, deploy and run your app on the selected device + +NOTE: A USB cable is required for initial application deployment; RhoStudio does not support deployment over Wi-Fi. + +![Build.yml settings](http://rhodocs.s3.amazonaws.com/guide/LiveUpdate/03_new_Build_config.png) + +NOTE: CAUTION: When bringing up the Run Configurations screen, RhoStudio opens the most recenly used build config, which could cause you to mistakenly re-build the last app you were working on. A good practice is to name your build config after the app it builds, and always to confirm the selected build config before clicking 'Run.' + +When first launched, an app that has been properly modified for Live Update will display a message similar to the one below. The name of the example app is "Bloopy." + + +#####Successful deployment of a Live Update-enabled app. + +
                                                                            +##4- Discover Devices, Begin Live Update Service +This step establishes Wi-Fi communications between the development host and the device(s) that you want to receive Live Updates. After discovery, the dev host knows which devices to 'notify' of updates and the devices become 'subscribers' to an embedded web server page on the dev host for downloading update bundles. + +With the modified app(s) running on the device(s): + +1. In Project Explorer, R-click your project's **'Live Update Settings'** file +2. Select **Open With > Live Update Setting** +3. In Subnets section, **double-click the subnet** that contains the device(s) to be discovered +4. A list of devices ** *that are running your Live Update-enabled app* **will appear in the Found Devices section +5. **Click the "Enable Live Update" button**, which is above the Subnets section +6. In the Project Explorer pane, **R-click project and select 'Refresh'**. The file `dev-config.yml` will appear in the project. +7. **Open `dev-config.yml` with the text editor and add 'refresh: 1'** (not indented) after the device section(s) to enable Live Update for all devices
                                                                            + + +![dev-config.yml mods](http://rhodocs.s3.amazonaws.com/guide/LiveUpdate/06_dev-config.yml.png) +
                                                                            + +**Congratulations!** Your dev host and target device(s) are now ready to use Live Update. To test it, make an obvious change to any file in the app's **/app or /public folder** and save it. + +After a moment, your device(s) should display the change along with a message like the one below. In this case, the app name was changed from Bloopy to "WorkerBee." + + +#####Successful deployment of an update bundle. +
                                                                            + +NOTE: The first Live Update in a session could take several minutes to appear; subsequent updates generally occur after a few seconds. + +##Notes about device and app behavior + +* Live Update works with multiple devices simultaneously, as long as they're among the discovered devices and have a Live Update-enabled app running. + +* A device that goes to sleep between Live Updates might become unresponsive or display errors on subsequent updates. First try killing and re-starting its app(s). If that fails, uninstall and redeploy the app(s). + +* An iPhone that is in sleep mode or has the Live Update app minimized will not be discovered. + +* To test apps for iOS, you must [manually install your app from iTunes](/guide/build_ios). + +* Changes to `.rb` files might require the app(s) to be killed and restarted. + + +##Troubleshooting +Here are some common problems and known issues of Live Update. If Live Update is not working for you, double-check the following first: + +* Does your `build.yml` file include the development extension? +* Are your device(s) on the same Wi-Fi subnet as the dev host? +* Does the `dev-config.yml` file contain 'refresh:1 on a not-indented line? +* If CLI commands are not responding, have you set the directory to that of your project? +* Is "Live Update is running" displayed in the Progress tab? + +###About Build.yml and Live Update + +* When a project is first created (but not yet built), the 'build' line in the `build.yml` file looks like this: + + + build: debug + +* After the first build, it looks like this: + + + build: "debug" + +
                                                                            + +* Changing "debug" to "release" declares a production build and removes the Live Update capability. + +* Before (and after) your first build, your 'extensions' line should look like the **correct** one below. If it doesn't, you might have forgotton to check "Use RhoElements" box when creating your project.
                                                                            + +**CORRECT**: + :::xml + + ... + extensions: + - rhoconnect-client + - development + +**INCORRECT**: + :::xml + + ... + extensions: ["rhoconnect-client"] + +###PROBLEM + +>"ERROR when downloading or unpack[ing]"
                                                                            + +> + +>**POSSIBLE CAUSE**
                                                                            +>Network connectivity issue + +>**SOLUTION**
                                                                            +>Check that the device is on the same Wi-Fi subnet as the dev host; kill and re-launch the app; rebuild and redeploy the app.
                                                                            + +###PROBLEM +>"Your application files too old" + +> + +>**POSSIBLE CAUSE**
                                                                            +>Mutiple files are out of sync between the dev host and the deployed app. + +>**SOLUTION**
                                                                            +>When using auto update mode, do not attempt to make changes to a file without first saving previous changes and seeing them updated on the device. This problem can sometimes be solved by "Refreshing" the app (R-clicking on the project name and selecting "Refresh") and applying an update with the full bundle. Otherwise, rebuild and redeploy the app. + +###PROBLEM +>"Error when update Bundle ... replace bundle ... unable to rename folder"
                                                                            + +> + +>**POSSIBLE CAUSE**
                                                                            +>This is a known issue in Live Update. + +>**Solution**
                                                                            +> On the device, go to **Settings > Apps > (your app) ** and press the '**Clear data' and 'Clear cache**' buttons. Then apply a **full update** or redeploy the app. +
                                                                            + +##Live Update from the CLI + +**1- Open a Terminal window and make your project the current directory**. + +**2- Discover devices on the current Wi-Fi subnet**: + + + + + rake dev:network:discovery + + + +If more than one subnet is present, you must specify which subnet to scan: + + + rake dev:network:discovery["192.168.1.*"] + +If you don't know whether more than one subnet is available, display a list... + + + rake dev:network:list + + +...and then use the ':discovery["IP ADDRESS"]' command above to specify which subnet to scan for subscribers. + +**3- Select subscribers using the following commands**: + + +For Android: + + + rake run:android:device + +For iOS: + + + + rake run:ios:device + + For Windows Mobile: + + + + rake run:wm:device + +**4- To start the Webserver, open a new Terminal window, navigate to your project directory and enter**: + + :::term + + rake dev:webserver:start + +To Stop the Webserver + + :::term + + rake dev:webserver:stop + + +**5- Select one of four Live Update modes of operation**: + +* **Partial Update** packages the portions of a project that have changed and notifies devices that a download is available. This on-command feature works only from the command line and **must be initialized** before each debugging session. Use this mode when you want to make multiple changes and see them applied on command instead of each time a file is saved. + rake dev:update:initialize + rake dev:update:partial + + +* **Full Update** packages all files in a project regardless of whether they've been changed and notifies devices. This on-command feature works only from the command line and does not require initialization. + + rake dev:update:full + +* **Auto Update** monintors all files in a project and automatically packages the app and notifies devices every time changes are saved. This mode is invoked by pressing the 'Enable Live Update' button in the Live Update Settings page in RhoStudio or by using the CLI command below. It can be monitored or stopped from RhoStudio's Progress tab, by pressing CTRL-C in webserver window, or by using the CLI commands below. + rake dev:update:auto + rake rev:update:auto:stop + +* **Build and Notify** mode is intended for use when integrating Live Update with an external build system and is a CLI-only feature. + rake dev:update:build_and_notify + +**Live Update receives change info from** two files stored in the project's root level: + +* `upgrade_package_add_files.txt` lists the project's new or modified files +* `upgrade_package_remove_files.txt` lists files removed from the project + +###Using Live Update with apps built on disparate platforms + +It possible to build an application on one host platform and use it with Live Update on another. For example: an iOS application built on Mac OS X can be copied to +a Windows development host for use with Live Update. + +To do this, enter the following command on the second dev host before your first Partial Update: + + :::term + + rake dev:update:full + +This will detect the connections and pathways for the new host computer and update your code accordingly. + +###Switching between Live Update apps +If you're taking a break from working on one app that uses Live Update and starting work on another, follow these steps to make Live Update work smoothly: + +1. **Halt Live Update in the first app** by either pressing the square red stop button in RhoStudio's Progress tab, by executing the **rake dev:update:auto:stop** Terminal command from the project folder or by **pressing CTRL-C from the webserver window** +2. **Launch the second Live Update-enabled app** on the device(s) on which to test +3. Open the second app project in RhoStudio and **open its Live Update Settings window** +4. **Discover the device** running the second Live Update-enabled app +5. **Press "Enable Live Update" button** to start the Live Update service +6. **Double-check the `dev-config.yml` file** for the correct app in its 'application:' line diff --git a/docs/en/5.5/guide/local_database.md b/docs/en/5.5/guide/local_database.md new file mode 100644 index 00000000..f32ec1a6 --- /dev/null +++ b/docs/en/5.5/guide/local_database.md @@ -0,0 +1,118 @@ +# Data Handling with Rhom and ORM + +The RhoMobile Suite provides several APIs for handling device data. Released with RhoMobile Suite 5.3 is the [ORM common API](../api/NewORM), which supports JavaScript and Ruby. RMS 5.2 and earlier versions support the original [Rhom API](../api/rhom-api) for Ruby apps and the [ORM API](../api/Orm), which adds JavaScript support to Rhom via the [OPAL library](http://opalrb.org). + +**RMS 5.3 and higher**: + +* [ORM Common API](../api/NewORM) (JavaScript and Ruby) +* [ORM Model Common API](../api/NewORMModel) (JavaScript and Ruby) + +**RMS 5.2 and lower**: + +* [ORM API](../api/Orm) and [ORM Model API](../api/OrmModel) (JavaScript) +* [Rhom API](../api/rhom-api) (Ruby) + +**Documentation**: + +* [ORM Common API Guide](newORM_js) (JavaScript) +* [ORM Common API Guide](newORM_ruby) (Ruby) +* [JavaScript 'Rhom' Guide](rhom_js) +* [Ruby Rhom Guide](rhom_ruby) + +NOTE: The ORM common API exposes more methods to JavaScript than the ORM API, and is therefore recommended for building new JavaScript apps. Ruby developers can use Rhom or the ORM common API. + +## What is ORM? +In general computing, [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) refers to the object-relational mapping technique that permits records of a relational database to be stored and retrieved programatically as objects. For RhoMobile, the ORM API provides a powerful high-level interface to an on-device SQLite database that can work alone or with the [RhoConnectClient](../api/RhoConnectClient) to enable two-way synchronization between your application and a RhoConnect server. + +One of the main benefits of using an ORM is the simplicity it brings to database operations. Instead of having to write complex SQL statements by hand, an app can perform database actions by getting and setting properties on model objects. For example: + +Update a record with a SQL command: + + :::sql + update product set price=119,brand='Symbol' where object='12345' + +Update the same record with ORM: + + :::javascript + product.updateAttibutes({price: 119, brand: "Symbol"}); + +Delete a record with SQL: + + :::sql + delete from product where object='12345' + +Delete an object with ORM: + + :::javascript + product.destroy(); + +## What's a model? +In general, RhoMobile applications follow the [Model-View-Controller](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) (MVC) pattern. In RhoMobile, a model can store information from two sources: + +* Data created or collected on the device +* Data retrieved from a RhoConnect synchronization server + +Each model contains attributes (aka 'fields') that store information relating to that model. For example, a `Product` model might have the attributes of `name`, `brand` and `price`. Applications will normally have a model for each entity that they handle (i.e. `Customer`, `Product`, `Invoice`, `InvoiceLine`, `Order`, `LineItem`, etc). + +RhoMobile apps can use two kinds of models: + +* Property Bag +* Fixed Schema + +Each model type has advantages and disadvantages depending on the application. + +## Property Bag Model + +In the property bag model, data is stored as key-value pairs in a single table using the object-attribute-value or [entity-attribute-value model](http://en.wikipedia.org/wiki/Entity-attribute-value_model). This model is sometimes referred to as 'open schema' because the fields (or keys) do not have to be defined in advance; the API stores and syncs all key-value pairs that are entered. + +### Advantages +* Simple, doesn’t require advance attribute design +* Attributes can be added or removed without modifying the database schema +* Requires no data migration following a schema change + +### Disadvantages +* Since all attributes are indexed, the database can be much larger than with fixed schema +* Sync process can be slower because database insertions are performed at the attribute level + +## Fixed Schema Model + +In a fixed schema model, each model has a separate database table and attributes forms the columns of that table. In this sense, the fixed schema model is similar to a traditional relational database. + +### Advantages +* Smaller database size; indexes can be assigned to specific attributes +* Sync process may be faster because whole objects are inserted at once + +### Disadvantages +* Schema changes require data migration +* Database performance may be slow without careful index specificity + +## How to Include the ORM API + +By default, RhoMobile apps will be built to use the older Rhom implementation (for Ruby) and ORM implementation (for JavaScript). To activate the newer ORM Common API (which supports both JavaScript _and_ Ruby), add the following line to application’s `rhoconfig.txt` file: + + :::yaml + use_new_orm = 1 + +Possible Values: + +* **0 = use 'old' Rhom/ORM API (default)** +* 1 = use newer ORM Common API + +NOTE: If this parameter is left unspecified, the older Rhom/ORM API will be used. + +## Database Encryption + +If your application requires local (on-device) database encryption, enable it by setting a flag in `build.yml`: + + :::yaml + encrypt_database: 1 + +**NOTE: Database encryption is not currently supported for applications that use bulk sync.** + +### Platform Notes +* iOS uses an AES 128 encryption algorithm from the iOS SDK. +* Android uses an AES 128 ecryption algorithm from the Android SDK. +* Windows Mobile uses an RC4 algorithm from Windows Mobile SDK. + + +**NOTE: [Rhom data encryption](../../2.2.0/rhodes/rhom#database-encryption) is no longer available as of Rhodes 3.3.3 and higher. This feature is now supported only in Zebra RhoMobile Suite and requires the purchase of a [RhoElements license](licensing).** diff --git a/docs/en/5.5/guide/localization.md b/docs/en/5.5/guide/localization.md new file mode 100644 index 00000000..ec3a0bec --- /dev/null +++ b/docs/en/5.5/guide/localization.md @@ -0,0 +1,51 @@ +# Localization + +See [Rhodes System API Samples application](http://github.com/rhomobile/rhodes-system-api-samples/tree/master/app/Localization/index.erb) as an example. + +Rhodes use localization_simplified library to support non-English languages. + +Add to build.yml: + + extensions: ["rholang"] + +In case of several extensions, insert space after extension name and comma: + + extensions: ["rholang", "net-http"] + +Create utf-8 encoded file in app `/app/lang/lang__.rb` or `/app/lang/lang_.rb`. This file will be automatically loaded by rhodes based on current locale. + +For Example create lang_en.rb: + :::ruby + module Localization + Views = { + :greeting => "This is test" + } + end + +And use this string in the view: + :::html +
                                                                              +
                                                                            • <%= Localization::Views[:greeting] %>
                                                                            • +
                                                                            + +To switch locale at runtime use: + :::ruby + System::set_locale('es') #set current locale to Spanish + +### Details: + +All non-ascii symbols should be utf-8 encoded. + +To get current locale on the phone use System.get_locale method. It returns 'en', 'de', etc. locale id's. + +To show localized Date and Time: + :::ruby + Time.now.to_formatted_s(:long) + Time.now.strftime("%B %d, %Y %H:%M") # all names will be localized + Date.today.to_formatted_s(:long) + Date.today.strftime("%B %e, %Y") # all names will be localized + +To show currency (see rails analog for details): + :::ruby + Rho::NumberHelper.number_to_currency + diff --git a/docs/en/5.5/guide/logging.md b/docs/en/5.5/guide/logging.md new file mode 100644 index 00000000..5ff0aaf8 --- /dev/null +++ b/docs/en/5.5/guide/logging.md @@ -0,0 +1,88 @@ +# Logging +There are two methods to log messages. + +From any controller you can log using the methods app_info and app_error. These methods take a string and will write that to rholog.txt with the category of your controllers name. + +Call app_info and app_error from a method in your controller: + + :::ruby + def index + app_info "My info message" + app_error "My error message" + end + +There also is a logging Ruby class called RhoLog. This class has methods info and error which take 2 strings. The first string is the category, the second string is the message. + +The [Rho.Log API](../api/Log) has methods to print error messages. Click the links below for detailed information about the methods. + + * [info](../api/Log#minfo) - Print an information message in the rholog.txt file. + * [error](../api/Log#merror) - Print an error message in the rholog.txt file. The message will have an “ERROR” prefix. + +Call the RhoLog error or info methods from a method in your Rhodes app: + +Ruby + + :::ruby + def index + Rho::Log.error("Some error message", "Some Category") + Rho::Log.info("Some info message", "Some Category") + end + +JavaScript + + :::javascripr + Rho.Log.error("Some error message", "Some Category"); + Rho.Log.info("Some info message", "Some Category"); + +Additionally all common ruby output routines (like puts, print) are redirected to rhodes log with INFO level. + +In rholog.txt the lines appear as follows: + + | + +To enable remote logging just add the line to `rhoconfig.txt`: + + rhologurl = 'http://:[/path]' + +Then all log messages will be sent to the specified URL via POST HTTP-requests. + +You can also send log to remote server manually: Log server address where log will be posted by using RhoConf.send_log or from the log view. Log server source code is open and available at , so you can deploy your own logserver. + +Add the lines to `rhoconfig.txt`: + + logserver = 'http://rhologs.heroku.com' + logname='helloworld' + +Then call RhoConf.send_log: + + :::ruby + def index + Rho::RhoConf.send_log() + end + + +See [Log Configuration](runtime_config#rhoconfigtxt) for all Logging configuration parameters. + +## How see log messages from iOS device. + +You have next ways for get log from iOS device : + +1. See full console output + +* open XCode +* open Organizer ("window" submenu in top menu) +* select "Devices" tab +* select your connected device in left panel +* select "Console" + +2. Get the rholog.txt file from device + +* open XCode +* open Organizer ("window" submenu in top menu) +* select "Devices" tab +* select your connected device in left panel +* select "Applications" +* select your application and wait few seconds +* you can select local file in your application's local folder and download it to computer - use "Download" button in bottom panel + +3. Send log to server from application \ No newline at end of file diff --git a/docs/en/5.5/guide/maps.md b/docs/en/5.5/guide/maps.md new file mode 100644 index 00000000..474f75c5 --- /dev/null +++ b/docs/en/5.5/guide/maps.md @@ -0,0 +1,105 @@ +# MapView + +The MapView class provides an embeddable map interface, similar to the one provided by the Maps application. Click the links below for detailed information about the [MapView API methods](../rhodesapi/mapview-api). + + * [create](../rhodesapi/mapview-api#create) - Create a map on your device. + * [set_file_caching_enable](../rhodesapi/mapview-api#setfilecachingenable) - Enable file caching for map tiles. The file cache can be used for offline map browsing. + * [preload_map_tiles](../rhodesapi/mapview-api#preloadmaptiles) - Preload a map tiles for a region defined by a zoom level range. + +### MapView Settings + +The supported providers are 'Google', 'ESRI', "RhoGoogle" and "OSM". + +To use ESRI maps in your projects on iPhone: + +* Install [ESRI iOS SDK](http://resources.arcgis.com/content/arcgis-iphone/api) - use default folders during installations ! +* Add "esri" to your applications extensions list in build.yml file. + +To use native Google map view on Android: + +* Install Google Add-on API using Android SDK Manager +* Setup Google Play Map service and create [Google Maps V2 API key](https://developers.google.com/maps/documentation/android/start#the_google_maps_api_key) +* Add 'apikey' parameter and 'gmaps' extension to your build.yml + + android: + apikey: + extensions: [gmaps] + +* Add 'network_state' and 'sdcard' capabilities to your build.yml. + + capabilities: + - network_state + +Map settings in rhoconfig.txt : + +* ESRI_map_url_roadmap - URL of ESRI roadmap tile map server (example: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/') +* ESRI_map_url_satellite - URL of ESRI satellite tile map server (example: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/') +* OSM_map_url_roadmap - URL of OSM tile map server (example: 'http://tile.openstreetmap.org/') + +### MapView Examples + +The following code in your controller has the map appear on a whole page. + +Ruby example: + + :::ruby + map_params = { + :provider => 'Google', + :settings => {:map_type => "hybrid",:region => [@params['latitude'], @params['longitude'], 0.2, 0.2], + :zoom_enabled => true,:scroll_enabled => true,:shows_user_location => false, + :api_key => 'Google Maps API Key'}, + :annotations => [{:latitude => @params['latitude'], :longitude => @params['longitude'], :title => "Current location", :subtitle => ""}, + {:street_address => "Cupertino, CA 95014", :title => "Cupertino", :subtitle => "zip: 95014", + :url => "/app/GeoLocation/show?city=Cupertino"}, + {:street_address => "Santa Clara, CA 95051", :title => "Santa Clara", :subtitle => "zip: 95051", + :url => "/app/GeoLocation/show?city=Santa%20Clara", :pass_location => true}] + } + MapView.create map_params + +JavaScript example: + + var map_params = { + provider: 'Google', + settings: { + map_type: 'hybrid', + region: [@params['latitude'], @params['longitude'], 0.2, 0.2], + zoom_enabled: true, + scroll_enabled: true, + shows_user_location: false, + api_key: 'Google Maps API Key' + }, + annotations: [ + {latitude: @params['latitude'], longitude: @params['longitude'], title: "Current location", subtitle: ""}, + {street_address: "Cupertino, CA 95014", title: "Cupertino", subtitle: "zip: 95014", url: "/app/GeoLocation/show?city=Cupertino"}, + {street_address: "Santa Clara, CA 95051", title: "Santa Clara", subtitle: "zip: 95051", url: "/app/GeoLocation/show?city=Santa%20Clara"} + ] + }; + Rho.MapView.create(map_params); + +You can enable file caching for map tiles - file cache can use for offline map browsing. + + :::ruby + MapView.set_file_caching_enable(1) + +Preload map tiles for region (0<=zoom<=18): + :::ruby + def preload_callback + puts '@@@@@@@@@ Preload Callback STATUS['+@params['status']+'] PROGRESS['+@params['progress']+']' + end + + def preload_map + options = { :engine => 'OSM', + :map_type => 'roadmap', + :top_latitude => 60.1, + :left_longitude => 30.0, + :bottom_latitude => 59.7, + :right_longitude => 30.6, + :min_zoom => 9, + :max_zoom => 11 + } + total_tiles_for_preload_count = MapView.preload_map_tiles(options, url_for(:action => :preload_callback)) + redirect :action => :index + end + +### Sample +See GeoLocation/controller.rb of [system API sample application](http://github.com/rhomobile/rhodes-system-api-samples/tree/master/app/GeoLocation/controller.rb) for some of the examples of how to use MapView class. diff --git a/docs/en/5.5/guide/media.md b/docs/en/5.5/guide/media.md new file mode 100644 index 00000000..7fdb84f6 --- /dev/null +++ b/docs/en/5.5/guide/media.md @@ -0,0 +1,98 @@ +# Media Support & Ringtones + +The MediaPlayer extension is used to playback different types of audio files. It also allows the playback of Ringtones for the respective platform. + +##Enabling the API + +In order to use this API you must include the following extension in your build.yml

                                                                            + + :::yaml + extensions: ["mediaplayer"] + + +## Playing Audio +Playing audio files is accomplished using the [Mediaplayer API](../api/mediaplayer) + +JavaScript + :::javascript + var platform = Rho.System.platform; + var audiolocation = ""; + + if (platform == "WINDOWS") + { + audiolocation = "\\thermo.wav"; + } + else if (platform == "ANDROID") + { + audiolocation = "/mnt/sdcard/test.mp3"; + } + + Rho.Mediaplayer.start(audiolocation); + +The [Mediaplayer.start](../api/mediaplayer#mstartSTATIC) method is used and is passed the full path to the audio file. On iOS when you pass a URL (http) to a remote file on a server, then we open the default browser for playing it. + +**NOTE: On iOS we support: mp3, mp4, wav formats. On other platforms the formats supported depend on what support is built into the platform. Typically on WM/CE this will be wav and on Android mp3 ** + +###Playing audio via native browser +Rhodes can play video/audio files in native Internet Browser. So application developer can just add link to online or local audio/video file: + :::html + Play mp4 online video + +**NOTE: You can also have your application download file to file system using [AsyncHttp.download_file](web_services) and then use a local url link [to this file](#file-system-access) to play. + +## Playing Video +Playing video files is accomplished using the [Mediaplayer API](../api/mediaplayer) + +JavaScript + :::javascript + var platform = Rho.System.platform; + var videolocation = ""; + + if (platform == "WINDOWS") + { + videolocation = "\\test.mp4"; + } + else if (platform == "ANDROID") + { + videolocation = "/mnt/sdcard/test.mp4"; + } + + Rho.Mediaplayer.startvideo(videolocation); + +The [Mediaplayer.start](../api/mediaplayer#mstartvideoSTATIC) method is used and is passed the full path to the video file. On iOS when you pass a URL (http) to a remote file on a server, then we open the default browser for playing it. + +**NOTE: On iOS we support: mov, mp4, 3gp formats. On other platforms the formats supported depend on what support is built into the platform. Typically on WM/CE this will be wav and on Android mp4 ** + +##Ringtones +Accessing ringtones on the device is accomplished via the [Mediaplayer](../api/medialplayer) API. + +### Getting available ringtones +The [Mediaplayer.getAllRingtones()](../api/mediaplayer#mgetAllRingtonesSTATIC) is used to find out all of the available ringtones on the device + +JavaScript + :::javascript + // Use getAllRingtones method + Rho.Mediaplayer.getAllRingtones(ringtones_callback); + +This will return an array of objects with a `name` and `fullname` property. + :::javascript + function ringtones_callback(ringtones) { + + var result = ""; + for (var i = 0; i < ringtones.length; i++) { + var name = ringtones[i].name; + result += '
                                                                          • ' + name + '
                                                                          • '; + } + + $(".ui-page-active ul.ringtone_list").html(result); + } + +You can then use the [Mediaplayer.playRingTone](../api/mediaplayer#mplayRingToneSTATIC) method to play the ringtone by name + + :::javascript + function play_ringtone(name) { + //name should be a valid name returned from getAllRingtones + Rho.Mediaplayer.playRingTone(name); + + } + diff --git a/docs/en/5.5/guide/native_extensions.md b/docs/en/5.5/guide/native_extensions.md new file mode 100644 index 00000000..b985a001 --- /dev/null +++ b/docs/en/5.5/guide/native_extensions.md @@ -0,0 +1,837 @@ +# Building a native extension + +## Introduction + +RhoMobile provides you with access to a wide variety of features offered by the device your application runs on, such as [sensors](../api/sensor) or [barcode scanners](../api/barcode). If you need to interact with the native platform in a way that the public RhoMobile APIs do not address, it is time to build a native extension. + +**NOTE: Native extensions are used only when strictly necessary. If you need to add functionality to your application and a compatible Ruby gem or JavaScript library is available, these are usually preferable.** + +## Overview + +The process of building a native extension involves + +* Using a code generator to build an XML descriptor that contains the structure of your new API +* Updating the template to add the names and features of the methods your API will provide +* Running the code generator to create stub implementations for the different platforms +* Implementing your API on the platform(s) you intend to support in native code. +* Adding the new extension to your build.yml so that it is available in your application + + +## Getting started - Basic extension walkthrough + +**NOTE: This guide contains a walkthrough of creating the simplest possible extension, and then progressively adding more features to it. If you need to build an extension for your application and have not done so before, it is recommended that you do not skip ahead but instead read the whole guide in order, as each section builds on the steps and knowledge acquired in the sections that came earlier.** + + +We will begin by creating a sample "Greeting" extension. Our target is to have a new API available as `Rho::Greeting` (Ruby) or `Rho.Greeting` (JavaScript) with the following methods: + +* welcome(username) +* farewell(username) + +These methods will be `static`, that is, they can be called directly on the Greeting class in the same way you can call methods on [Rho::Log](../api/Log) + +Ruby: + :::ruby + greeting = Rho::Greeting.welcome("John Doe") # <= "Welcome, John Doe" + farewell = Rho::Greeting.farewell("Jane Doe") # <= "Farewell, Jane Doe" + +JavaScript: + :::javascript + var greeting = Rho.Greeting.welcome("John Doe") // <= "Welcome, John Doe" + var farewell = Rho.Greeting.farewell("Jane Doe") // <= "Farewell, Jane Doe" + + +From the console, change into your application's directory and run: + + :::console + rhodes extension greeting + +this will create the initial set of files for the new extension. Open the new `extensions/greeting` folder and you will find: + +* ext.yml - you do not normally need to modify this file +* public/api/generated/Rho.Greeting.js - automatically generated JavaScript bindings +* ext/platform - one folder for each supported platform (android, iphone, wm, wp8) +* ext/shared/generated - automatically generated glue code +* ext/greeting.xml - API descriptor. This is where you define which methods your API provides, the parameters they expect and the result they return, as well as provide user documentation. + +**NOTE: Whenever you see a directory named `generated`, keep in mind that everything it contains can be overwritten by the code generator on subsequent runs. Consider these directories as "read-only", do not modify any of these files because your changes will be lost.** + +## Adding an extension to your application + +Merely creating an extension does not automatically include it in an application: you still need to edit the `build.yml` file and add it: + + :::yaml + extensions: + - greeting + +## Overview of the API descriptor (XML) file + +The API descriptor (`extensions//ext/.xml`) contains all the information required by the `rhodes` code generator to build a basic template that you can then implement for each platform. The default descriptor that is generated contains some sample methods that serve as documentation and starting point for your own. The structure of the API descriptor is as follows: + + :::xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Sections marked "documentation" are meant to be user-readable, while ``, ``, ``, `` and `` drive the code generation and implementation of the extension. + +**NOTE: The set of attributes supported by each of these tags is fully documented in [Reference: the API descriptor in depth](#reference-the-api-descriptor-in-depth). The basic extension shown in this guide does not make use of every feature.** + +The default descriptor already contains a set of methods and includes some templates. For simplicity, instead of using the default, we will start from the smallest possible descriptor and add features to our extension gradually. This will let you see how all the pieces fits together and what each change provides; once you start to build a real extension, you will know what you can save from the default and what has to be removed for your particular case. + +Keep a mental note of the methods that the default descriptor includes (`getPlatformName`, `calcSumm`, `joinStrings`) and +replace the contents of your greeting.xml file with the following: + + :::xml + + + + + Example extension api + This is example of API. Implementation contain in extension. + + + + + + + + + + + + + + + Warm welcome for the user + + + + + + + + 1.0.0 + + + + + + +From the command line, switch to the `extensions/greeting/ext` folder and run + + :::console + rhodes api greeting.xml + +**NOTE: Every time you make changes to the API descriptor and regenerate files, run the appropriate rake clean task (i.e., `rake clean:android` or `rake clean:iphone`) before building your application, otherwise you may sometimes experience compilation errors.** + +This command processes the descriptor and rebuilds the auto-generated files. You are now ready to start adding your implementation. + +## High-level structure of extensions + +The `rhodes` command builds a set of files for each platform, divided in two sets: + +* Base classes and interfaces to use in your own implementation. These are regenerated automatically. +* Implementation classes. These contain your custom code. They must implement / extend the autogenerated base classes and are generated only the first time: when you make changes to the API descriptor and re-run the `rhodes` command, you will also need to make the appropriate changes to these files manually. + + +Depending on the platform you are working on, complete one of the following sections: + +### Android + +Android extensions place their generated base classes and interfaces in `/ext/platform/android/generated` and your implementation in `/ext/platform/android/src` + +Open `extensions/greeting/ext/platform/android/generated/src/com/rho/greeting/IGreetingSingleton.java` and you will see it declares a very simple interface with a single method, `welcome`, that takes a `String` parameter called `user`, like you specified in the API descriptor. + +However, instead of returning `String` like you would expect from the declaration, it is `void` and instead takes a second parameter called `result` of type `IMethodResult`. All methods in your extension will follow this pattern: they will be declared `void` and the `result` parameter is what allows you to return a value. + +Now open `extensions/greeting/ext/platform/android/src/com/rho/greeting/GreetingSingleton.java`. This class is declared to implement the `IGreetingSingleton` interface we just saw in the previous step but it will not compile in its present form. This is an implementation class, which means it was autogenerated the first time but it is now up to you to make the relevant changes to implement the API correctly. + +In order to do that: + +* remove all existing methods +* add the missing method: + + :::java + @Override + public void welcome(String user, IMethodResult result) { + result.set("Welcome, "+user); + } + +Remember that the API descriptor initially had some methods (`getPlatformName`, `calcSumm`, `joinStrings`) that are no longer present. For the extension to build cleanly, you must remove these methods from `android/src/com/rho/greeting/Greeting.java` + + +### iOS + +iOS extensions place their generated base classes and interfaces in: + +* `/ext/platform/iphone/generated/base_impl` +* `/ext/platform/iphone/generated/stub_impl` + +Your code must be located in `/ext/platform/iphone/impl` + +Open `stub_impl/GreetingSingleton.h` and copy the `welcome` method to `impl/GreetingSingleton.h`, removing the other methods that are present. Do the same between `stub_impl/GreetingSingleton.m` and `impl/GreetingSingleton.m`, fleshing out the method like this: + + -(void) welcome:(NSString*)user methodResult:(id)methodResult { + [methodResult setResult:[@"Welcome, " stringByAppendingString:user]]; + } + +You will have noticed that, although the API descriptor declared that the `welcome` method takes a single parameter (`user`)and returns a `String`, the generated method takes two parameters (`user` and `methodResult`) and returns void. All extension methods will follow this pattern of being void and receiving an extra parameter of type `IMethodResult` to return a value. + +However, instead of returning `String` like you would expect from the declaration, it is `void` and instead takes a second parameter called `result` of type `IMethodResult`. All methods in your extension will follow this pattern: they will be declared `void` and the `result` parameter is what allows you to return a value. + +### Windows Mobile + +The `rhodes` tool creates a Visual Studio solution project in `extensions/greeting/ext/platform/wm/Greeting.sln`. When you open it in VS 2008, you will see it contains `Greeting_impl.cpp", which is where implementation code is added for any methods declared in the API descriptor, and `shared/generated/cpp` which contains the base classes and interfaces that your implementation must extend. + +Open `shared/generated/cpp/IGreeting.h` and you will find that `IGreetingSingleton` declares the `welcome` method defined in the API descriptor, with some differences: it is `void` instead of returning a `String` and it has an extra parameter of type `rho::apiGenerator::CMethodResult&` called oResult. Extension methods will follow this pattern of being `void` and taking an extra CMethodResult parameter which lets you return a value to the caller. + +In `Greeting_impl.cpp`, update class `CGreetingSingleton` to match the following: + + :::cplusplus + class CGreetingSingleton: public CGreetingSingletonBase + { + ~CGreetingSingleton(){} + + public: + void welcome( const rho::String& user, rho::apiGenerator::CMethodResult& oResult) { + oResult.set("Welcome, "+user); + } + }; + +All you need to do is remove the methods called `getInitialDefaultID` and `enumerate` (these were generated automatically but they do not apply to our extension) and add an implementation of `welcome` with the signature found in `shared/generated/cpp/IGreeting.h` + + +## Invoking the new extension + +Now that the native part of the extension is implemented, you can start to use it in your application. Open `app/index.erb` and edit the `content` div to match the following: + + :::html +
                                                                            + <%= Rho::Greeting.welcome("John doe") %> +
                                                                            + +Make sure you [added the extension to build.yml](#Adding-an-extension-to-your-application) and run your application. You will see the extension in action, returning the value as you would expect, exactly like any other API call. + +The build system creates all the initialization and glue code so that your extensions are available from both Ruby and JavaScript code automatically. The following code will also work: + + :::javascript + alert(Rho.Greeting.welcome("John doe")); + + +## A deeper look into the two approaches to developing extensions. Singleton and Factory + +Now that you have a good overview of how to build a simple extension, you can expand your knowledge with more advanced concepts. + +The basic extension you just developed followed the "singleton" pattern, which means you don't create instances of the `Greeting` class but instead just call methods on it. This is how `Rho.Log` works and is appropriate when it does not make sense to have more than one instance of a particular object. + +Another approach is also supported, the "factory" pattern. This is how many other RhoMobile APIs work like [Barcode](../api/barcode) and [Camera](../api/Camera) are implemented: there may be more than one barcode scanner or camera present in a device, so you can enumerate them and get a different instance representing each of them. + +Which pattern you use depends on what exactly your extension needs to achieve and is a decision that must be taken early. + +In order to create a `Factory`-style extension, you will typically: + +* Keep `` inside the `` section of the API descriptor +* Keep the `enumerate` method +* Implement a set of `instance` methods and add the same methods as `static` also, with the implementation delegating to a default instance. + +The starter API descriptor builds Factory-style extensions by default. Now that you know what each piece of the puzzle means, you are ready to understand how the generated implementation works and use it as a base for your own extension. + +## Using callbacks + +There are many methods in the RhoMobile standard APIs that, instead of returning a value immediately, receive a callback parameter and invoke it when the value is available. For example, [Barcode.take](../api/barcode#mtake) receives a `hash` of properties to configure the scanner and a `callback` that will be executed when the scanner reads a barcode or times out. + +The `` tag in the API descriptor accepts a `hasCallback` attribute with one of the following values: `none`, `optional`, `mandatory`. See the documentation for the `` tag for reference + + +## Returning values + +The implementations of all native methods in an extension follow the same pattern: + +- they are declared as `void` +- their last parameter is a special `MethodResult` object, used as a conduit to return values + +If your return value is a primitive or simple type (number, string), you can call `methodResult.set` directly as in the examples above. If you need to return a composite object such as a `hash` or an `array`, there are some special type mappings to take into account. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                            + In order to return + + On + + Use + + Example +
                                                                            Primitive types, strings + All platforms + the raw value + +
                                                                            + Java: +
                                                                            + methodResult.set(42); +
                                                                            + methodResult.set("Welcome"); +
                                                                            +
                                                                            + Objective-C: +
                                                                            + [methodResult setResult:42]; +
                                                                            + [methodResult setResult:@"Welcome"]; +
                                                                            +
                                                                            + C++: +
                                                                            + oResult.set(42); +
                                                                            + oResult.set("Welcome"); +
                                                                            +
                                                                            +
                                                                            Array + Android + + java.util.List + +
                                                                            + + List myList = new LinkedList();
                                                                            + myList.add(42);
                                                                            + myList.add(7);
                                                                            + methodResult.set(myList);
                                                                            +
                                                                            +
                                                                            Array + iOS + NSArray + +
                                                                            + + NSArray* array = [NSArray arrayWithObjects:
                                                                            + @"String1",
                                                                            + @"String2",
                                                                            + nil];
                                                                            + [methodResult setResult:array];
                                                                            +
                                                                            +
                                                                            Hash + Android + java.util.Map + +
                                                                            + + Map map = new java.util.HashMap();
                                                                            + map.put("key1", "value1");
                                                                            + map.put("key2", "value2");
                                                                            + methodResult.set(map);
                                                                            +
                                                                            +
                                                                            Hash + iOS + NSDictionary + +
                                                                            + + NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                                                            + @"value1", @"key1", @"value2", @"key2", nil];
                                                                            + [methodResult setResult:dict];
                                                                            +
                                                                            +
                                                                            + + +## Reference: The API descriptor in depth + +### MODULE + +The `` tag describes the API class you are building + +Attributes: + +* `name`. Mandatory. Contains the name of the generated API +* `parent`. Optional. If present, the generated API will created inside the specified namespace. +* `generateUnderscoreRubyNames`. Optional, default is `false`. If true, ruby method names will be created with underscores between words instead of camel case +* `generateDoc`. Optional, default is `true`. If false, the module is considered to be internal and will not be documented. + +Examples: + + :::xml + + + + + + + + + +### ALIAS + +The `` tag registers alternative names for a module, property or method + +Examples: + + :::xml + + + + + +### TEMPLATES + +Templates add default behavior to modules, based on the templates present [here](https://github.com/rhomobile/rhodes/tree/master/res/generators/templates/api/xml_templates). + + +#### DEFAULT_INSTANCE + +The `DEFAULT_INSTANCE` template is appropriate for factory-style modules. It provides static methods in your module class that delegate to the instance returned by `getDefault` (and which can be changed with `setDefault`). For example, the [Camera API](../api/camera) lets you enumerate cameras and use one in particular to take an image but you can also call static methods directly on the `Camera` class and it will use the default camera on the device. This template provides an implementation of + +* `getDefault` +* `setDefault` + +Example: + + :::xml + + +#### PROPERTY_BAG + +The `PROPERTY_BAG` template allows your module to get and set its properties in a generic way in addition to specific property getters and setters. It provides: + +* `getProperty(name)` - get the value of a single property +* `getProperties(names)` - return a hash with the values of an array of properties +* `setProperty(name,value)` - set a single property +* `setProperties(hash)` - set multiple properties in a single call + +Example: + :::xml + + + + +### CONSTANTS + +Container for `` elements + +#### CONSTANT + +Defines a Ruby and JavaScript constant in a module + + :::xml + + + + + +### PROPERTIES + +Declare properties of your module, either on instances or for static access, with the `` tag + +#### PROPERTY + + + :::xml + + + + + + + + + +The above results in the following properties being accessible: + + :::javascript + // JavaScript code + Rho.Example.customProperty="exampleValue"; // static access + Rho.Example.getDefault().color="#FF0000"; // instance access + +The `` tag accepts several attributes apart from `name`: + +* `access` : either `"STATIC"` or `"INSTANCE"`, describes how the property is accessed +* `usePropertyBag` : one of + - `none` : any generated property bag code will not integrate this property + - `accessorsViaPropertyBag` : `get` and `set` will delegate to `getProperty` and `setProperty` + - `propertyBagViaAccessors` : `getProperty` and `setProperty` will delegate to `get` and `set` +* `nativeName` : the actual name used for the `get` and `set` methods. Example: + + :::xml + + + Will be used like: + + :::javascript + var color = Rho.Example.getredgreenblue(); + Rho.Example.setProperty("color","#FF0000"); + +* `generateAccessors` : defaults to true, set to false if you do not need the `get` and `set` methods +* `type` : the type of the property (`"STRING"`, `"INTEGER"`, etc.) +* `readOnly` : defaults to false, determines whether the `set` method will be generated and makes `setProperty` throw an exception +* `default` : the default value for the property +* `generateAPI` : defaults to true; if set to false the generator will not create `get` and `set` methods, you will have to implement them in Ruby and JavaScript yourself +* `runInThread` : affects the thread that the `set` method runs in: + - `none` : no special threading + - `module` : the method runs in a per-module thread + - `separate` : a new thread is launched for each method invocation + - `ui` : the method runs on the UI thread + + +### VALUES + +If a property (``) only accepts a predefined set of values, use the `` and `` tags: + + :::xml + + + + + +The accepted attributes of the `` tag are: + +* `value` : mandatory +* `type` : optional, defaults to `"STRING"`. Any basic type (`STRING`, `INTEGER`, `BOOLEAN`, `FLOAT`) can be used +* `constName` : optional; if specified, the generator will create static constants in the module file + +The above snippet will produce the following code for Android: + + :::java + public interface IGreetingSingleton + { + + static final String WIDTH_WIDE = "WIDE"; + static final String WIDTH_NARROW = "NARROW"; + } + +iOS: + :::c + #define WIDTH_WIDE @"WIDE" + #define WIDTH_NARROW @"NARROW" + + +### METHODS + +The `` tag contains one `` subtag for each method you implement in your extension + +`` recognizes the following attributes: + +* `name` : mandatory, the name of the method in Ruby / JavaScript +* `nativeName` : if present it will override `name` as the name of the native method. Otherwise, the name will be generated by removing invalid symbols from `name` for each platform. +* `hasCallback` : defaults to `"none"` + - `hasCallback="none"` (the default): the method will return a result value synchronously + - `hasCallback="mandatory"` : the method will never return a value and will always invoke its callback + - `hasCallback="optional"` : if a callback is present, it will be used, otherwise, the method will return its result synchronously + +* `runInThread` : affects the thread that the method runs in. Defaults to `"module"` if a callback is present + - `none` : no special threading, the method runs in the current thread even if a callback is present + - `module` : the method runs in a per-module queue thread + - `separate` : a new thread is launched for each method invocation + - `ui` : the method runs on the UI thread + +If the method runs in a thread (any value other than `"none"`, it can only return a result via callback. If the callback is absten, the return value will be lost) + +* `deprecated` : defaults to `false`. Document the method as deprecated +* `generateAPI` : defaults to `true`. If `false`, no native code will be generated for the method and you will need to implement it in Ruby and JavaScript yourself. +* `generateDoc`: defaults to `true`. If `false`, the module is considered to be internal and will not be documented. +* `access`: defaults to `"INSTANCE"`. If set to `"STATIC"`, the method will be available for static calls via the module class. +* `generateNativeAPI`: defaults to `true`. If `false`, native C wrappers for Ruby and JavaScript will not be created. +* `constructor`: defaults to `false`. If `true`, the method will be called from the constructor when an object is instantiated +* `destructor`: defaults to `false`. If `true`, the method will be called from the destructor when an object is released + +#### PARAMS + +The `` tag declares the parameters that a `` accepts + + :::xml + + + + + + + + + + + + +`` accepts these attributes and subtags: + +* `name`: determines the name of the parameter in the native implementations +* `type`: defaults to `STRING`, can be any of: `STRING`, `INTEGER`, `BOOLEAN`, `FLOAT`, `HASH`, `ARRAY` +* `propertyHash`: defaults to `false`, only valid for `type="HASH"`. If `true`, the hash will be converted internally to use values declared in `` tags +* `default`: specify the default value of the parameter if none is provided + +`` declares that a parameter is optional and can be omitted + +#### RETURN + +A `` declaration may include a `` tag to specify that the method returns a value. + +Example: + + :::xml + + + description of the return value + + + +Methods that return a hash can describe which keys will be present using `` with the same syntax seen above for method parameters + + :::xml + + + description of the return value + + + + + + + + + +This also declares constants in the native implementation with the prefix HK (Hash Key): + +Android: + :::java + static final String HK_ERROR = "error"; + static final String HK_PENDING = "pending"; + static final String HK_SYNCHRONIZED = "synchronized"; + static final String HK_TOTAL = "total"; + +C++: + + :::cplusplus + static const char HK_ERROR[] = "error"; + static const char HK_PENDING[] = "pending"; + static const char HK_SYNCHRONIZED[] = "synchronized"; + static const char HK_TOTAL[] = "total"; + + +#### CALLBACK + +Whenever a method accepts a callback, it must be documented with the `` tag: + + :::xml + + + ... + + + + + + + + + + +The `` tag uses exactly the same syntax as ``. + +## Platform-specific notes + +### Android + +* `ext/platform/android/ext_java.files` contains a list of the files that are required for an extension to build. If you add new Java files to your extension, you must add them to this list also or they will not be found at compile-time. + +* Making changes to application AndroidManifest.xml + +You can specify changes to AndroidManifest.xml in the ext.yml file as a list of paths to the files containing change instructions. There are three formats recognized by the build system, depending on the file extension: + +* .xml - xml file with common AndroidManifest.xml format; its tags will be merged into the final manifest. +* .erb - ruby templates which will be injected into the final manifest. +* .rb - ruby script which will run by the manifest erb generator. + + android: + manifest_changes: + - ext/yourextension/platform/android/AndroidManifestAdds.xml + - ext/yourextension/platform/android/ApplicationTagAdds1.erb + - ext/yourextension/platform/android/ApplicationTagAdds2.erb + - ext/yourextension/platform/android/ManifestTagAdds.erb + - ext/yourextension/platform/android/AndroidManifestScript.rb + +#### XML + +This is the simplest way, if you know how your manifest has to look. Add the final AndroidManifest.xml to the extension and specify it in ext.yml. +The build system will try to merge all the tags from the file into the final AndroidManifest.xml. If a particular tag exists both in the default Rhodes manifest as well as in the extension, the extension manifest takes priority and will overwrite the default. + + android: + manifest_changes: ext/yourextension/platform/android/AndroidManifest.xml + +#### ERB template + +There are two common levels where additional definitions can be injected into AndroidManifest.xml. + +* Application tag +* Manifest tag + +To add additional definitions to the Application tag, the template name must fit the file name mask of `Application*.erb`, such as `ApplicationManifestAdds.erb`. + +To add additional definitions to Manifest tag, the template name must fit the file name mask of `Manifest*.erb`. + +There may be a number of templates of each type. +In the template, you may access manifest generator fields which hold values that are frequently-used in manifest generation. The list of available values is documented below, under the heading "ERB Manifest Generator". + +Below is example of a broadcast receiver definition added to 'application' tag by rhoconnect-push extension: + + :::xml + + + + + + + + + + + + + + +#### RB script + +In case the methods listed above are not enough, you can write your own script that will change the values used to generate the manifest. +You can have a single script per extension. + +In the script, you may access the ERB generator instance as a local variable. + + :::ruby + generator.permissions["#{generator.appPackageName}.permission.ANS"] = 'signature' + generator.usesPermissions << "#{generator.appPackageName}.permission.ANS" + generator.usesPermissions << 'com.motsolutions.cto.services.ans.permission.REGISTER' + +#### ERB Manifest Generator + +The following generator fields may be accessed from erb templates or scripts. + +* javaPackageName - read-only string +* appPackageName - read-only string +* versionName - read-write string +* versionCode - read-write string +* installLocation - read-write string +* minSdkVer - read-write string +* maxSdkVer - read-write string +* permissions - hash of permission name/protectionLevel pairs +* usesPermissions - array of permission names +* usesLibraries - hash of library name/isRequired pairs +* screenOrientation - read-write string +* debuggable - read-write string (allows two values: 'true' or 'false') +* rhodesActivityIntentFilters - array of hashes with filter values. Each hash can contain next keys: +** :act - string, intent action name +** :cat - array of strings with category names +** :data - hash with data tag attributes (name/value pairs) +* manifestManifestAdds - array of strings with full paths to erb templates for 'manifest' tag +* applicationManifestAdds - array of strings with full paths to erb templates for 'application' tag + +For more details about the values for the generator fields, refer to [Android Developer Documentation](http://developer.android.com/guide/topics/manifest/manifest-intro.html). + +You may also look in your Rhodes installation under /platform/android/Rhodes/AndroidManifest.xml.erb to study how these values are used. + +## Platform Notes + +### Using Resources + +If you want to use any resources in your code, use com.rhomobile.rhodes.R instead of just R. This will make all resources (include your additonal resources) accessible from this R file. + +### Calling JNI Functions at Android + +If you need to call JNI functions from your native code, you need to retrieve the `JNIEnv *env` variable. To get it, include the file `RHO_ROOT/platform/android/Rhodes/jni/include/rhodes.h` in your C/C++ files. The global function `JNIEnv *jnienv()` is defined in this file, so use it anywhere when `JNIEnv *`is needed. + +### Using Prebuilt Libraries (jars) + +If your native extension uses prebuilt libraries (jars), your build script must copy all such jar files to the TARGET_TEMP_DIR. The jar files must have the extension '.jar'; RhoMobile will include these files automatically in the final build. + +### Creating Native Threads + +If your native extension creates a native thread (using pthread_create, for example), this thread should be attached to the JVM so that it can call Java methods from its context. Do this by using the rho_nativethread_start/rho_nativethread_end functions, called at the start/end of your thread routine. + +Example: + + :::cpp + void *thread_routine(void *arg) + { + void *q = rho_nativethread_start(); + ..... + rho_nativethread_end(q); + return NULL; + } + +Otherwise, if the thread is not attached to the JVM, no JNI calls should be performed in its context (otherwise it will cause your application to crash). + +### Providing Additional DLLs for Windows Mobile + +If your application needs additional DLLs, put them in the TARGET_TEMP_DIR. The Rhodes build scripts will detect them and include them in the final binary automatically. + diff --git a/docs/en/5.5/guide/native_ui_elements.md b/docs/en/5.5/guide/native_ui_elements.md new file mode 100644 index 00000000..0736d727 --- /dev/null +++ b/docs/en/5.5/guide/native_ui_elements.md @@ -0,0 +1,371 @@ +# Using native UI elements + +## Overview + +Apart from the regular `WebView` component that contains your HTML, CSS and JavaScript code, RhoMobile also includes some platform-native components that make your app act like other applications users are already accustomed to. When used properly, these components help you make navigation easier, improve accessibility and shorten the learning curve for your users. + +## NativeTabbar + +By default, there is only one `WebView` component in a RhoMobile application. On startup, it loads the `start_path` url specified in `rhoconfig.txt` and displays the corresponding HTML. However, it is possible to have more than one `WebView` in the same application: `NativeTabbar` allows you to create several independent `WebView`s, each inside its own tab and selectable by the user. + +**NOTE: On Windows Mobile, NativeTabbar, despite the name, does not actually show any visible tabs. In order to switch tabs, you must do it in code** + +### Usage + +`NativeTabbar`s can be created and removed dynamically at runtime. To create a `NativeTabbar`, invoke [NativeTabbar.create](../api/NativeTabbar#mcreate) with the appropriate parameters: + +* An array of tabs, with each element describing one of the tabs +* Global tab properties +* A callback function to be invoked when the user switches tabs + +Ruby: + + :::ruby + Rho::NativeTabbar.create( + # Tabs array + [ + # First tab - we have specified our application's start path but it could be anything + { + :label => "Home", + :action => Rho::Application.startURI + }, + + # Second tab - invoke an action in a controller + { + :label => "Do something", + :action => url_for(:controller => :MyController, :action => :my_action) + }, + + # Third tab - an external site + { + :label => "example.com", + :action => "http://www.example.com" + } + ], + + # Global tab properties + { + :createOnInit => true + }, + + # Callback + url_for(:controller => :MyController, :action => :tabbar_callback) + ) + + def tabbar_callback + Rho::Notification.showPopup("Switching to tab #{@params["tab_index"]}") + end + + +JavaScript: + + :::javascript + Rho.NativeTabbar.create( + // Tabs array + [ + // First tab - we have specified our application's start path but it could be anything + { + label : "Home", + action : Rho.Application.startURI + }, + + // Second tab - invoke an action in a controller + { + label : "Do something", + action : "/app/MyController/my_action" + }, + + // Third tab - an external site + { + label : "example.com", + action : "http://www.example.com" + } + ], + + // Global tab properties + { + createOnInit : true + }, + + // Callback + tabbar_callback + ); + + function tabbar_callback(params) { + Rho.Notification.showPopup("Switching to tab "+params.tab_index); + } + +![NativeTabbar](http://rhodocs-images.s3.amazonaws.com/guide/native_ui_elements/nativetabbar.png) + +Apart from `label` and `action`, there are more properties you can specify for each tab, including `icon` and `disabled` among others. Refer to [NativeTabbar.create](../api/NativeTabbar#mcreate) for the complete list. + +Once you have more than one tab and therefore more than one `WebView`, the [WebView API](../api/webview) can be used to control each of them independently. A regular call would be + + :::javascript + Rho.WebView.navigate("http://www.example.com") + +That code does not indicate which `WebView` to operate on, so it applies to whichever `WebView` is currently active. However, you can cause a different `WebView` to be affected instead: + + :::javascript + // Direct the third WebView to example.com + Rho.WebView.navigate("http://www.example.com",2) + + +### Use cases + +* An additional tab can provide users with a way to quickly access instructions or cross-reference documentation, as well as help validate data before saving. For example, if your application required users to capture information in different physical locations, you could have the data capture forms in one tab, a map on another and the instructions for the current location on a third tab. + +* As can be seen in the example above, the `:action` of a tab does not necessarily have to link to an internal URL in your application. This can be leveraged to provide side-by-side documentation from a website, which can be updated frequently without requiring redeployment of the RhoMobile application. + + +### Considerations + +* Each `NativeTabbar` creates its own `WebView`, which consumes a fair amount of resources. On older devices, mainly on Windows Mobile, this can make the whole application run more slowly, especially if your views are complex. Be sure to test on a physical device to get a feel for the responsiveness of your application. + +* If you need tabs to load their contents as soon as they are created, set `createOnInit` to `true`. This will cause your application to slow down while all tabs process their requests, so it should only be used when strictly necessary. + +* Before using `NativeTabbar` for navigation, think about the tradeoff of easy access vs losing so much screen real estate on a small screen plus increased memory usage. If it fits your application, create the `NativeTabbar` when needed and call [NativeTabbar.remove](../api/NativeTabbar#mremove) when it is no longer needed, to reclaim the memory and visual space. Normally, `NativeToolbar` and `NavBar` provide a better alternative as navigation controls. + +* The `NativeTabbar` in iOS7 includes a few differences from legacy `NativeTabbar`. See the [Differences in iOS7](build_ios#differences-building-for-ios7) section in [building for iOS](build_ios) for details and examples. + +## NativeToolbar + +A `NativeToolbar` is a container for buttons that remain visible at all times and provide shortcuts to actions in your application. + +### Usage + +Ruby: + :::ruby + Rho::NativeToolbar.create([ + { + :label => "New product", + :action => url_for(:action => :new) + }, + { + :label => "Home", + :action => "home" + }, + { + :label => "Refresh", + :action => "refresh" + }, + { + :label => "Exit", + :action => "exit" + } + ], + {} + ) + +JavaScript: + :::javascript + Rho.NativeToolbar.create([ + { + label : "New product", + action : "/app/Product/new" + }, + { + label : "Home", + action : "home" + }, + { + label : "Refresh", + action : "refresh" + }, + { + label : "Exit", + action : "exit" + } + ], + {} + ); + +### Use cases + +* `NativeToolbar` is ideally suited for operations that may be used frequently. You can use it to provide efficient access to the key actions of your application. + +* Different areas of your application may benefit from their own shortcuts. You can create `NativeToolbar`s with specific buttons depending on the section the user is currently browsing. If you are swapping one toolbar for another, you do not need to call `NativeToolbar.remove`, `NativeToolbar.create` will replace the existing toolbar, if any. + +### Considerations + +* The toolbar does not support scrolling. If you add too many items to the toolbar, some of them will not be accessible by the user. + +* Input on a mobile device is prone to error and users will often tap the wrong button. Actions that cannot be undone or that can potentially cause data loss must provide a confirmation dialog before being executed. + +* The `NativeToolbar` in iOS7 includes a few differences from legacy `NativeToolbar`. See the [Differences in iOS7](build_ios#differences-building-for-ios7) section in [building for iOS](build_ios) for details and examples. + +## NavBar + +A `NavBar` is a composite navigation control with two buttons (left, right) and a title, that appears at the top of the screen and uses its two buttons to help the user move through the application. + +### Usage + +Ruby: + :::ruby + Rho::Navbar.create({ + :left => { + :label => "Home", + :action => url_for(Rho::Application.startURI) + }, + :right => { + :label => "example.com", + :action => "http://www.example.com" + }, + :title => "Hello World" + }) + +JavaScript: + :::javascript + Rho.Navbar.create({ + left : { + label : "Home", + action : "/app" + }, + right => { + label : "example.com", + action : "http://www.example.com" + }, + title : "Hello World" + }); + + +### Use cases + +* "back" and "forward" buttons in complex multi-step workflows + + +### Considerations + +* `Navbar` is only available on iOS. + +* jQuery Mobile emulates the NavBar and provides an HTML+JavaScript equivalent by default. Do not use both, as that tends to be confusing and waste screen real estate. + + +## NativeMenubar + +The `NativeMenubar` component allows you to interact with the native application menus of the different platforms. Android and Windows Mobile both have a main menu, plus WM has an extra menu that can be leveraged for less-frequently used actions when there are too many items on the main menu. + + + +### Usage + +`NativeMenu.mainMenu` and `NativeMenu.extraMenu` are simple arrays where you can add or remove items as required. Each item is represented by a `hash` with the following keys: + +* `label` : user-visible text that identifies the item +* `action` : either a callback that will be invoked when the item is selected or one of the predefined special values +* `disabled` : if present, the item will be visible but not selectable + +### Example + +Ruby: + :::ruby + def tweak_menus + Rho::NativeMenubar.extraButton = { + :label => "Extra" + } + + Rho::NativeMenubar.extraMenu = [ + { + :label => "Show alert 1", + :action => url_for(:action => :show_alert_1) + }, + { + :label => "Show alert 2", + :action => url_for(:action => :show_alert_2) + }, + { + :label => "Win the lottery", + :disabled => true # sorry! maybe in the next version. Pull requests welcome + } + ] + + end + + def show_alert_1 + Rho::Notification.showPopup({ + :message => "This alert was invoked from a NativeMenubar item", + :buttons => ["OK"] + }) + render :action => :menubar_menu + end + + def show_alert_2 + Rho::Notification.showPopup({ + :message => "This is another alert, also called from the NativeMenubar", + :buttons => ["OK"] + }) + render :action => :menubar_menu + end + + def remove_menuitems + Rho::NativeMenubar.extraMenu = [] + render :action => :menubar_menu + end + + +JavaScript: + :::javascript + function show_alert_1() { + alert("This alert was invoked from a NativeMenubar item"); + } + + function show_alert_2() { + alert("This is another alert, also called from the NativeMenubar"); + } + + function create_menuitems() { + Rho.NativeMenubar.extraButton = { + label : "Extra" + }; + + Rho.NativeMenubar.extraMenu = [ + { + label : "Show alert 1", + action : show_alert_1, + }, + { + label : "Show alert 2", + action : show_alert_2, + }, + { + label : "Win the lottery", + disabled : true // sorry! maybe in the next version. Pull requests welcome + } + ]; + } + + function remove_menuitems() { + Rho.NativeMenubar.mainMenu = []; + Rho.NativeMenubar.extraMenu = []; + } + +### Considerations + +* Use `NativeMenubar` to provide quick access to frequently-used actions, but do not rely on it to be the only way to access functionality. + +* Avoid having more than a few items in a menu. Windows Mobile allows menus to scroll if the number of items does not fit the screen but this process requires very precise aiming and is very prone to error. If you have many actions that are performed with equal frequency, consider adding a single item that takes the user to a new page with larger buttons. + + +## Predefined actions + +The following predefined strings are recognized as values for the `action` key with special meanings: + +* `separator` : inserts a separator line between items +* `exit` or `close` : quit the application +* `options` : navigate to the "settings" page as defined in rhoconfig.txt or Application.settingsPageURI +* `home` : navigate to the home page as defined in rhoconfig.txt or Application.startURI +* `refresh` : reload the current page (equivalent to [WebView.refresh](../api/webview#mrefresh)) +* `back` : navigate to the previous page (equivalent to [WebView.navigateBack](../api/webview#mnavigateBack)) +* `log` : open the log viewer dialog (equivalent to [Log.showLog](../api/Log#mshowLog)) +* `fullscreen` : toggle fullscreen mode (equivalent to [WebView.fullScreen](../api/webview#pfullScreen)) +* `sync` : invoke [RhoConnectClient.doSync](../api/RhoConnectClient#mdoSync) +* `minimize` : invoke [Application.minimize](../api/Application#mminimize) +* `SIP` : toggle the on-screen virtual keyboard (WM only) + + +## Related reading + +* [NativeTabbar](../api/NativeTabbar) +* [NativeToolbar](../api/NativeToolbar) +* [NativeMenubar](../api/NativeMenubar) +* [WebView](../api/webview) diff --git a/docs/en/5.5/guide/nativesdksetup.md b/docs/en/5.5/guide/nativesdksetup.md new file mode 100644 index 00000000..19d74a65 --- /dev/null +++ b/docs/en/5.5/guide/nativesdksetup.md @@ -0,0 +1,104 @@ +# Native SDK Setup +This page describes how to setup the underlying native SDKs when building a RhoMobile application locally for our supported platforms: iPhone, RIM Blackberry, Windows Mobile and Android. + +## Setup for iOS +In order to build an iOS application locally, it must be performed on a Macintosh computers or by using [RhoHub](http://rhohub.com) using any type of type of laptop/desktop. The instructions below describe how to do this from either the Macintosh Xcode development environment or from the command line on your local Macintosh. + +### Prerequisites +To build for iPhone/iPad using you will need the following software installed: + +* Mac OS X 10.6 or greater. +* XCode 4.2 or greater +* XCode Command Line Tools (already included in versions of XCode before 4.3) should be installed manually from XCode 4.3 - see Note below. +* iPhone SDK. We recommend installing the latest XCode with the latest iOS SDK (the latest XCode is already included with the iOS SDK). The latest stable version is available from the [iPhone Dev Center](http://developer.apple.com/iphone/index.action). + +> Note: In XCode 4.3, command line tools are not included in the installation. You should install the command line tools from XCode by using the Components tab of the Downloads preferences panel. See [New Features in Xcode 4.3](https://developer.apple.com/library/ios/#documentation/DeveloperTools/Conceptual/WhatsNewXcode/Articles/xcode_4_3.html) + +## Setup for Android +### Setting Up the Android SDK and NDK +Check that your [OS is compatible with the Android SDK](http://developer.android.com/sdk/requirements.html). + +1) Download the [Android SDK](http://developer.android.com/sdk/index.html), and unzip it to the location of your choice. + +> Note: A minimum Android API level 10 must be installed. + +On Macintosh and Linux, navigate to and run `/tools/android sdk`. On Windows, navigate to and run /SDK Manager.exe. The Android SDK Manager window appears. Then perform the following steps: + + * Select Settings, then check "check `Force https://... sources to be fetched using http://". + * Run Android SDK Manager, check latest Android SDK Platform(s) and Google APIs, then click "Install packages" button to download and install them. + +> Note: To use Google Map View you need to install latest Google API from Android SDK Manager + +2) Download and unzip the [latest Android NDK](http://developer.android.com/sdk/ndk/index.html) to the location of your choice. + +> Note: You should update the Android SDK and NDK as you update to new versions of Rhodes. Android NDK version r8e is required as a minimum. + +NOTE: RMS 5.1 does not support Android NDK r10; Android NDK r9 is current recommendation. + +Download Android NDK r9 from Google's servers: + +* [for Linux](http://dl.google.com/android/ndk/android-ndk-r9-linux-x86.tar.bz2) + +* [for Mac OS X](https://dl.google.com/android/ndk/android-ndk-r9d-darwin-x86_64.tar.bz2) + +* [for Windows](http://dl.google.com/android/ndk/android-ndk-r9d-windows-x86_64.zip) + + +3) The Android Support Library must be installed using the latest version. (Minimum Rev 14). This can be installed using the Android SDK Manager under the `Extras` folder. + +In RhoStudio -> Preferences on the Macintosh or Windows -> Preferences on Windows, open Rhomobile->Android and set the paths to your Android SDK and NDK installations. + +![img](http://rhodocs.s3.amazonaws.com/rhostudio-tutorial/preferences-android-sdk-4.0.png) + +If you are not using RhoStudio, run rhodes-setup from the command line and set the paths to the Android SDK and NDK installations. + +### Setting up the Android Maps API +In case you are planning to work with native geo mapping (the MapView interface), you must do two things: + +* Retrieve the Android Maps API key from Google. Follow these [instructions](http://code.google.com/intl/en/android/add-ons/google-apis/mapkey.html) to get it. When key received, put it in your application's `build.yml` or share it across all your applications by adding it to `rhobuild.yml`. Note that the `apikey` value must match a certificate used to sign an application (the key is different for debug and production signed build and debug key cannot be shared between different build computers). + + android: + apikey: "GOOGLE-API-KEY-FOR-ANDROID" + +* Enable 'mapping' in your application's `build.yml` (or in `/rhobuild.yml`). In RhoStudio, you can double-click on your application's build.yml and edit from the text editor; otherwise, you can edit rhobuild.yml or build.yml from another text editor. + + android: + mapping: yes + +## Setup for Windows Mobile +Note that Windows Mobile versions of your Rhodes application must be built in a Windows environment. +### Prerequisites +Make sure you have installed the following software. Since Rhdoes builds a unified .cab file for both WM and WinCE, only the WinCE SDK is necessary for building either platform. + +* .NET Compact Framework +* For Windows Mobile and Windows CE 5.0: MC3000c50b PSDK from [Zebra Support Central](https://atgsupportcentral.motorolasolutions.com/ewa/pub/getFile.do?fileName=/ssi/emb/downloads/30XXC50BxxPS010403.exe) +* Microsoft Active Sync 4.5 for Windows XP; Windows Mobile Device Center for Windows Vista or higher +* Microsoft Device Emulator 3.0 for Windows Vista or higher +* Visual Studio 2008. +* Software for unzipping a zip file, such as [7-zip](http://www.7-zip.org/) + +> Note: It is a good idea to install Windows Mobile 6 Professional last, since it needs to be installed after Visual Studio, and since the Windows Mobile 6 Professional install process will tell you if you forgot to install any of the other prerequisites. + +## Setup for Windows Desktop +### Prerequisites +* Visual Studio 2012 SP1 (or 2008 SP1) + * Make sure that `VS110COMNTOOLS` (or `VS90COMNTOOLS`) environment variable is defined and points to the correct location, e.g. to `C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools` + +* Install [Qt libraries 5.1.1 for Visual Studio 2012](http://download.qt-project.org/official_releases/qt/5.1/5.1.1/qt-windows-opensource-5.1.1-msvc2012-x86-offline.exe) - 511 MB (or [build Qt libraries 5.1.1 for Visual Studio 2008](build_win#build-qt5-for-vs2008)) + * The Qt binaries for Visual Studio 2012 are not compatible with Windows XP. For targeting Windows XP, please refer to the [Build for Windows](build_win) instructions. + +* Create new (or update existing) system environment variable `QTDIR` and make sure it points to root folder of the installed Qt libraries, e.g. `C:\Qt\Qt5\5.1.1\msvc2012` + +>Note: If the application uses HTTPS, the Qt binaries must be built against OpenSSL. Please refer to [Build for Windows](build_win) for instructions and links to Zebra's pre-built Qt binaries. + +## Setup for Windows Phone 8 +### Prerequisites +* Windows 8.x OS +* Visual Studio 2013 installed or VS Express 2013 for Windows Phone + * [Windows Phone SDK 8.0](http://dev.windowsphone.com/en-us/downloadsdk) + +* Add path to `msbuild` to `rhobuild.yml` in rhodes folder. Use 32-bit version compiler to build for device. + + env: + paths: + msbuild: C:/Program Files (x86)/MSBuild/12.0/Bin/MSBuild.exe \ No newline at end of file diff --git a/docs/en/5.5/guide/newORM_js.md b/docs/en/5.5/guide/newORM_js.md new file mode 100644 index 00000000..fbcf11ac --- /dev/null +++ b/docs/en/5.5/guide/newORM_js.md @@ -0,0 +1,248 @@ +# Using the ORM Common API in JavaScript + +The RhoMobile Suite provides several methods of handling device data. For RhoMobile Suite 5.3 and higher is the [ORM common API](../api/NewORM), which supports JavaScript (documented here) and Ruby. RMS 5.2 and lower support the original [Rhom API](../api/rhom-api) (for Ruby) and the [ORM API](../api/Orm), which adds JavaScript support to Rhom via the [OPAL library](http://opalrb.org). + +## How to Include the ORM API + +By default, RhoMobile apps will be built to use the older Rhom implementation (for Ruby) and ORM implementation (for JavaScript). To activate the newer ORM Common API (which supports both JavaScript _and_ Ruby), add the following line to application’s `rhoconfig.txt` file: + + :::yaml + use_new_orm = 1 + +Possible Values: + +* **0 = use 'old' Rhom/ORM API (default)** +* 1 = use newer ORM Common API + +NOTE: If this parameter is left unspecified, the older Rhom/ORM API will be used. + +## Creating a JavaScript Model + +The first step in using Rhom is to create a model class with the required attributes. Models are created in JavaScript using the [ORM.addModel](../api/Orm#maddModel) method, which defines a class reference for the model and makes it available to the application. + +When the application pages load, execute the `Rho.ORM.addModel` function for every model to be defined in the application. + + :::javascript + // Models MUST be defined when your HTML pages load + + // Either set a global reference... + var userModel = Rho.ORM.addModel('User', function(model) { + model.setModelProperty('name','string',''); + model.setModelProperty('email','string',''); + // optionally enable sync for rhoconnect applications: + // model.enable('sync'); + // optionally define model as fixedSchema (default is propertyBag): + // model.fixed_schema = true); + }); + + // ...or define the model without a global reference + Rho.ORM.addModel('Product', function(model) { + model.setModelProperty('name','string',''); + model.setModelProperty('qty','string',''); + }); + + +Once created, models can be retrieved using the `ORM.getModel` method: + + :::javascript + var productModel = Rho.ORM.getModel('Product'); + +**NOTE: It is advisable to use either the Ruby or JavaScript methods for handling model definition and access. DO NOT do this from _both_ languages**. + +## Adding new items + +The fastest way to insert a single item into the database is to use the `create` method to create a new model object and save it to the database: + + :::javascript + var user = userModel.create({ + name: 'Alice', + email: 'alice@example.com'}); + +You also can create a new model object without saving it automatically, and then explicitly use the `save` method. This is useful for updating some of the object attributes before saving: + + :::javascript + var user = userModel.make({name: 'Alice'}); + // update the object + user.email = 'alice@example.com'; + user.save(); + +## Retrieving objects + +Use the `find` method to retrieve all objects for a model or only those matching given conditions: + +### Getting all objects for a model + + :::javascript + var users = userModel.find('all'); + +### Finding objects matching conditions + + :::javascript + var users = userModel.find( + 'all', + { + conditions: {name: 'Alice'} + } + ); + +### Ordering the objects + +Use the `order` and `orderdir` parameters to retrieve objects sorted by one or more attributes: + + :::javascript + // order by one attribute + var users = userModel.find( + 'all', + { + order: 'name', + orderdir: 'DESC', + conditions: {...} // JavaScript API requires conditions + } + ); + + // order by multiple attributes + var users = userModel.find( + 'all', + { + order: ['name', 'email'], + orderdir: ['ASC', 'DESC'], + conditions: {...} // JavaScript API requires conditions + } + ); + +### Retrieving specific attributes + +If only some attributes in an object are needed for a particular action, increase app performance by using the `select` parameter to choose only the required attributes: + +JavaScript syntax: + :::javascript + var users = userModel.find( + 'all', + { + select: ['name'], + conditions: {...} // JavaScript API requires conditions + } + ); + +### Retrieving the first object match + +Use the `first` method (instead of `all`) when calling `find` to get only the first object matching the given condition(s): + + :::javascript + var user = userModel.find( + 'first', + { + conditions: {name: 'Alice'} + } + ); + +## Counting objects + +Use the `count` parameter with `find` method to get a count of objects matching given condition(s): + +JavaScript syntax: + :::javascript + var count = userModel.find( + 'count', + { + conditions: {name: 'Alice'} + } + ); + +## Updating + +The fastest way to add or update object attributes is to save to the database using the `update_attributes` method: + +JavaScript syntax: + :::javascript + var user = userModel.find('first', {conditions: {name: 'Alice'}); + user.update_attributes({ + name: 'Bob', + email: 'bob@example.com'}); + +## Deleting + +### Deleting one object + +To delete one model object, use the `destroy` method on the object to be deleted: + +JavaScript syntax: + :::javascript + var user = userModel.find('first'); + user.destroy(); + +### Delete multiple objects + +Use the `deleteAll` method to delete all objects for a model or only those matching given condition(s): + +JavaScript syntax: + :::javascript + // delete all objects + userModel.delete_all(); + + // delete only objects matching :conditions + userModel.delete_all({conditions: {name: 'Alice'}}) + +## Transactions + +For database operations that must either succeed or fail as a group without leaving any partially completed operations, use transactions to group them together. Combine any set of object/model operations, such as 'insert/update/delete' under a transaction: + + :::javascript + // open 'app' partition + var db = new Rho.Database(Rho.Application.databaseFilePath('app'),'app'); + db.startTransaction(); + try + { + // do multiple operations + db.executeSql("update User set name=?, email=? where object=?",["Alice","alice@example.com","12345"]); + db.executeSql("update User set name=?, email=? where object=?",["Bob","bob@example.com","67890"]); + + // no errors, so commit all the changes + db.commitTransaction(); + } + catch + { + // on error rollback all changes + db.rollbackTransaction(); + } + finally // always close every database connection you open + { + db.close(); + } + +## Executing SQL + +Use the `Database.executeSql` method to execute SQL statements directly on the database: + + +JavaScript syntax: + :::javascript + try { + var db = new Rho.Database(Rho.Application.databaseFilePath('app'),'app'); + var result = db.executeSql('SELECT * FROM User'); // result is an array of hashes, where each hash is a record + } + finally { + db.close(); + } + +Use the `Database.executeBatchSql` to execute a series of SQL statements in a single method call: + + :::javascript + db.executeBatchSql("UPDATE User set valid=0; Update Account set active=0"); + + +## Resetting database + +To recover the database from a bad or corrupt state or if the RhoConnect server returns errors, use the following method to delete all objects for given model(s): + +JavaScript syntax: + :::javascript + var ary = ['Product','Customer']; + Rho.ORM.databaseFullResetEx(ary, false, true); + + +## Related reading + +* [Database API reference](../api/Database) +* [ORM API reference](../api/Orm) +* [ORMModel API reference](../api/OrmModel) diff --git a/docs/en/5.5/guide/newORM_ruby.md b/docs/en/5.5/guide/newORM_ruby.md new file mode 100644 index 00000000..64e1ecd9 --- /dev/null +++ b/docs/en/5.5/guide/newORM_ruby.md @@ -0,0 +1,710 @@ +# Using the ORM Common API in Ruby + +The RhoMobile Suite provides several methods of handling device data. For RhoMobile Suite 5.3 and higher is the [ORM common API](../api/NewORM), which supports JavaScript and Ruby (documented here). RMS 5.2 and lower support the original [Rhom API](../api/rhom-api) (for Ruby), and the [ORM API](../api/Orm), which adds JavaScript support to Rhom via the [OPAL library](http://opalrb.org). + +## How to Include the ORM API + +By default, RhoMobile apps will be built to use the older Rhom implementation (for Ruby) and ORM implementation (for JavaScript). To activate the newer ORM Common API (which supports both JavaScript _and_ Ruby), add the following line to application’s `rhoconfig.txt` file: + + :::yaml + use_new_orm = 1 + +Possible Values: + +* **0 = use 'old' Rhom/ORM API (default)** +* 1 = use newer ORM Common API + +NOTE: If this parameter is left unspecified, the older Rhom/ORM API will be used. + +## Creating a Ruby Data Model + +Ruby models can be generated using RhoStudio or from the command line. The approaches are functionally equivalent; the generator outputs the model class itself along with a set of sample views that can be customized as needed. + +### From RhoStudio + +1. In Project Explorer, **right-click on the application project and select New -> RhoMobile model**. + + + +2. **Enter the model name in the Model Information window**. + +**NOTE: Models MAY NOT have the same name as any of Ruby's built-in classes. These include: `Config, Settings, helpers, test, Client, Sync`. Best practices call for descriptive model names such as `Product` and `Service`, and to avoid generic names such as `time` and `print`. Descriptive model names will help in the future when the application grows or changes**. + +3. **Enter the model attributes separated by commas only (no spaces)**. + + + +4. **Click Finish**. Model generator results will appear in the output console window similar to the image below. + + + +### From the command line + +The 'Rhodes' tool can be invoked manually to allow use of the command line or an IDE other than RhoStudio. The two steps below are functionally identical to the four above. + +1. **Open a command prompt** and switch to the root directory of your application (the directory that contains `app` as a child). + +2. **Execute the commmand** below: + + :::term + $ rhodes model Product name,brand,price,quantity,sku + + +### What's inside a generated model + +Output from the model generated in the 'Product' example will contain the following files, which can be updated to suit the application: + +* **app/Product/index.erb** - the html view template to display the list of objects +* **app/Product/edit.erb** - the html view template to edit an object +* **app/Product/new.erb** - the html view template to supply values to create a new object +* **app/Product/show.erb** - the html view template to displays the selected object +* **app/Product/product_controller.rb** - contains the the business logic for the model, the basic CRUD actions of create, read, update and delete plus indexing. +* **app/Product/product.rb** - contains the Product model definition +* **app/test/product_spec.rb** - placeholder for Product test specs + +**NOTE: Depending on the data model being used, model attributes might not be visible in the `product.rb` file. See [Using Models (below)](#property_bag) for more information.** + + +## Using Models + +Rhodes offers a choice of PropertyBag and FixedSchema model storage schemes. PropertyBag, the default scheme, stores data in a table that's built dynamically as needed, so no attributes are present in a newly generated model. FixedSchema stores data for each model in a database table, with columns for each attribute defined in advance. Please refer to the [Data Handling](local_database) guide for more information. + +### Property Bag +In the property bag model, data is stored as key-value pairs in a single table using the object-attribute-value or [entity-attribute-value model](http://en.wikipedia.org/wiki/Entity-attribute-value_model). This model is sometimes referred to as 'open schema' because the fields (or keys) do not have to be defined in advance; the API stores and syncs all key-value pairs that are entered. + +#### Advantages +* Simple, doesn’t require advance attribute design +* Attributes can be added or removed without modifying the database schema +* Requires no data migration following a schema change + +#### Disadvantages +* Since all attributes are indexed, the database can be much larger than with fixed schema +* Sync process can be slower because database insertions are performed at the attribute level + +In a property bag model, Rhom groups objects by their source ID and object ID. The following example illustrates this idea: + +
                                                                            +Source ID: 1, Model Name: Account
                                                                            ++-----------+----------+--------------+----------------------+
                                                                            +| source_id | attrib   | object       | value                |
                                                                            ++-----------+----------+--------------+------- --------------+
                                                                            +|         1 | name     | 48f39f63741b | A.G. Parr PLC 37862  |
                                                                            +|         1 | industry | 48f39f63741b | Entertainment        |
                                                                            +|         1 | name     | 48f39f230529 | Jones Group          |
                                                                            +|         1 | industry | 48f39f230529 | Sales                |
                                                                            ++-----------+----------+--------------+----------------------+
                                                                            +
                                                                            + +Here, Rhom will expose a class `Account` with the attributes `name` and `industry`: + + :::ruby + account = Account.find('48f39f63741b') + account.name + #=> "A.G. Parr PLC 37862" + + account.industry + #=> "Entertainment" + +#### Using Property Bag Models +1. **Generate a new model** with some attributes: + + :::term + $ rhodes model product name,brand,price,quantity,sku + +This will generate a file called `product.rb` that looks like this: + + :::ruby + class Product + include Rhom::PropertyBag + + # Uncomment the following line to enable sync with Product. + # enable :sync + + #add model specific code here + end + +2. **Enable the requiured features in the model** from the following feature list: + + + :::ruby + class SomeModel + include Rhom::PropertyBag + + # rhoconnect settings + # Enable sync for this model. + # Default is disabled. + enable :sync + + # Set the type of sync this model + # will use (default :incremental). + # Set to :bulk_only to disable incremental + # sync and only use bulk sync. + set :sync_type, :bulk_only + + # Set the sync priority for this model. + # 1000 is default, set to lower number + # for a higher priority. + set :sync_priority, 1 + + # Instruct Rhom to send all attributes + # to RhoConnect when an object is updated. + # Default is disabled, only changed attributes + # are sent. + enable :full_update + + # RhoConnect provides a simple way to keep data out of redis. + # If you have sensitive data that you do not want saved in redis, + # add the pass_through option in settings/settings.yml for each source. + # Add pass_through to client model definition + enable :pass_through + + # model settings + + # Define how data is partitioned for this model. + # For synced models default is :user. + # For non-synced models default is :local + # If you have an :app partition + # for your RhoConnect source adapter and use bulk sync, + # set this to :app also. + set :partition, :app + + # Define blob attributes for the model. + # :blob Declare property as a blob type + # + # :overwrite (optional) Overwrite client copy + # of blob with new copy from server. + # This is useful when RhoConnect modifies + # images sent from Rhodes, for example + # zooming or cropping. + property :image_url, :blob, :overwrite + + # You can define your own properties also + property :mycustomproperty, 'hello' + end + + +### Fixed Schema +In a fixed schema model, each model has a separate database table and attributes form the columns of that table. In this sense, the fixed schema model is similar to a traditional relational database. + +#### Advantages +* Smaller database size; indexes can be assigned to specific attributes +* Sync process may be faster because whole objects are inserted at once + +#### Disadvantages +* Schema changes require data migration +* Database performance may be slow without careful index specificity + + +#### Using Fixed Schema Models +Using a fixed schema model involves one more step than the Property Bag model. + +1. **Generate the model using the 'rhodes' command**: + + :::term + $ rhodes model product name,brand,price,quantity,sku + +2. **Change the include statement in `product.rb` to**: + + :::ruby + include Rhom::FixedSchema + +3. **Add the attributes**: + + :::ruby + class Product + include Rhom::FixedSchema + + # Uncomment the following line to enable sync with Product. + # enable :sync + + property :name, :string + property :brand, :string + property :price, :string + property :quantity, :string + property :sku, :string + + property :int_prop, :integer + property :float_prop, :float + property :date_prop, :date #translate to integer type + property :time_prop, :time #translate to integer type + + end + +A table with a fixed schema model will be generated automatically when the application launches. + +Below is a full list of options available to fixed schema models: + + :::ruby + class SomeModel + include Rhom::FixedSchema + + # rhoconnect settings + # Enable sync for this model. + # Default is disabled. + enable :sync + + # Set the type of sync this model + # will use (default :incremental). + # Set to :bulk_only to disable incremental + # sync and only use bulk sync. + set :sync_type, :bulk_only + + # Set the sync priority for this model. + # 1000 is default, set to lower number + # for a higher priority. + set :sync_priority, 1 + + # Instruct Rhom to send all attributes + # to RhoConnect when an object is updated. + # Default is disabled, only changed attributes + # are sent. + enable :full_update + + # RhoConnect provides a simple way to keep data out of redis. + # If you have sensitive data that you do not want saved in redis, + # add the pass_through option in settings/settings.yml for each source. + # Add pass_through to client model definition + enable :pass_through + + # model settings + + # Define how data is partitioned for this model. + # Default is :user. If you have an :app partition + # for your RhoConnect source adapter and use bulk sync, + # set this to :app also. + set :partition, :app + + # Set the current version of the fixed schema. + # Your application may use it for data migrations. + set :schema_version, '1.0' + + # Define fixed schema attributes. + # :string and :blob types are supported. + property :name, :string + property :tag, :string + property :phone, :string + property :image_url, :blob + + # Define a named index on a set of attributes. + # For example, this will create index for name and tag columns. + index :by_name_tag, [:name, :tag] + + # Define a unique named index on a set of attributes. + # For example, this will create unique index for the phone column. + unique_index :by_phone, [:phone] + + # Define blob attributes for the model. + # :blob Declare property as a blob type + # + # :overwrite (optional) Overwrite client copy + # of blob with new copy from server. + # This is useful when RhoConnect modifies + # images sent from Rhodes, for example + # zooming or cropping. + property :image_url, :blob, :overwrite + + # You can define your own properties also + property :mycustomproperty, 'hello' + end + +## Data Migration +Changes to the data model in a fixed-schema database requires that data be migrated from the old schema to the new one (a requirement not shared by the Property Bag model because of its 'open schema' construction). + +For this reason, Rhom provides an application hook for manually migrating data in the event of a model change. The hook also can be used to run business logic related to updates to a database. For example, it is sometimes desireable to display a custom alert notifying the user to wait a few moments while a data migration is in progress. + +To use this hook: + +1. **Track the `:schema_version`** in the model: + + :::ruby + class Product + include Rhom::FixedSchema + + set :schema_version, '1.1' + end + +2. **In the `application.rb` class, implement the hook `on_migrate_source(old_version, new_src)`** as follows: + + :::ruby + class AppApplication < Rho::RhoApplication + + # old_version String containing old version value (i.e. '1.0') + # new_src Hash with source information: + # 'schema_version', 'name', 'schema' + # new_src['schema']['sql'] contains new schema sql + def on_migrate_source(old_version, new_src) + # ... do something like alert user ... + + db = Rho::RHO.get_src_db(new_src['name']) + db.execute_sql("ALTER TABLE #{new_src['name']} ADD COLUMN mytest VARCHAR DEFAULT null") + + true # does not create table + end + end + +The code above will call the hook on application start whenever `:schema_version` has changed. + +**NOTE: To modify the schema without recreating the table, use the ADD COLUMN command. Limitations of SQLlite prevent the removal of columns or changes to the type**. + +1. **Return `false` to run the custom SQL** specified by the new_src['schema']['sql'] string: + + :::ruby + def on_migrate_source(old_version, new_src) + # ... do something like alert user ... + false # create table by source schema - useful only for non-synced models + end + +**NOTE: When migrating a table with source data that was synchronized, data must be copied to the new table before the first sync can occur. The sync function will not populate a blank table**. + +### Property Bag Data Migrations +Since its attributes are dynamic, the Property Bag database requires no data migrations when changes are made to its schema. + +### Removing Local Data From a Device +This scenario will work for Property Bag and Fixed Schema models. + +To remove all local data when upgrading to new application version, simply change `app_db_version` in the `rhoconfig.txt` file. + +## Adding new objects +To create a new model object and save it to the database, use the `create` method: + + + :::ruby + user = User.create( + :name => 'Alice', + :email => 'alice@example.com') + +NOTE: This is the fastest way to insert a single item into the database. + +You also can create the new model object without saving it automatically, and then explicitly use the `save` method. This is useful for updating some of the object attributes before saving: + + :::ruby + user = User.new(:name => 'Alice') + # update the object + user.email = 'alice@example.com' + user.save + +## Retrieving objects +Use the find method to retrieve all objects for a model or only those matching given conditions. + +### Getting all objects for a model +To retrieve all objects for a model using the `all` parameter: + + :::ruby + users = User.find(:all) + +### Finding objects matching conditions +To retrieve all objects matching given conditions using the `conditions` parameter: + + :::ruby + users = User.find( + :all, + :conditions => {:name => 'Alice'} + ) + +### Ordering the objects +Use the `order` and `orderdir` parameters to retrieve objects sorted by one or more attributes: + + :::ruby + # order by one attribute + users = User.find( + :all, + :order => 'name', + :orderdir => 'DESC' + ) + + # order by multiple attributes + users = User.find( + :all, + :order => ['name', 'email'], + :orderdir => ['ASC', 'DESC'] + ) + +### Retrieving specific attributes +If only some attributes in an object are needed for a particular action, increase app performance by using the `select` parameter to choose only the required attributes: + + :::ruby + users = User.find( + :all, + :select => ['name'] + ) + +### Paginating results + +For retrieving objects in chunks, the `paginate` method emulates Rails' classic pagination syntax. The default page size is 10. + +Use `:conditions`, `:order` and `:select` parameters in a way similar to the `find` method: + + :::ruby + # get first 10 records + users = User.paginate(:page => 0) + + # get records 21-40 + users = User.paginate(:page => 1, :per_page => 20) + +### Retrieving only the first object matching conditions +Retrieve only the first object matching given conditions using `first` instead of `all` when calling `find`: + + :::ruby + user = User.find( + :first, + :conditions => {:name => 'Alice'} + ) + +### Using SQL queries directly +Retrieve model object(s) directly using SQL queries with the `find_by_sql` method. This method works only for fixed schema models: + + :::ruby + users = User.find_by_sql('SELECT * FROM User') + +## Counting objects +Get the number of objects matching given condition(s) using the `count` parameter with `find` method: + + :::ruby + count = User.find( + :count, + :conditions => {:name => 'Alice'} + ) + +## Updating +Update an object’s attributes and save to the database using the `update_attributes` method: + + :::ruby + user = User.find(:first, :conditions => {:name => 'Alice'}) + user.update_attributes( + :name => 'Bob', + :email => 'bob@example.com') + +NOTE: This is the fastest way to add or update item attributes. + + +## Deleting +### Deleting one object +To delete a single model object, use the `destroy` method on the object to be deleted: + + :::ruby + user = User.find(:first) + user.destroy + +### Delete multiple objects +To delete all objects for a model, or only those matching given condition(s), use the `delete_all` method: + + :::ruby + # delete all objects + User.delete_all() + + # delete only objects matching :conditions + User.delete_all(:conditions => {:name => 'Alice'}) + +## Transactions + +For database operations that must either succeed or fail as a group without leaving any partially completed operations, use transactions to group them together. Combine any set of object/model operations, such as ‘insert/update/delete’ under a transaction: + + :::ruby + db = Rho::Database.new + db.startTransaction + begin + # do multiple operations + User.create(:name => 'Alice', :email => 'alice@example.com') + User.create(:name => 'Bob', :email => 'bob@example.com') + + # no errors, so commit all the changes + db.commitTransaction + rescue + # on error rollback all changes + db.rollbackTransaction + end + +## Executing SQL +To execute SQL statements directly on the database, use the `Database.executeSql` method: + + :::ruby + begin + db = Rho::Database.new(Rho::Application.databaseFilePath('app'),'app'); + result = db.executeSql('SELECT * FROM User') # result is an array of hashes, where each hash is a record + ensure + db.close + end + + :::ruby + db.executeBatchSql("UPDATE User set valid=0; Update Account set active=0") + +## Adding fields to an existing model + +The list of attributes (fields) in a model can be updated as development progresses. If using the Property Bag storage scheme (the default), all that's required is to add the relevant code to the views (`index.erb`, `edit.erb`, `new.erb` and `show.erb`); Rhodes will take care of the rest. If using Fixed Schema, add the appropriate lines in your `.rb` file: + + :::ruby + property : : + +For example, in the `Product` model, we could add: + + :::ruby + property :color, :string + +For further details, please refer to the [Using the local database](../rhodes/rhom#fixed-schema) guide, which also contains methods to fine-tune data synchronization. + +## Linking a model to a RhoConnect synchronization server + +### What is RhoConnect? +RhoConnect is the server-side component of the RhoMobile Suite that connects mobile applications to external data sources and handles all aspects of data synchronization. Whether data comes from a relational database, NoSQL data store, RESTful web services or any other data source, RhoConnect bridges the gap between mobile clients and server resources. RhoConnect frees the developer from having to write complex synchronization code that's error-prone and hard to maintain. + +### Integrating a RhoMobile app with RhoConnect +Once an application can store data about a particular model, enabling two-way synchronization with a RhoConnect server is a one-step process. + +To enable synchronization in a RhoMobile app, simply open the model file (i.e. `product.rb`) and uncomment the line: + + :::ruby + enable :sync + +As long as RhoConnect server is properly configured, this is all that is required to benefit from automatic, two-way synchronization. See the [RhoConnect Tutorial](../tutorial/rhoconnect) for in-depth information about the benefits RhoConnect provides, as well as [Using the local database](../rhodes/rhom#fixed-schema) to find out how to tune data synchronization according to the needs of your application. + +## Associations +Rhom has a `sync association` called `belongs_to` which can be used to trigger updates on sync-enabled models. This is useful when relationships between backend service objects exists. + +For example, an app might contain a list of customers assigned to a sales person: + + :::ruby + class Customer + include Rhom::PropertyBag + + # Declare container model and attribute. + belongs_to :salesrep_id, 'SalesRep' + end + +The value used as the identifier for linking objects is the `object` property: + + :::ruby + def create + @customer = Customer.new(@params['customer']) + @customer.save + + sales_rep = SalesRep.find(...) # find the appropriate sales representative for new customers + customer.salesrep_id = @sales_rep.object + customer.save + redirect :action => :index + end + +Polymorphic sync associations, or associations across multiple classes, also can be defined using array notations or multiple declarations: + +Using array notation: + + :::ruby + belongs_to :parent_id, ['Product', 'Case'] + +Using multiple declarations: + + :::ruby + belongs_to :parent_id, 'Product' + belongs_to :parent_id, 'Case' + +If planning to use the bulk sync feature for associated models, consider the corresponding support on the RhoConnect Server side. See [RhoConnect Bulk Sync associations](../rhoconnect/bulk-sync#bulk-sync-associations). + +## Freezed models +To limit model attributes to a specific list, the model can be 'freezed': + + :::ruby + class Customer + include Rhom::PropertyBag + + enable :sync + + set :freezed, true + + property :address, :string + property :city, :string + property :email, :string + end + +If an attempt is made to set a property on a freezed model that has not been explicitly defined, an ArgumentError exception will result: + + :::ruby + obj = Customer.new( :wrong_address => 'test') #will raise ArgumentError exception + obj = Customer.create( :wrong_address => 'test') #will raise ArgumentError exception + + obj = Customer.new + obj.wrong_address = 'test' #will raise ArgumentError exception + + obj = Customer.new + obj.update_attributes(:wrong_address => 'test') #will raise ArgumentError exception + +**NOTE: FixedSchema models are 'freezed' by default**. + +## Resetting the Database +To recover the database from a bad or corrupt state or if the RhoConnect server returns errors, use the following method to delete all objects for given model(s). + +### Delete all objects for given models + + :::ruby + ary = ['Product','Customer'] + Rho::ORM.databaseFullResetEx(ary, false, true) + + +Use `Rho::ORM.databaseFullReset(resetClientInfo=false, resetLocalModels=true)` to delete all records from the property bag and model tables: + + :::ruby + # resetClientInfo If set to true, client_info + # table will be cleaned. + # + # resetLocalModels If set to true, local(non-synced models) + # will be cleaned. + Rho::ORM.databaseFullReset(false,true) + +Use `Rho::ORM.databaseFullResetAndLogout` to perform a full reset and then logout the RhoConnect client: + + :::ruby + Rho::ORM.databaseFullResetAndLogout + +Use `Rho::ORM.databaseFullclientResetAndLogout` for the equivalent to `Rho::ORM.databaseFullReset(true)` plus a `SyncEngine.logout`: + + :::ruby + Rho::ORM.databaseFullclientResetAndLogout + +### "Unknown client" sync error + +If the "Unknown client" sync error occurs in the sync callback, the RhoConnect server no longer knows about the client. In such cases, a `Rho::ORM.databaseFullclientResetAndLogout` is recommended. This error requires proper intervention in the app to handle the state before resetting the client. For example, a sync notification could contain the following:** + + :::ruby + if @params['error_message'].downcase == 'unknown client' + puts "Received unknown client, resetting!" + Rho::ORM.databaseFullclientResetAndLogout + end + +### `Rho::ORM.databaseLocalReset` + +To reset only local (non sync-enabled) models: + + :::ruby + Rho::ORM.databaseLocalReset + +Use `Rho::ORM.databaseFullResetEx([model_name1, model_name2], false, true)` to delete +all records from the property bag and model tables. + +If models are set, then reset only selected models: + + :::ruby + # models Array of model names to reset + # resetClientInfo If set to true, client_info + # table will be cleaned. + # + # resetLocalModels If set to true, local(non-synced models) + # will be cleaned. + Rho::ORM.databaseFullResetEx(['Product', 'Customer'], false, true) + +## Database Encryption + +**NOTE: [Rhom data encryption](../../2.2.0/rhodes/rhom#database-encryption) is no longer available as of Rhodes 3.3.3 and higher. This feature is now supported only in Zebra RhoMobile Suite and requires the purchase of a [RhoElements license](licensing). Your application's build.yml will also need to be modified to [indicate the application type is 'Rhoelements'](build_config#other-build-time-settings). Additionally, a [RhoElements license](licensing) is required. ** + +If the application requires local (on-device) database encryption, enable it by setting a flag in `build.yml`: + + :::yaml + encrypt_database: 1 + +**NOTE: Database encryption is not currently supported for applications that use bulk sync.** + +### Platform Notes +* iOS uses an AES 128 encryption algorithm from the iOS SDK. +* Android uses an AES 128 ecryption algorithm from the Android SDK. +* Windows Mobile uses an RC4 algorithm from Windows Mobile SDK. + +## Related reading + +* [Database API reference](../api/Database) \ No newline at end of file diff --git a/docs/en/5.5/guide/nonrhostudio.md b/docs/en/5.5/guide/nonrhostudio.md new file mode 100644 index 00000000..014ab6f6 --- /dev/null +++ b/docs/en/5.5/guide/nonrhostudio.md @@ -0,0 +1,148 @@ +# Developing Without RhoStudio +Although installing RhoMobile Suite provides everything you need to build RhoMobile applications through the included RhoStudio IDE, you may wish to use your own IDE to build your RhoMobile applications. This guide describes how to setup your environment as well as how to use the Rhomobile command line options. + +## What are Gems? +A RubyGem is a software package, commonly called a “gem”. Gems contain a packaged Ruby application or library. The RubyGems software itself allows you to easily download, install, and manipulate gems on your system. There are three gems included with RhoMobile Suite: `rhodes`, `rhoelements` and `rhoconnect-client`. + +For more information on Ruby Gems, visit [Rubygems.org](http://guides.rubygems.org/what-is-a-gem/) + +## Installing Rho Gems +Before installing the needed Rho Gems, you must: + +* [Install Ruby for your operating system](rhomobile-install) (RhoMobile Suite currently includes version 1.93) + +Then, run this command to install the Rho Gems. + + :::term + $ [sudo] gem install rhodes + $ [sudo] gem install --local path_to_gem/rhoelements_gem_name.gem + $ [sudo] gem install --local path_to_gem/rhoconnect-client_gem_name.gem + +> Note: Installing RhoMobile Suite will install these gems automatically. You can have multiple versions of these gems installed on your system. By default when building your application the most recent version # is used. Please consult the guide on building for a specific version of RhoMobile. + +* The `rhodes` gem is distrubuted to publically availableRuby repositories. The command above will install the latest version available. If you are testing a beta release, you can also use the local syntax for installing a local copy of the gem file + +* The `rhoelements` gem is only needed if your application will be taking advantage of mobile APIs and features that are targeted towards enterprise devices. You will also need this gem if you wish to have a Webkit-enabled application running on Windows Mobile/CE. + +* The `rhoconnect-client` was previosly included in the `rhodes` gem prior to version 4.0. If your application plans on using the RhoConnect client for data synchronization, you will need to install this gem. + +## Linking SDKs +You will need the SDKs for the platform you want to build your app on. These instructions are found [here](nativesdksetup). + +After you install the gem and your desired SDKs, you need to run: + + :::term + $ rhodes-setup + +This will prompt you for where you installed the SDKs for the various platforms. The installation script will display its best guess as to where the SDK is. You can then enter a new location, or leave it blank to use the suggestion. If you are not building for a specific platform (for example, you can't build for the iPhone on Windows), you can leave that SDK location blank. + +## Generating A Rhodes Application +The first step is to generate the application and base files. First we will generate an application called StoreManager with the following command: + + :::term + $ rhodes app storemanager http://localhost:9292/application + +This will generate an application directory called "storemanager" with several files. Note also that the third argument above is the URL to the RhoConnect server data source (required if you want to do synchronized data as we describe in the next section). Specifically it will set the rhoconfig.txt file to have the following option: + + :::txt + syncserver = 'http://localhost:9292/application' + +If you do not need synchronized offline data, you can leave the third argument out. + + +The default home screen of the app is defined in the storemanager/app/index.erb file. You can edit the HTML there to create what your app displays. You can link to other HTML files and ERB files from there with standard HTML techniques. + +## Generating Models +You can also use the command line to add models and controllers. When the model is generated, Rhodes will also create files for a standard UI for displaying and editing the model. This follows the standard model-view-controller paradigm.Get more details on [project structure](creating_a_project#project-structure). + +Let's generate a model called "product" and give it some attributes. + + :::term + $ cd storemanager + $ rhodes model product brand,name,price,quantity,sku + Generating with model generator: + [ADDED] app/Product/index.erb + [ADDED] app/Product/edit.erb + [ADDED] app/Product/new.erb + [ADDED] app/Product/show.erb + [ADDED] app/Product/product_controller.rb + [ADDED] app/Product/product.rb + [ADDED] app/test/product_spec.rb + +> Note: Models created through the command-line-interface will use the [property bag data schema](rhom_ruby#property_bag) by default. To use Fixed Schema instead, have a look at the [fixed schema section](rhom_ruby#fixed_schema) of our [Rhom in Ruby guide](rhom_ruby). + +## Building and Running +You build and run for individual platforms using command line options + +Running on iphone simulator + + :::term + rake run:iphone + +Running for iOS on RhoSimulator + + :::term + rake build:iphone:rhosimulator + +Running on WM device + + :::term + rake run:wm:device + +> Note: Starting in version 4.1 of RhoElements, no .cab file will be generated within the project when running rake run:wm:device + +## Command Line Options +If your IDE or Text-Editor provides a means to launch an external executable, you can integrate RhoMobile development tasks by using command line options. You execute these by the appropriate rake tasks, such as "rake run:android" to run it on the Android emulator. To see all possible rake tasks do the following from your `application project folder`: + + :::term + $ rake -T + + rake build:android:eclipsebundle # Build RhoBundle for Eclipse project + rake build:android:extensions # Building native extensions + rake build:android:rhobundle # Build RhoBundle for android + rake build:wp8:rhobundle_noext # Build WP8 rhobundle + rake build:wp:rhobundle # Build WP7 rhobundle + rake clean:android # Clean Android + rake clean:iphone # Clean iphone + rake clean:win32 # Clean win32 + rake clean:wince # Clean windows ce + rake clean:wm # Clean wm + rake clean:wp # Clean wp + rake clean:wp8 # Clean wp + rake device:android:debug # Build debug self signed for device + rake device:android:production # Build production signed for device + rake device:iphone:production # Builds and signs iphone for production + rake device:symbian:production # Build production for device + rake device:win32:production # Build installer for Windows + rake device:wince:production # Build production for device or emulator + rake device:winxpe:production # Build installer for Windows XP Embedded + rake device:wm:production[exclude_dirs] # Build production for device or emulator + rake device:wp8:production # Build production for device + rake device:wp:production # Build production for device or emulator + rake emulator:wp8:production # Build production for device + rake run:android # build and launch emulator + rake run:android:device # build and install on device + rake run:android:rhosimulator # Run application on RhoSimulator + rake run:iphone # Builds everything, launches iphone simulator + rake run:iphone:rhosimulator # Run application on RhoSimulator + rake run:webrickrhologserver[app_path] # start rholog(webrick) server + rake run:win32 # Run win32 + rake run:win32:rhosimulator # Run application on RhoSimulator + rake run:wince:device # Build and run on the Windows CE device + rake run:wince:device:cab # Build, install .cab and run on the Windows CE device + rake run:wince:rhosimulator # Run application on RhoSimulator + rake run:wm # Build and run on WM6 emulator + rake run:wm:cab # Build, install .cab and run on WM6 emulator + rake run:wm:device # Build and run on the Windows Mobile device + rake run:wm:device:cab # Build, install .cab and run on the Windows Mobile device + rake run:wm:rhosimulator # Run application on RhoSimulator + rake run:wp # Build, install .xap and run on WP7 emulator + rake run:wp8 # Build, install .xap and run on WP8 emulator + rake run:wp8:device # Build, install .xap and run on WP8 device + rake run:wp8:rhosimulator # Run application on RhoSimulator + rake run:wp:device # Build, install .xap and run on WP7 device + rake run:wp:rhosimulator # Run application on RhoSimulator + rake uninstall:android # uninstall from emulator + rake uninstall:android:device # uninstall from device + +> Note: Windows Mobile/CE apps that use the Webkit will not be able to run in the Windows Mobile Emulator due to memory limitations in the emulator. \ No newline at end of file diff --git a/docs/en/5.5/guide/pim.md b/docs/en/5.5/guide/pim.md new file mode 100644 index 00000000..6bf9f0ab --- /dev/null +++ b/docs/en/5.5/guide/pim.md @@ -0,0 +1,113 @@ +# PIM Contacts and Calendar + +## PIM Contacts + +Rhodes provides access to the device's local phone book and stored contacts via the Ruby class RhoContact. + +To allow read/modify personal information and contacts enable the pim capability. This is done by adding the following lines to build.yml: + + :::yaml + capabilities: + - pim + +### PIM Contacts API + +Refer to the [PIM Contacts API](../rhodesapi/rhocontact-api) methods to perform the following functionality. + + * [find](../rhodesapi/rhocontact-api#find) - Returns the contacts in the device phone book. + * [create!](../rhodesapi/rhocontact-api#create) - Create a new contact in the phonebook. + * [destroy](../rhodesapi/rhocontact-api#destroy) - Delete this contact from the phonebook. + * [update_attributes](../rhodesapi/rhocontact-api#updateattributes) - Find a contact in the phonebook and update its properties. + +The [Contact Properties](../rhodesapi/rhocontact-api#contact-properties) lists the contact properties that are supported for all platforms, and additional contact properties supported on Android and iOS. + +Example of returning a hash of hashes of all the contacts stored in the phonebook (index): + + :::ruby + Rho::RhoContact.find(:all) + +Example for Android and iOS of finding the number of contacts in the phonebook: + + :::ruby + Rho::RhoContact.find(:first) + +**NOTE: It is allowed to pass additional params hash at all platforms. Platforms that has no extended functionality will just skip these** + +Example of returning a hash of all properties of the contact identified by the provided id (show): + + :::ruby + Rho::RhoContact.find(@params['id']) + +Example of finding with conditions: + + :::ruby + @count = Rho::RhoContact.find(:count, :conditions => {:phone => 'not_nil'}) + if @params['offset'] + @offset = @params['offset'].to_i + else + @offset = 0; + end + @contacts = Rho::RhoContact.find(:all, :per_page => 10, :offset => @offset, :select => ["id", "display_name", "mobile_number"], :conditions => {:phone => 'not_nil'}) + @contacts = {} unless @contacts + @contacts = @contacts.sort do |x,y| + res = 1 if x[1]['display_name'].nil? + res = -1 if y[1]['display_name'].nil? + res = x[1]['display_name'] <=> y[1]['display_name'] unless res + res + end + +### Sample +For examples on how to use the API provided by this class, see the view and controller in the /app/Contacts folder in the [System API Samples application](http://github.com/rhomobile/rhodes-system-api-samples/tree/master/app/Contacts/controller.rb). + +## PIM Calendar/Events +Rhodes provides access to the device's local calendar and stored events via the [Ruby class RhoEvent](../rhodesapi/rhoevent-api). Click the links below for detailed information about the methods. + + * [find](../rhodesapi/rhoevent-api#find) - Returns the events in the device calendar. + * [create!](../rhodesapi/rhoevent-api#create) - Creates a new event in the calendar. Returns a hash of the properties in the event. + * [update_attributes](../rhodesapi/rhoevent-api#updateattributes) - Update the properties for this event and save the event in the calendar. + * [destroy](../rhodesapi/rhoevent-api#destroy) - Remove this event from the calendar. + * [Event hash properties](../rhodesapi/rhoevent-api#event-hash-properties) - A listing of the propeties storied in a calendar event hash, which is returned by the find method. + +To allow read/modify calendar information enable the calendar capability. This is done by adding the following lines to build.yml: + + :::yaml + capabilities: + - calendar + +Check if the device has a calendar: + :::ruby + System::get_property('has_calendar') + +Example of returning a hash of hashes of all the events stored in the calendar (index): + :::ruby + Rho::RhoEvent.find(:all) + +Example of returning a hash of all the properties of the event identified by the provided id (show): + :::ruby + Rho::RhoEvent.find(@params['id']) + +Example of returning a hash of all properties of the events found by specified parameters (index): + :::ruby + start = Time.utc(2010, 'jan', 1, 0, 0, 0) + finish = Time.utc(2012, 'dec', 31, 23, 59, 59) + @@events = Rho::RhoEvent.find(:all, :start_date => start, + :end_date => finish, :find_type => 'starting', + :include_repeating => true) + +Create new event in the calendar: + :::ruby + created_event = Rho::RhoEvent.create!(@params['event']) + +Update event in the calendar: + :::ruby + Rho::RhoEvent.update_attributes(@params['event']) + +Delete event from the calendar: + Rho::RhoEvent.destroy(@params['id'])) + +### Remarks +In Android Device's, Calendar Event will only be created if the calendar is synced with atleast one mail account. + +### Sample +For examples on how to use the API provided by this class, see the view and controller in the /app/Calendar folder in the [System API Samples application](http://github.com/rhomobile/rhodes-system-api-samples/tree/master/app/Calendar/controller.rb). + diff --git a/docs/en/5.5/guide/printing.md b/docs/en/5.5/guide/printing.md new file mode 100644 index 00000000..2a6f867f --- /dev/null +++ b/docs/en/5.5/guide/printing.md @@ -0,0 +1,418 @@ +# Printing +## Overview +RhoMobile Suite 5.3 permits printing via Bluetooth and Wi-Fi from mobile devices running Android, iOS and Windows Mobile/CE. **New in version 5.3 is the ability to print via USB to Windows Mobile/CE devices**, building on similar support for Android devices introduced in 5.1. + +To facilite USB printing, the RhoMobile printing API now includes the `CONNECTION_TYPE_USB` parameter. The API is otherwise unchanged, and operates in the same way as in prior editions. To print via USB, the Zebra device must be connected with a USB "On-The-Go" (OTG) cable or adapter to one of [Zebra's supported printers](#zebra-printers-with-usb-printing). Android and Windows Mobile/CE printing is supported via direct USB OTG connection or through a cradle with OTG adapter. Windows Mobile/CE devices also must be in 'Host Mode,' which is found under USB Config in the Settings panel. + +This guide is designed to provide an overview of the steps necessary to enable printing in a RhoMobile application. Where appropriate, it contains links to details for the calls, methods, parameters, constants and other specifics necessary to build your application using the Zebra printing APIs. + +## 1- Enable Print APIs +The [RhoMobile APIs](apisummary) provide two APIs for printing. The [Printing](../api/printing) API is a parent class that defines common class attributes that specific printer-type APIs will inherit. The [PrintingZebra](../api/printingzebra) API is the printer-type API for Zebra printers. + +**To enable printing in your application, your `build.yml` must include both of these extensions**. + +Example `build.yml` command: + + :::ruby + ... + extensions: ["printing","printing_zebra",...] + ... + + +## 2- Find a Printer +Before your app can print, it must first discover and connect to a printer. There are a few ways to discover printers, but all use the [searchPrinters](../api/printing#msearchPrintersSTATIC) method. + +###Finding via Bluetooth +Printing via Bluetooth is supported for Android, iOS and Windows Mobile apps. **During Bluetooth discovery, the printer must be set to "discoverable."** The following JavaScript code looks for any Zebra printers discoverable via Bluetooth by specifying the `connectionType` and `printerType` in the `options` parameter: + +Sample JavaScript code: + + :::javascript + var printers = []; + + Rho.Printer.searchPrinters({ + connectionType:Rho.Printer.CONNECTION_TYPE_BLUETOOTH, + printerType: Rho.Printer.PRINTER_TYPE_ZEBRA + }, function (cb){ + if(cb.status == 'PRINTER_STATUS_SUCCESS') + { + if (typeof cb.printerID != "undefined") + { + console.log('Found: ' + cb.printerID) + // > Found ZEBRA_PRINTER_1 + + printers.push(cb.printerID); + } + else + { + console.log('Done Searching'); + } + } + else + { + console.log(cb.status); + } + }); + +NOTE: TIP: To minimize search time, code should provide as many search parameters as possible. + +The Bluetooth MAC address consists of six groups of two hexadecimal digits separated by colons. If a printer's Bluetooth MAC address is known, it can be specified as a `deviceAddress` using the `options` parameter: + +Sample JavaScript code: + :::javascript + Rho.PrinterZebra.searchPrinters({ + connectionType:Rho.Printer.CONNECTION_TYPE_BLUETOOTH, + deviceAddress: '00:03:7A:4C:F2:DB' + ... + +NOTE: When pairing with a Bluetooth device for the first time, a prompt might appear for a pairing PIN. Commonly used PINs: 0000, 1111 and 1234. Check the printer manufacturer's specifications. + +###Finding via Wi-Fi +Printing via Wi-Fi is supported for Android, iOS and Windows Mobile apps. For Wi-Fi printer searching, the `deviceAddress` and `devicePort` parameters can be used to quickly identify known devices: + +Sample JavaScript code: + :::javascript + Rho.Printer.searchPrinters({ + connectionType:Rho.Printer.CONNECTION_TYPE_TCP, + deviceAddress: '192.168.1.121', + devicePort: 6101 + ... + +NOTE: When attepting to connect via Bluetooth or Wi-Fi, be sure the device's corresponding radio is turned on. If using Bluetooth, the printer should be set to "discoverable." + +###Finding via USB +Printing via USB is supported on Android and Windows Mobile/CE devices. To print from a Zebra enterprise mobile computer, it must be connected to one of [Zebra's supported printers](#zebra-printers-with-usb-printing) **using an OTG cable or adapter.** Windows Mobile/CE devices also must be in 'Host Mode,' which is found under USB Config in the Settings panel. + +Sample JavaScript code: + + :::javascript + var printers = []; + + Rho.Printer.searchPrinters({ + connectionType:Rho.Printer.CONNECTION_TYPE_USB, + printerType: Rho.Printer.PRINTER_TYPE_ZEBRA + }, function (cb){ + if(cb.status == 'PRINTER_STATUS_SUCCESS') + { + if (typeof cb.printerID != "undefined") + { + console.log('Found: ' + cb.printerID) + // > Found ZEBRA_PRINTER_1 + + printers.push(cb.printerID); + } + else + { + console.log('Done Searching'); + } + } + else + { + console.log(cb.status); + } + }); + +Use the `search.Printers` method and the connecionType as `CONNECTION_TYPE_USB` parameter to search for printer(s) connected to the mobile device via USB. **This parameter is new in RMS 5.1.** +
                                                                            + +####USB Compatibility Alerts + +* **A USB On-the-Go (OTG) cable or adapter permits a mobile device to act as 'host' to client peripherals** such as flash drives, keyboards and printers. + +* **Some [Zebra TC7X single/dual slot cradles](https://www.zebra.com/us/en/products/accessories/mobile-computer/cradles/sharecradle-system.html) present a USB micro "AB" receptacle** that allows the TC7X to act as host or client depending on the cable. + +* **The Zebra OTG implementation lacks Session Request Protocol (SRP) and Host Negotiation Protocol (HNP)**, portions of the spec that allow connected devices to control power consumption and switch dynamically between host and client modes. + +* **Printing via USB from a cradled device is possible by inserting an OTG micro A connector to the cradle** and connecting the USB-B (or mini-B) end to the printer. + +* **OTG supports direct USB connections only**; the use of USB hubs is not supported by the OTG spec. +
                                                                            + + +## 3- Connect to a Printer + +The script in STEP 2 executes the callback function of the [searchPrinters](../api/printing#msearchPrintersSTATIC) method, which returns a unique printerID property for each printer found. This ID will be used to establish a connection with the desired printer. After the last printer is found, an additional callback will be triggered and will contain no printerID, signaling the end of search and that it's safe to connect to a printer. + +NOTE: This `printerID` is a unique identifier that is tracked by the RhoMobile framework. It has no relation to ID numbers that a printer manufacturer might be using. + +At this time there should be one or more `printerID` values in the `printers` array variable. To access one, create an instance of the Printer class by calling the [getPrinterByID](../api//printingzebra#mgetPrinterByIDSTATIC) method and passing a `printerID` as a string to the vairable `myPrinter`: + +Sample JavaScript code: + :::javascript + // Ex: printers[0] = 'ZEBRA_PRINTER_1' + var myPrinter = Rho.Printer.getPrinterByID(printers[0]); + + // myPrinter is now an instance class of Printer + // and can use the Instance Methods and properties associated + // with that class + + +Once you've instantiated a specific printer, your app can connect to it using the [connect](../api/printingzebra#mconnect) method: + +Sample JavaScript code: + :::javascript + myPrinter.connect(function (cb){ + + console.log(cb); + // > PRINTER_STATUS_SUCCESS + //cb = PRINTER_STATUS... constant + + console.log(myPrinter.deviceName); + // > 'XXXX09-10-5799' + // deviceName will be Zebra's 'Friendly Name' + + console.log(myPrinter.deviceAddress); + // > '00:03:7A:4C:F2:DB' + // deviceAddress will equal the Bluetooth Address + + }); + +The `callback` object in the [connect](../api/printingzebra#mconnect) method will be a `string` containing one of the [PRINTER_STATUS...](../api/printingzebra#Constants) constants. For example: + +- PRINTER_STATUS_SUCCESS +- PRINTER_STATUS_ERR_NETWORK +- PRINTER_STATUS_ERR_TIMEOUT + +## 4- Retrieve Printer State +You can also check information about the printer using the [requestState](../api/printingzebra#mrequestState) method, which returns the information in a callback object. The first parameter of this method is an array that lists the items to find. These are [PRINTER_STATE...](../api/printing#Constants) constants. For example: + +- PRINTER_STATE_IS_COVER_OPENED +- PRINTER_STATE_IS_DRAWER_OPENED +- PRINTER_STATE_IS_PAPER_OUT + +Sample JavaScript code: + + :::javascript + // Assumes you have created the instance 'myPrinter' + // from previous methods described above + myPrinter.requestState(['PRINTER_STATE_IS_READY_TO_PRINT', + 'PRINTER_STATE_IS_PAPER_OUT'],function (cb){ + console.log(cb.status); + console.log(cb.PRINTER_STATE_IS_PAPER_OUT); + console.log(cb.PRINTER_STATE_IS_READY_TO_PRINT); + + }); + +## 5- Retrieve Supported Printer Languages +Before sending commands to the printer, you must be aware of which printer languages are supported. For Zebra printers these might include ZPL, CPCL and EPS. To retrieve a list of supported languages, use the [enumerateSupportedControlLanguages](../api/printing#menumerateSupportedControlLanguages) method. + +The callback will be an array of [PRINTER_LANGUAGE...](../api/printing#Constants) constants. For example: + +- PRINTER_LANGUAGE_ZPL +- PRINTER_LANGUAGE_CPCL +- PRINTER_LANGUAGE_EPS + +Sample JavaScript code: + :::javascript + //assumes you created a printer instance from previous instructions + myPrinter.enumerateSupportedControlLanguages(function(cb){ + // cb = Array of strings + // PRINTER_LANGUAGE_ZPL + // PRINTER_LANGUAGE_CPCL + // PRINTER_LANGUAGE_EPS + }); + +NOTE: WARNING: Ruby is NOT supported with the CPCL printer language. + +## 6- Begin Sending Printer Commands +Once your app finds and connects to a printer, it can begin sending commands. Printer behavior will vary depending on printer make, model and its current state. Consult your printer's technical documentation for printer-specific commands and syntax. + +In general, there are two fundamental ways to send commands: + +* In a string that includes raw printer commands +* In a series of commands stored in a file (i.e. ZPL, CPCL) + +### Sending a Raw String +To send a string to the printer, you use the [printRawString](../api//printingzebra#mprintRawString) method: + + :::javascript + // If my printer was in line mode I would see this text printed + myPrinter.printRawString('This is a test print'); + + // Example of sending a Zebra CPCL Command + // changing from line mode to ZPL mode + myPrinter.printRawString('! U1 setvar "device.languages" "ZPL"\r\n'); + +### Sending a Series of Commands +When a series of commands is used repeatedly by an app, they can be stored in a file (i.e. ZPL, CPCL) and modified programatically to perform a task, for example to print an address label. Command files can be generated manually or made using a tool provided by Zebra. They can be created in advance and delivered with the application. + +For example, let's say we created a file called `address.cpcl` that's stored in the application's `public` folder. This file will contain CPCL commands that will be used to print an address, and might look something like the one below. + +Sample terminal script file with embedded CPCL commands: + :::term + ! U1 SETLP 5 2 46 + AURORA'S FABRIC SHOP + ! U1 SETLP 7 0 24 + 123 Castle Drive, Kingston, RI 02881 + (401) 555-4CUT + +You can use the [RhoFile.join](../api/File#mjoinSTATIC) helper function and the [Application.publicFolder](../api/Application#ppublicFolder) property to create a fully qualified path to the `address.cpcl` file. This file path would then be passed to the [sendFileContents](../api/printingzebra#msendFileContents) method: + + +Sample JavaScript code: + :::javascript + var addressFile = Rho.RhoFile.join(Rho.Application.publicFolder, 'address.cpcl'); + + //assuming you made an instance and connected per the previous instructions + myPrinter.sendFileContents(addressFile,function(e){ + console.log(e); + // Will return a PRINTER_STATUS... CONSTANT String + }); + +## 7- Disconnect +Whenever your app is finished printing, it's important to disconnect from the printer. This is especially important for Bluetooth connections. To disconnect, use the [disconnect](../api/printingzebra#mdisconnect) method: + + :::javacript + //assumes you already created an instance object from previous instructions + myPrinter.disconnect(); + +## Using Files Stored On The Printer +Some printers have the ability to store command-file templates or other files useful for performaing print operations. To retrieve a list of files that exist on the printer, use the [retrieveFileNames](../api/printingzebra#mretrieveFileNames) method: + +Sample JavaScript code: + :::javascript + myPrinter.retrieveFileNames(function (e){ + // e.status : PRINTER_STATUS_SUCCESS, PRINTER_STATUS_ERROR + // e.fileNames : ARRAY of file names + // + }); + +Once the file names are known, your app can print to them, passing variables as specified within the ZPL or CPCL files themselves. This is done using either the [printStoredFormatWithArray](../api/printingzebra#mprintStoredFormatWithArray) method or the [printStoredFormatWithHash](../api/printingzebra#mprintStoredFormatWithHash) method. Both include three parameters: + +###Parameter 1- formatPathOnPrinter +This will be 'E:filename' where 'filename' is the name of the file that we sent in the previous step, or one that existed on the device (assuming the file is on the printer's 'E' partition) + +###Parameter 2- vars +This represents the data we want to pass to the label. + +`printStoredFormatWithArray` - An array of strings representing the data to fill into the format. For ZPL formats, index 0 of the array corresponds to field number 2 (^FN2). For CPCL, the variables are passed in the order that they are found in the format + +Sample JavaScript code: + :::javascript + myPrinter.printStoredFormatWithArray('E:LABEL.ZPL',['John Doe','123 East Main St','Smalltown, NY 11766'],function (e){ + // Will return a PRINTER_STATUS... CONSTANT String + }); + +`printStoredFormatWithHash` (supported by ZPL only) - A hash which contains the key/value pairs for the stored format. For ZPL formats, the key number should correspond directly to the number of the field in the format. Number keys should be passed as string ex: '1':'field1', '2':'field2' etc. + +Sample JavaScript code: + :::javascript + myPrinter.printStoredFormatWithHash('E:LABEL.ZPL',{ '1':'John Doe','2': '123 East Main St','3': Smalltown, NY 11766'},function (e){ + + // e = PRINTER_STATUS... CONSTANT String + if(e == 'PRINTER_STATUS_SUCCESS') + { + + } + }); + + +###Parameter 3- callback +This will return a [PRINTER_STATUS...](../api/printingzebra#Constants) constant as a string. + +## Printing Images +For printers with graphics support, images are printed using the [printImageFromFile](../api/printingzebra#mprintImageFromFile) method. For example, an image called `myImage.jpg` in your application's `public` folder could use the same [RhoFile.join](../api/File#mjoinSTATIC) helper function and [Application.publicFolder](../api/Application#ppublicFolder) property described above to create a fully qualified path to the `myImage.jpg` file. The file could then be passed to the [printImageFromFile](../api/printingzebra#mprintImageFromFile) method: + +Sample JavaScript code: + :::javascript + var imagefile = Rho.RhoFile.join(Rho.Application.publicFolder, 'myImage.jpg'); + + //assuming you made an instance and connected per the previous instructions + myPrinter.printImageFromFile(imagefile,0,0,{},function(e){ + + // e = PRINTER_STATUS... CONSTANT String + if(e == 'PRINTER_STATUS_SUCCESS') + { + + } + }); + +A callback for the [PRINTER_STATUS](../api/printingzebra#Constants) constant would return a string indicating whether the operation was successful. + +NOTE: Images larger than 1024x768 might take a long time or print incorrectly. Consult the printer manufacturer's documentation for image printing parameters. + +### Storing Images +Some Zebra printers support the storage of images. You can accomplish this by creating your own ZPL or CPL command set, or use the [storeImage](../api/printingzebra#mstoreImage) method: + +Sample JavaScript code: + :::javascript + //location of image on device + var imagefile = Rho.RhoFile.join(Rho.Application.publicFolder, 'myImage.jpg'); + + //destination of image on the printer. Must have partion specified + var destination = "E:LOGO.GRF" + + //assuming you made an instance and connected per the previous instructions + myPrinter.storeImageFromFile(destination,imagefile,0,0,{},function(e){ + + // e = PRINTER_STATUS... CONSTANT String + if(e == 'PRINTER_STATUS_SUCCESS') + { + + } + }); + + +## Platform Notes +### Windows Mobile / Windows CE +#### Requirements +Windows Mobile/CE require that a provided `printing-service` application is installed and always running in order to use the [Printing](../api/printing) and [PrintingZebra](../api/printingzebra) APIs. + +* Before installing the printing service on Windows Mobile devices, you first need to install the [.NET compact framework](http://www.microsoft.com/en-us/download/details.aspx?id=65) on your device. You may find the device installation package on your build machine at `C:\Program Files (x86)\Microsoft.NET\SDK\CompactFramework\v3.5\WindowsCE\NETCFv35.wm.armv4i.cab` +* Windows CE only - You'll also need to install the messaging framework found on your build machine at `C:\Program Files (x86)\Microsoft.NET\SDK\CompactFramework\v3.5\WindowsCE\Diagnostics\NETCFv35.Messages.EN.cab` on Windows 7. + +#### Printing-Service Installation +* The .cab file for the printing service is held inside the `printing-service` folder inside your RhoMobile Suite installation directory located at `C:\\printing-service\PrintingService.cab` + +#### Limitations +* The printing service currently supports a single client at a time. Multi-client printing will be introduced in a future version of RMS. +* The method [`Printer.requestState()`](../api/printing#mrequestState) does not work with Bluetooth printers. +* The method [`Printer.stopSearch()`](../api/printing#mstopSearchSTATIC) currently does not work. + +##Zebra Printers With USB Printing + +

                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                            DeviceDevice familyDevice model(s)Operating System(s)
                                                                            MZMZ 220, MZ 320Android, Mac OS X, Windows Mobile, CE, x86
                                                                            iMZiMZ 220, iMZ 320Android, Mac OS X, Windows Mobile, CE, x86
                                                                            RWRW 220, RW 420, RW 420 Print StationAndroid, Mac OS X, Windows Mobile, CE, x86
                                                                            P4TP4T, RP4T Passive RFID PrinterAndroid, Mac OS X, Windows Mobile, CE, x86
                                                                            ZD500RZD500R RFID PrinterAndroid, Mac OS X, Windows Mobile, CE, x86
                                                                            NOTE: Printing via USB is NOT supported on iOS devices.NOTE: Zebra's QL Plus and QLn series printers DO NOT support Android USB printing.
                                                                            + diff --git a/docs/en/5.5/guide/profiling.md b/docs/en/5.5/guide/profiling.md new file mode 100644 index 00000000..17e71681 --- /dev/null +++ b/docs/en/5.5/guide/profiling.md @@ -0,0 +1,133 @@ +# Performance Profiling + +To perform performance measurements or found applications bottlenecks you can use RhoMobile Profiler tool. + +RhoMobile Profiler use performance counters to calculate execution time of specific function/code. There are 2 types of counters: global and local: + +* Global counters created once and can be stopped/started many times. When Global counter destroyed, it log accumulative time of all start/stop intervals. +* Local counters can be stopped/started only once. While stopped, counter will log time interval between start and stop. + +## Profiler log. +When Counter stopped (Local counters) or destroyed(Global counters) information from counter will be logged in the following format: + +(log prefix) PRFILER| (counter name)( (counter time Minutes:Seconds:Milliseconds) ): START/STOP + +For example: + +I 06/18/2012 23:27:20:311 00002ffc PROFILER| BROWSER_PAGE (0:03:104) : STOP + +## Enable Profiler. +Profiler is configurable at build time in build.yml file(Turned Off by default): + + profiler: 1 + +Will turn on Profiler + +After Profiler ON/OFF - full rebuild is required. + +## Built-in performance counters. + +These counters start working after you turn on Profiler in build.yml: + +* ERB_RENDER - ERB-file render (Ruby) +* CTRL_ACTION - Controller action (Ruby) +* INDEX_ACTION - Index page render +* ERB_RENDER - ERB-file render (Ruby) +* BROWSER_PAGE - Browser page loading time (Native) +* SyncEngine components has several native counters: + + 'Sync' - Full sync time + + 'DB' - Time spend for database insert/update/delete while sync + + 'Net' - Time spend for network communication while sync + +These counters works only if you create them in application. You can create counter in controller action and destroy it after some operations: + +* Sqlite database (Native) + + 'SQLITE' - counter for whole time processing SQL query including data conversion , sqlite3_step and prepare statement + + 'SQLITE_EXEC' - sqlite3_step time only. + +To Enable Ruby Garbage collector logging modify rhoconfig.txt(set log level to Trace): + + MinSeverity = 0 + +There are two Profiler API available: Ruby and Native(C/C++). + +## RhoProfiler Ruby API Examples + +The [RhoProfiler Ruby API](..rhodesapi/rhoprofiler-api) contains the following static methods. + +* [create_counter](../rhodesapi/rhoprofiler-api#createcounter) creates a Global counter. +* [destroy_counter](../rhodesapi/rhoprofiler-api#destroycounter) destroys a Global counter. +* [start_counter](../rhodesapi/rhoprofiler-api#startcounter) starts a Local or Global counter. If a Global counter with this name exists, this global counter will be started. If no global counter exists, a local counter will be created and started. +* [stop_counter](../rhodesapi/rhoprofiler-api#stopcounter) stops a Global or local counter. +* [flush_counter](../rhodesapi/rhoprofiler-api#flushcounter) logs information from a counter (Local or Global). Counter does not stop or start. +* [start_created_counter](../rhodesapi/rhoprofiler-api#startcreatedcounter) - The counter will start only if it is already created previously (Global counter). + +Example of custom counter: + + :::ruby + def index + RhoProfiler.create_counter('Counter1') + + RhoProfiler.start_counter('Counter1') + function1() + RhoProfiler.stop_counter('Counter1') + + #do something + + RhoProfiler.start_counter('Counter1') + function2() + RhoProfiler.stop_counter('Counter1') + + RhoProfiler.destroy_counter('Counter1') #Will log summary of function1 and function2 execution time + end + +Example using 'SQLITE' built-in counter: + + :::ruby + def some_method + + RhoProfiler.create_counter('SQLITE') + + #do something: create/update objects for example + + RhoProfiler.destroy_counter('SQLITE') + + end + +## RhoProfiler C/C++ API. +RhoProfiler C/C++ API contains several defines to manipulate Performance Counters. Here is the list of defines: + + //Global accumulative counters + #define PROF_CREATE_COUNTER(name) // Create Global counter + #define PROF_DESTROY_COUNTER(name) // Destroy Global counter + #define PROF_START(name) //Start Local or Global counter. If Global counter with this name exist , this global counter will started. If no global counter exists, local counter will be created and started. + + #define PROF_STOP(name) // Stop Global or local counter. + #define PROF_FLUSH_COUNTER(name,msg) //Log information from counter(Local or Global). Counter does not stopped or started. + #define PROF_START_CREATED(name) //Counter will start only if it is already created previously(Global counter) + +Example: + + :::ruby + #include "statistic/RhoProfiler.h" + void testFunction() + { + PROF_CREATE_COUNTER("Counter1"); + + PROF_START("Counter1"); + function1(); + PROF_STOP("Counter1"); + + //do something + + PROF_START("Counter1") + function2(); + PROF_STOP("Counter1") + + PROF_DESTROY_COUNTER("Counter1") #Will log summary of function1 and function2 execution time + } diff --git a/docs/en/5.5/guide/push_notifications.md b/docs/en/5.5/guide/push_notifications.md new file mode 100644 index 00000000..6cc4ba36 --- /dev/null +++ b/docs/en/5.5/guide/push_notifications.md @@ -0,0 +1,180 @@ +# Push notifications + +## Push notifications and when to use them + +Traditional client/server applications work based on a request/response cycle: The client sends a request to the server and the server sends back a response (the client is said to *pull* information from the server). But there was once no way for the server to send (push) information to the client outside of a regular request cycle. + +Push notifications solved this problem. They're a way for the server to initiate a connection and send information to a client whenever there's an event of interest. This mechanism allows for updates to be delivered in near real-time instead of having to wait for the next synchronization. + +Depending on how they are implemented and delivered, there are two types of push notifications: + +* Native push notifications (Android, iOS), provided by the mobile operating system and third party infrastructure (Google / Apple) +* RhoConnect Push Service, built into RhoConnect Server and deployed in your choice of cloud and/or traditional server provider. + +**NOTE: This difference is particularly important on Android because Android's native notifications require accessing Google services (in particular, Google Cloud Messaging, or GCM) which are linked to the Google Play Store. Enterprise devices might not include access to the Play Store, so if you are deploying your application to the Enterprise Tablet or other professional-grade Android devices, be aware that Google Cloud Messaging may not be available and you will need to use RhoConnect Push Service instead.** + +In order to choose one or the other, you need to think about: + +* The devices your application will be deployed to, whether they can support platform-specific notifications or not (whether they include the Google Play Store). Be aware that RhoConnect Push Service is not available on iOS. +* Data protection / compliance with regulatory limitations in specific industries. For example, a law firm could be legally required to never send any of its data to a third party like Google or Apple. In cases like this, RhoConnect Push Service offers a way to keep all parts of the infrastructure under your control, with everything running on your own servers. + +>**Having trouble building an Android app with RhoElements 4.0.0 and Push capability?**
                                                                            +>Since being moved to Google Play services, GCM is no longer supported as a standalone jar file. If you're having trouble building an Android app with RhoElements 4.0.0 and Push capability, try these steps:

                                                                            +>1. [Download the GCM r03 sip file](http://dl-ssl.google.com/android/repository/gcm_r03.zip) from Google's repository.
                                                                            +>2. Copy it to sdk/extras and extract it.
                                                                            +>3. Rename the folder to 'gcm'
                                                                            +> + +## Setting up an app for native push notifications + +**NOTE: You only need to complete *one* of the setup sections, either "native" (this section) or ["RhoConnect Push Service"](#setting-up-your-app-for-rhoconnect-push-service-notifications) depending on which delivery backend you want to use. If you are not sure, check [what push notifications are and when to use them](#what-push-notifications-are-and-when-to-use-them). Once you have completed one of these, proceed to [Integrating push notifications in a RhoMobile app](#integrating-push-notifications-in-a-rhomobile-app). ** + + +### Native iOS notifications + + +Native iOS notifications use Apple's Push Notification Service (APNS) for delivery. + +**NOTE: You need an Apple iOS Developer account and a real device in order to use native push notifications in iOS. Testing on the iOS Simulator is not possible due to Apple's restrictions.** + +The following checklist contains the steps required to enable native push in iOS: + +* Sign up for an iOS Developer account if you do not have one already +* Create an APNS certificate in Apple's Developer Portal +* Install the APNS certificate in RhoConnect +* Update a provisioning profile in Developer Portal, download it and install it in your iOS device + +See [Setting Up RhoConnect Push on iOS](../rhoconnect/push-client-setup-ios) for detailed information on how to complete these operations. + +Once completed, proceed to [Integrating push notifications in a RhoMobile app](#integrating-push-notifications-in-a-rhomobile-app) + +### Native Android notifications + +Native Android notifications use Google Cloud Messaging (GCM) for delivery. The following checklist must be completed in order to integrate your RhoConnect server with GCM: + +* Create a Google API Project +* Enable the GCM Service +* Obtain an API key. Preferably, you will get at least one key for development and another for production, and limit the accepted IP addresses of the production key to those of your server(s) +* Add the API key(s) to `settings/settings.yml` in RhoConnect as `:gcm_api_key` +* Add the Google API Project number as the sender to `build.yml` in your RhoMobile app +* Optionally, if you want notifications to be visible to the user, configure `build.yml` to always display notifications or to do so only if the application is not running when the notification is received + +See [Setting Up RhoConnect Push on Android](../rhoconnect/push-client-setup-android) for the details on how to complete these steps. + +Once completed, proceed to [Integrating push notifications in a RhoMobile app](#integrating-push-notifications-in-a-rhomobile-app) + +## Setting up your app for RhoConnect Push Service notifications + +**NOTE: You only need to complete *one* of the setup sections, either this section ("RhoConnect Push Service") or ["Setting up your app for native push notifications"](#setting-up-your-app-for-native-push-notifications), depending on which delivery backend you want to use. If you are not sure, check [what push notifications are and when to use them](#what-push-notifications-are-and-when-to-use-them). Once you have completed one of these, continue with [Integrating push notifications in a RhoMobile app](#integrating-push-notifications-in-a-rhomobile-app). ** + +If you cannot use platform-specific notifications for whatever reason, RhoConnect Push Service still allows you to use push notifications in your app. See [Setting Up RhoConnect Push Service](../rhoconnect/push-client-setup-rps) for more information on how to set up this solution. Be aware that RhoConnect Push Service is not available on iOS. + +## Integrating push notifications in a RhoMobile app + +Once the server-side infrastructure is ready, reacting to push notifications in RhoMobile is really easy: just use the [Push API](../api/push) to register a callback that will be invoked when a notification is received. + +Each notification can contain one or more commands to be performed: + +* data source synchronization +* text alert +* sound alert +* vibration + +When your code receives a notification, inspect the `params` hash and process the different commands, such as in the following example: + +Ruby: + + :::ruby + def setup_push + Rho::Push.startNotifications(url_for(:action => :push_callback)) + end + + def push_callback + + # If the notification contains a message, it will be in the alert parameter + if @params['alert'] + Rho::Notification.showPopup("Push notification received with message: #{@params['alert']}") + end + + sources_to_sync = @params['do_sync'] # comma-separated list of data sources we must sync, or "all" + if sources_to_sync + if sources_to_sync=="all" # if the notification tells us to sync all sources, we will do just that + Rho::RhoConnectClient.doSync() + else # otherwise, we will sync only those sources mentioned in the notification + sources_to_sync.split(",").each do |source| + Rho::RhoConnectClient.doSyncSource(source) + end + end + end + end + +JavaScript: + + :::javascript + function setup_push_manual() { + Rho.Push.startNotifications(push_callback); + } + + function push_callback(params) { + // If the notification contains a message, it will be in the alert parameter + if (params.alert) { + Rho.Notification.showPopup("Push notification received with message: "+params.alert); + } + + var sources_to_sync = params.do_sync; // comma-separated list of data sources we must sync, or "all" + + if (sources_to_sync) { + if (sources_to_sync=="all") { // if the notification tells us to sync all sources, we will do just that + Rho.RhoConnectClient.doSync(); + } else { // otherwise, we will sync only those sources mentioned in the notification + var sources = sources_to_sync.split(","); + for (var i=0; i> Run Configurations** +* In the **left pane** of the **Run Configurations window** you'll see **RhoMobile Application**: + * **Double-click** it to create a **new Launch Configuration**
                                                                            + **OR**
                                                                            + * **Single-click its arrow** to **edit an existing Launch Configuration** (shown below)
                                                                            + +* With the desired Launch Configuration selected, **choose the Platform and Simulator type** +* **Click Run** to deploy and run your app in RhoSimulator + +![Run Configurations](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/run-configuration.png) + +In the example, a Run Configuration is shown for the iPhone platform and RhoSimulator. The resulting RhoSimulator screen should look similar to this: + +![Device Window](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/device-window.png) + +## 2- Examine Code With Web Inspector + +**RhoSimulator presents two windows**: One displays your application's UI, and the other exposes its code in a multi-tabbed window. The first is referred to as **the Device Window** (similar to the one above), and the second is **Web Inspector window** (below), a powerful debugging aid that allows you to inspect and edit the HTML and CSS of your web interface and immediately see the effects of your changes. + +![Web Inspector](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/web-inspector-window.png) + +### Examining the DOM + +In the context of modern web programming, **the 'DOM' refers to your HTML code as it will appear when running**. For example, while an HTML5 app might define certain variables, those variables contain no values until the app is actually running. So you might think of the DOM as HTML5 that's live and in use. + +You can **examine the DOM in the Elements tab** of Web Inspector. This tab shows the DOM tree structure of the HTML page that's currently displayed in the Device Window. You can select and examine the code or individual elements in the DOM tree by using one of the following methods: + +### Using the Element Picker + +Click on the 'Magnifying glass' icon in the bottom toolbar: + +![Magnifying glass icon](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/html-element-picker.png) + +Then, move to the Device Window and click on the HTML element you want to inspect: + +![Selecting an element](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/selecting-html-element.png) + +The selected element will then be highlighted in the Inspector Window, with its applied CSS styles shown in the right-hand pane and its heirarchy shown along the bottom: + +![Selected element](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/selected-html-element.png) + +### Using the Search Elements box + +You also can find particular attributes in the DOM using Search Elements. **Click inside the Search Elements box in the upper-right corner and enter text**, content or the tag name of an element or attribute you'd like to find. All items matching the search will be highlighted: + +![Search elements](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/search-elements.png) + +### Expanding/collapsing the DOM tree + +You also can **navigate directly to the required HTML element by expanding/collapsing the DOM tree** using the disclosure arrows to the left of all tags with children: + +![DOM tree arrows](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/dom-tree-arrows.png) + +## 3- Live-Editing HTML and CSS + +The Web Inspector permits live editing of HTML and CSS code and immediately renders your changes in the Device Window. This provides a quick way to preview HTML and CSS changes without having to go back to the IDE to edit, save and refresh. However, **these changes exist only within the simulator**. To make your changes permanent, you'll need to update your code files once you're satisfied with the changes. + +NOTE: Changes in RhoSimulator are temporary and apply only to the code running inside the simulator. To make changes permanent, you must update your HTML/CSS files separately. + +The following changes can be made live: + +### Editing an element attribute + +1. **Double-click the element attribute** name or value +2. **Edit** the text +3. Press **ENTER to apply** the change or **ESC to cancel** + +In the example below, a CSS class attribute is edited: + +![Edit attribute](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/live-edit-attribute.png) + +### Editing element inner text + +1. **Double-click the text *inside* the element** +2. **Edit** the text +3. Press **ENTER to apply** the change or **ESC to cancel** + +In the example below, the *Login* button's text was changed to *Sign in*: + +![Edit innertext](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/live-edit-innertext.png) + +### Editing an element tag + +1. **Double-click the element's tag name** +2. **Edit** the tag +3. Press **ENTER to apply** the change or **ESC to cancel** + +![Edit tag](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/live-edit-tag.png) + +### Deleting an element + +1. **Single-click the element** +2. **Press Delete** key + +### Editing a style declaration + +1. Inside a CSS rule, **double-click the property or value** part of the declaration +2. **Edit** the property or value +3. Press **ENTER to apply** the change or **ESC to cancel** + +In the example below, the *text-align* style was changed to *right*: + +![Edit declaration](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/live-edit-declaration.png) + +### Disabling a style declaration + +1. Inside a CSS rule, **locate the appropriate checkbox to the right of the declaration** +2. **Add a check to temporarily enable**; remove a check to temporarily disable + +In the example, the *text-align* style *left* is temporarily disabled: + +![Disable declaration](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/live-disable-declaration.png) + +### Adding a style declaration + +1. **Double-click the opening or closing braces** of a CSS rule +2. **Type in the property name** followed by a colon and the value +3. Press **ENTER to apply** the change or **ESC to cancel** + +In the example, a new *border-style* is added: + +![New declaration](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/live-new-declaration.png) + +### Creating a new style rule + +1. **Click the small 'Gear' icon** to the right of the *Styles* heading +2. **Select 'New Style Rule'** +3. **Edit the selector as required** and press Enter (or ESC to cancel) +4. **Type in the property name** followed by a colon and the value +5. Press **ENTER to apply** the change or **ESC to cancel** + +![New rule](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/live-new-rule.png) + +### Editing a style selector + +1. Under the Styles heading, **Double-click the style rule's selector** +2. **Edit** the text +3. Press **ENTER to apply** the change or **ESC to cancel** + +![Edit selector](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/live-edit-selector.png) + +### Other Web Inspector Tabs + + + +There are a few other Web Inspector tabs that might be useful for debugging your app. + +#### Resources Tab +The **Resources tab** allows you to see the resources being used by the current Webview page. Reources can include outside assets being called into your app such as **images, JavaScript, stylesheets and cookies**. Inspecting the resources can be useful if you want to make sure a particular resource has been loaded. This tab also can provide insight into other HTML5 features such as WebSQL and localStorage, if present. + +![Resources Tab](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/resources.png) + +NOTE: WebSQL and localStorage are HTML5-specific features that are used by certain WebKit-based browsers. They are not related to the Rhom database provided by RhoMobile. + +#### Network Tab +The Network tab **measures and displays the time required for HTTP requests** made by an application. Clicking on any of the resources in the left-hand pane will visually represent the delay as its headers and content are loaded and AJAX and other calls are made to remote servers. Data displayed when hovering over 'Latency' and 'Timeline' columns can be used to help optimize load-time performance. + +![Network Tab](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/network.png) + +#### Timeline Tab +The Timeline tool **measures and displays the rendering time of each element of the user interface**, presenting a visual display similar to that of the Network tab. The Timeline tab is useful for finding bottlenecks in front-end UI or DOM performance. + +More information about Timeline can be found starting at 25:10 of Zebra's [Front-End UI Optimization Webinar](https://developer.motorolasolutions.com/docs/DOC-1661). This one-hour video contains useful information about detecting reflows and other common problems that can bring mobile apps to a crawl. + +##4- Debugging JavaScript Code + +####Scripts Tab +The Web Inspector's **Scripts tab** allows you to set breakpoints and inspect variables in your JavaScript code. + +### Setting breakpoints, inspecting variables + +1. From the dropdown near the top of the Scripts tab, **select the JavaScript source file** you want to debug. +2. To set a breakpoint at a code line, **click its line number**. A breakpoint flag will appear. +3. Next time you run, the app will pause at breakpoints (or after pressing the Pause button). +4. When paused, **inspect the values of JavaScript variables** under the 'Scope Variables' header, at right. + +![Breakpoints](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/javascript-breakpoints.png) + +**NOTES:**
                                                                            + +* **Local variables are displayed under** the **'Scope Variables'** heading. +* If you **switch to a different stack frame under the 'Call Stack' heading**, the local variables displayed will match the currently selected stack frame. +* **Use 'Watch Expressions' to evaluate an expression every time** the code is paused. These can include variables or any valid JavaScript expression. +* To **remove a breakpoint, click on its line-number** flag. +* **Breakpoints also are presented in a list view** under the 'Breakpoints' heading at right. +* **Use the checkboxes in list view to toggle Breakpoints** on and off. + +####Console Tab + +The **Console tab allows JavaScript execution and debugging** and displays log messages generated by your code and by the system it's running on. + +### Using the Console + +Viewing the Console tab provides the greatest exposure for displaying large numbers of log messages: + +![Console](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/console.png) + +You also can **toggle a Console pane** while in other tabs **by using the Show Console button** at the bottom-left corner of other tabs: + +![Embedded Console](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/console-embedded.png) + +#### Logging + +The Console logs errors and warnings from the system and logs messages generated by your application code. Messages can be filtered by type whether using the Console tab or viewing the Console through a pane: + +![Filtering messages](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/filtering-console-messages.png) + +###Generating log messages + +Log messages are not visible by the end-user, but can be extremely useful for debugging. Log messages are generated from JavaScript using the console.log() method: + +Sample JavaScript code: + + :::javascript + console.log('Hello, world'); + + +#### Interactive JavaScript + +In adddition to displaying log messages, the Console provides a fully interactive JavaScript execution environment that lets you **evaluate valid JavaScript expressions, examine variables or object properties and invoke methods on objects**. + +![Interactive JavaScript](http://rhodocs-images.s3.amazonaws.com/guide/debugging_with_rhosimulator/interactive-javascript.png) + +### Using Chrome's Web Inspector + +Optionally, **you can debug the visual elements of your app with Chrome's Web Inspector instead of the one in RhoSimulator**. Google urges web developers to use [Google Chrome Canary](https://www.google.com/intl/en/chrome/browser/canary.html) so they always have latest version Chrome DevTools, but all recent versions of Chrome include Web Inspector. + +1. **Once your app is open in RhoSimulator, point Chrome to**:
                                                                            + +[http://localhost:9090/webkit/inspector/inspector.html?page=2](http://localhost:9090/webkit/inspector/inspector.html?page=2). + +2. If neccessary, **open the JavaScript console: View>>Developer>>JavaScript Console** + +Alternatively, you can navigate to [http://localhost:9090](http://localhost:9090) and click the link that references your start page (for example http://127.0.0.1:49964/**app/index.erb** if your app starts at /app/index.erb). You should see a screen similar to this: + +>![Remote Inspector Landing Page](https://s3.amazonaws.com/rhodocs/guide/debugging_js/remote_inspector_landing_page.png) +
                                                                            + +## On-Device Debugging With Weinre + +Weinre is a must-have developer tool for testing or debugging RhoMobile JavaScript applications. Although lots of testing and analysis can be done using RhoSimulator, hardware features such as [Barcode](../api/barcode) are unavailable in RhoSiumulator, and applications often look or behave differently when running on a device. Weinre solves these problems. Acting like a remote Web Inspector, the JavaScript Console in Weinre allows you to get familiar with the RhoMobile APIs right from the tab. This is faster and easier than fumbling through logs. + +This guide is modeled after a 14-minute [Weinre webinar](https://www.youtube.com/watch?v=aSTXEEAfJ6M) that shows most of what we cover here in action. We'll be using the [Barcode Example](https://github.com/rhomobile/rho-samples/tree/master/BareBones/BarcodeExample) app for all of the examples in this guide. You're welcome to download the app and follow along, but it's by no means necessary. You could follow along using your own app, or simply play around with the APIs and try out some code. + + +###1- Install Weinre + +NOTE: WARNING: You must have admin/sudo privileges to install Weinre, and the target device must be on the same Wi-Fi network as the development system. + +Weinre is a Node.js application and comes delivered via a Node Package installed with the `npm` command. Since Node.js is installed along with the Rhomobile suite, installing Weinre is as simple as running this Terminal command: + + :::term + $ npm -g install weinre + +Some Mac users may have to include the 'sudo' command: + + :::term + $ sudo npm -g install weinre + +For further installation and configuration instructions, visit [Weinre's installation site](http://people.apache.org/~pmuellr/weinre/docs/latest/Installing.html). If you did not install RhoMobile Suite, you can still use Weinre, but you might have to install [Node.js](https://nodejs.org/) separately. + +###2- Start Weinre + +**From the command line, launch Weinre using the `boundhost` option.** This will bind it to your machine's local IP address: + + :::term + $ weinre --boundhost + +NOTE: Launching Weinre without this option will cause it to bind with the `localhost`, which is inaccessible from apps on a device. + +**Weinre will display an IP address and port number similar to this:** + + :::term + 2013-10-31T00:24:07.549Z weinre: starting server at http://192.168.1.128:8080 + +**Point a browser to that address and port to verify that Weinre is running correctly**. You should see a page similar to the following: + + + +###3- Enable Weinre In Your App + +If all went well in Step 2, your browser is displaying the Weinre Inspector Remote console. In the section labeled 'Target Script,' you'll see a string that contains a URL with your local IP address and port number, plus the name and path of the script file that Weinre needs to communicate with the target device. + +Lower in the Target Script section is an example of how to embed the Target Script string between `script` tags: + +####EXAMPLE: +`` + +**Copy and paste the example string (above) into the `barcode_enumerate.html` file (or the corresponding file for your app). Then copy your *actual* URL string referenced earlier and use it to replace the *example* URL. Be sure to leave the quote marks on either side of the URL**. + +>TIP: In RhoStudio, the default double-click action for an HTML file is to open its browser representation in the editor. To edit the HTML itself, right-click the file, select 'Open With' and choose 'Text Editor' as shown below. + + + +Here's what the line should look like in the HTML: + + + +###4- Start the debug client UI +**Start Weinre's debug interface by clicking the link under `Access Points` in the Weinre Console**: + + + +#### Debug Client UI + +The image below shows the 'Remote' tab of Weinre's Debug Client UI. The 'Targets' and 'Clients' sections contain one device each, and the green text indicates that both devices are communicating. + +The inset image is a screenshot from the target Android device that's being displayed by an app called [Droid@Screen](http://droid-at-screen.ribomation.com/). This useful screencasting tool uses USB and [ADB](http://developer.android.com/tools/help/adb.html) to stream screen shots to the development host. + + + +At this point, can inspect your app just as you would with the Web Inspectors of RhoSimulator or Chrome. The Elements tab shown below demonstrates two-way communication between the device and the development host. Clicking on an element in the HTML will cause that element to be highlighted on the device's UI. + + + +The Elements tab can be used for on-the-fly changes to CSS styling, API and method calls and any and all app UI settings. In the example below, the button text was changed from 'Enumerate' to 'Changed!' simply by editing the test in the Elements tab. + +

                                                                            +
                                                                            +
                                                                            +

                                                                            Button text 'Enumerate'

                                                                            + +
                                                                            +
                                                                            +

                                                                            Button text 'Changed!'

                                                                            + +
                                                                            +
                                                                            +
                                                                            + +### Issuing API calls with Console + +One of the most versatile components of Weinre is its Console. Not only does it offer classic capabilities such as device visibility and monitoring during operation, but the Weinre Console also can access all of a device's hardware fearures, issue commands and report how the device reacts. + +The example below shows results from an attempt to use the JavaScript API to check the target platform, use the camera to scan a barcode, and issue a command to the [ScreenOrientation API](http://127.0.0.1:9393/en/edge/guide/screen_orientation) (which returned an error). + + + +In the example, I used the Console to verify that my JavaScript APIs are functioning properly. A return of the correct system platform of 'Android' proves that the System API is working. A return of the correct scanned barcode value likewise proves that the Barcode module is working properly. + +>**There's another important benefit of the Weinre console.**
                                                                            +Notice that when the barcode callback handler function is executed, we are using the form `console.log(e)`, where `e` is the callback return object. That allows us to inspect the object right in the console. This simplifies validation because we see that it contains a `barcode` property and a `status` property, exactly as described in the [Barcode.take( )](../api/barcode#mtake) method description. Alternative means--such as adding code for outputting to a log, then for seaching and retrieving the information from the device--can be time consuming, tedious and error-prone. + +### Extension Inclusion + +Now we turn to the error thrown by the [ScreenOrientation](../api/screenorientation) API call: `TypeError: cannot call method 'normal' of undefined.`
                                                                            + +This indicates that it cannot find the module, and reminds us that the ScreenOrientation API is not included in RhoMobile apps by default. To include it in our build, it must be listed in the extensions section of the app's build.yml before the app is rebuilt: + + + +
                                                                            +
                                                                            +

                                                                            + Since we did not remove the target script line from the HTML, the app should connect to Weinre as soon as it is rebuilt and activated. And now that the module is included and the framework is now aware of this module, the module name will auto-complete as it's typed into the Console. And instead of returning an error, the API call will change the orientation of the screen and return what it is supposed to: VOID, which in the console is represented by a null return. +

                                                                            +

                                                                            + To determine which extensions you'll need to add to your build.yml, please see the API Summary Page in our docs and click on the API you wish to use. The resulting module page will describe what needs to be done to use any given API. +

                                                                            +
                                                                            +
                                                                            +

                                                                            Auto-Completing Code

                                                                            + +

                                                                            Extension Working properly

                                                                            + +
                                                                            +
                                                                            + + + + + +## On-Device Debugging With Chrome + +If you're building an Android app and have a device with Android KitKat 4.4 or higher, [Google Remote Debugging](https://developer.chrome.com/devtools/docs/remote-debugging) is an alternative to Weinre that's a bit easier to install and offers some fine visuals for testing, debugging and fine-tuning your app while it's running on the device. + +Google Remote Debugging works with native Android apps that use WebView--such as those built with RhoMobile--as well as purely browser-based apps. It includes live screencasting from the remote unit to the development host, and supports port forwarding and virtual host mapping in case your device needs to access a development server. + +###Requirements + +* Mac OS X or Windows development host +* Chrome 32 or later installed +* A USB cable for connecting the target to the dev. host +* A target device running Android 4.4 (KitKat) or later +* USB debugging enabled on target +* An app configured for WebView debugging + +###1. Enable Device Debugging +The target device must have USB debugging enabled. This feature is found in **Settings >> Developer Options** panel, which is hidden by default. + +![Developer Options](http://rhodocs.s3.amazonaws.com/guide/debugging_js/Android_developerOptions.png) + +Here's how to **unhide Developer options** (if neccessary) **and enable USB debugging**: + +1. Go to **Settings >> About Phone** +2. **Go to the 'Build Number' box** (by scrolling all the way to the bottom) +3. **Tap the Build Number box seven times** +4. Then, go back to Settings and **tap Developer Options** +5. **Enable USB Debugging** by checking its box + +###2. Discover Device (in Desktop Chrome) +If you haven't already done so, **connect your device to an available USB port on the development host** and **enable device detection in Chrome**: + +>![Developer Options](http://rhodocs.s3.amazonaws.com/guide/debugging_js/Chrome_detect_USB.png) + +1. Open a browser window and **enter 'chrome://inspect'** in the address bar. You should see a screen similar the one above. + +2. **Check the 'Discover USB Devices' checkbox**. Your mobile device should appear along with an alert on the device. + +3. **Tap OK on the device** to complete the connection + +4. Linux- and Mac-based developers can skip to the next step. **Developers on Windows must install a USB driver** to make a USB-attached Android device visible. Visit [Google's USB Driver page](http://developer.android.com/tools/extras/oem-usb.html) for instructions and links to OEM drivers for your brand of hardware. + +5. The final step is to **configure WebView for debugging**, which must be done from within the app. Fortunately, RhoMobile developers can skip this step too because the WebView components used by the RhoMobile Suite are automatically configured for debugging when deployed to devices with debug mode enabled. + +6. At this point you should be ready to begin debugging. Once your app is deployed and running on the device, the chrome://inspect page should look something like the one shown below, with your device and a link to its debug-enabled WebViews. **To begin debugging, click an inspect link.** + +
                                                                            + +## Running RhoSimulator From the Command Line + + RhoSimulator can be executed from the command line and thereby integrated with your favorite IDE or inspected with alternative tools. To run RhoSimulator from the command line, use one of the following platform-specific commands from within the folder containing the app to be simulated: + +* Android + + rake run:android:rhosimulator + +* iOS + + rake run:iphone:rhosimulator + +* Windows Phone 8 + + rake run:wp8:rhosimulator + +* Windows Mobile + + rake run:wm:rhosimulator + +* Windows (desktop) + + rake run:win32:rhosimulator + + diff --git a/docs/en/5.5/guide/rhoArchitecture.md b/docs/en/5.5/guide/rhoArchitecture.md new file mode 100644 index 00000000..852b3819 --- /dev/null +++ b/docs/en/5.5/guide/rhoArchitecture.md @@ -0,0 +1,378 @@ +# RMS 5.4 Supported Platforms + +The RhoMobile Suite (RMS) is an integrated development environment for Mac OS X and Windows development hosts that can target multiple mobile-device platforms from a single code base. RhoMobile apps employ an HTML front-end that presents the UI component and passes device calls through to the underlying hardware. RhoStudio also supports native app development. + +**New in RMS 5.4 is support for the MC92 with Android KitKat and the [TC8000](https://www.zebra.com/us/en/products/mobile-computers/handheld/tc8000.html), Zebra's revolutionary new touch mobile computer** running Android KitKat. The latest version also supports Apple iOS 9.0 and can remap the Android keyboard to produce keycodes for Windows Mobile or for custom needs as required. + +For more information about this and prior releases, including bug fixes and issue resolutions, please [download the RMS 5.4 release notes](http://rhomobile-suite.s3.amazonaws.com/5.4/5.4.0/Release_Notes_RMS_5_4.html). + +##Supported Mobile-Device Platforms + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                            Device imageOperating system familyDevice(s)Operating System(s)
                                                                            AndroidZebra devices (see below), third-party devices (ARM and x86)Android 2.3 to 4.4: Gingerbread, Ice Cream Sandwich, Jelly Bean, KitKat
                                                                            AndroidThird-party consumer tablets and smartphones (ARM and x86)Android 5.1 Lollipop
                                                                            Apple iOSiPad, iPhone, iPod TouchiOS 6, iOS 7, iOS 8, iOS 9
                                                                            Windows Mobile/CEZebra devices (see below), third-party devicesWM6.x Pro, WM 6.0 Std, WinCE 5, WinCE 6, WinCE 7, WinXPe
                                                                            WindowsThird-party laptops, tablets and desktopsWindows 7, Windows 8, Windows 8.1
                                                                            + +**NOTE: For more information about supported devices and operating systems, please refer to its accompanying documentation and [download the latest RMS release notes](http://rhomobile-suite.s3.amazonaws.com/5.4/5.4.0/Release_Notes_RMS_5_4.html).** + +##Supported Zebra Devices +RMS 5.3 has been approved for building apps that target the following Zebra Enterprise Mobility devices: + +

                                                                            Mobile Computers

                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                            Device imageDevice familySupported model(s)Operating system(s)
                                                                            ES400ES400Windows Embedded Handheld 6.5
                                                                            ET1ET1 (Enterprise Tablet), ET1 WANAndroid 4.1 (JellyBean)
                                                                            MC2100*MC2100, MC2180Windows CE 6.0 Core
                                                                            MC3100MC3100R, MC3100S, MC3190G, MC3190R, MC3190S, MC3190ZWindows CE 6.0 Professional,
                                                                            Windows Embedded Handheld 6.5
                                                                            MC32N0MC32N0Windows CE 7.0,
                                                                            Android 4.1 (JellyBean)
                                                                            MC40MC40Android 4.4 (KitKat)
                                                                            TC55TC55Android 4.4 (KitKat)
                                                                            TC70TC70 GA2 (rebranded device)Android 4.4 (KitKat)
                                                                            TC75TC75Android 4.4 (KitKat)
                                                                            TC8000TC8000Android 4.4 (KitKat)
                                                                            MC18MC18Windows CE 7.0,
                                                                            Android 4.4 (KitKat)
                                                                            WAP4WorkAbout Pro 4Windows CE 6.0
                                                                            MC45MC45Windows Embedded Handheld 6.5
                                                                            MC55MC5574, MC5590Windows Embedded Handheld 6.5
                                                                            MC55A0MC55A0Windows Embedded Handheld 6.5
                                                                            MC55N0MC55N0Windows Embedded Handheld 6.5
                                                                            MC65MC659BWindows Embedded Handheld 6.5
                                                                            MC67MC67Windows Embedded Handheld 6.5,
                                                                            Android 4.1 (JelyBean)
                                                                            MC70MC7004, MC7090, MC7094, MC7095Windows Mobile 6.1
                                                                            MC75MC7506, MC7508, MC7596, MC7598Windows Embedded Handheld 6.5
                                                                            MC75aMC75A0, MC75A6, MC75A8Windows Embedded Handheld 6.5
                                                                            MC9100MC9190-G, MC9190-ZWindows CE 6.0 Professional,
                                                                            Windows Embedded Handheld 6.5
                                                                            MC9200MC92N0Android KitKat,
                                                                            Windows CE 7.0,
                                                                            Windows Embedded Handheld 6.5
                                                                            MC9500MC9590, MC9596, MC9598, MC959B (WM6.1)Windows Mobile 6.1, Windows Embedded Handheld 6.5
                                                                            + +* The MC2100 family of devices is supported only by RhoElements 2.1.
                                                                            +

                                                                            + +

                                                                            Vehicle Computers

                                                                            + + + + + + + + + + + + + + + + + + + +
                                                                            Device imageDevice familySupported model(s)Operating system(s)
                                                                            VC6000VC6000, VC6096Windows Embedded Handheld 6.5
                                                                            VC70VC70Windows CE 7.0
                                                                            + +

                                                                            Micro Kiosks

                                                                            + + + + + + + + + + + + + +
                                                                            Device imageDevice familySupported model(s)Operating system(s)
                                                                            MK3100MK3100, MK3190Windows CE 7.0
                                                                            + +

                                                                            Wearable Computers

                                                                            + + + + + + + + + + + + + + +
                                                                            Device imageDevice familySupported model(s)Operating system(s)
                                                                            WT41N0WT41N0Windows CE 7.0
                                                                            + +## Device Memory and Other Considerations +Memory constraints are important to consider, particularly when targeting the older devices supported by RhoElements. The following points might be helpful to keep in mind: + +* RhoElements requires a *minimum* of 128MB physical device RAM
                                                                            + +* The more RhoElements apps running on a device, the greater its memory requirement; consider using [TabBar](../api/NativeTabbar) to combine several individual apps + +* Use the [Memory API](../../2.2.0/rhoelements/memory) and memory logs to monitor your app's memory requirements + +* For low-end Zebra CE devices, try using Control Panel to increase available program memory + +* Limiting the use of JavaScript frameworks will minimize an app's RAM footprint + +* Don't rely too heavily on performance tests for JavaScript and CSS found online unless they're written specifically for mobile devices + +* To maximize performance, JQueryMobile is not included in Windows Mobile/CE devices by default + +* An active [RhoMobile developer community](https://developer.motorolasolutions.com) offers forums, blogs, webinars and other useful resources to aid in your development efforts + + +##Compatibility Alerts + +* **RMS 5.3 supports printing via USB from Android apps** to a subset of [Zebra printers that support USB printing](printing#zebra-printers-with-usb-printing). + +* **The TC55 supports [4.0 APIs](apiusage#api-migration-table) and only a subset of [2.2 APIs](apiusage#using-22-apirsquos)**. Applications developed using certain 2.2 APIs might need to be rebuilt using a newer version of the API. For example, apps built with the [2.2 Scanner API](../../2.2.0/rhoelements/scanner) must now use the [5.x Barcode API](../api/barcode). Please consult the [migration table](apiusage#api-migration-table) for more information. + +* **The MC3190-Z and MC9190-Z devices require an [RFID plugin](../../2.2.0/rhoelements/rfid) to be installed separately**. This plug-in was originally developed for RhoElements version 2.2 but is still supported. + +* **Only local deveopment is supported for Micro Kiosk (MK) devices**. Zebra development options for supported MK devices include [RhoMobile Suite](http://rhomobile.com/) and [Enterprise Browser](http://goo.gl/V9zMxD). The use of [RhoMobile.com](../../hosted/guide/remote-build-guide) is not supported for building apps for MK devices. + +* **When using JQM transitions on Windows Mobile or Windows CE devices**, you may notice that the transition animations do not occur. This is due to insufficient processing resources on the device. + +
                                                                            + +##Deprecated Zebra Devices +**The following Zebra Devices are not supported in RMS 5.3 and later** (but can still be targeted by RMS versions earlier than 5.1): + +

                                                                            Mobile Computers

                                                                            + + + + + + + + + + + + + + + + + + + +
                                                                            Device imageDevice familyDeprecated model(s)Operating system(s)
                                                                            MC3000MC3000 (CE 5.0 only), MC3090Windows CE 5.0
                                                                            Windows Mobile 6.1
                                                                            MC9000MC9090, MC9097, MC9094Windows CE 5.0
                                                                            Windows Mobile 6.1
                                                                            + +

                                                                            Micro Kiosks

                                                                            + + + + + + + + + + + + + + + + + + + +
                                                                            Device imageDevice familyDeprecated model(s)Operating system(s)
                                                                            MK3000MK3000, MK3090Windows CE 5.0
                                                                            MK4000MK4000, MK4090Windows CE 5.0
                                                                            +

                                                                            Vehicle Computers

                                                                            + + + + + + + + + + + + + +
                                                                            Device imageDevice familyDeprecated model(s)Operating system(s)
                                                                            VC5090VC5090Windows CE 5.0
                                                                            + +

                                                                            Wearable Computers

                                                                            + + + + + + + + + + + + + +
                                                                            Device imageDevice familyDeprecated model(s)Operating system(s)
                                                                            WT4090WT4070, WT4090Windows CE 5.0
                                                                            + +###Compatibility Alert +>Support for older or deprecated device families such as the MC9000 and MK4000 can be found in versions of RhoElements prior to 5.1. For access to earlier RMS versions, visit [Launchpad](https://developer.motorolasolutions.com/community/rhomobile-suite) and click on **Resources>>Download**. diff --git a/docs/en/5.5/guide/rho_ruby.md b/docs/en/5.5/guide/rho_ruby.md new file mode 100644 index 00000000..5989673b --- /dev/null +++ b/docs/en/5.5/guide/rho_ruby.md @@ -0,0 +1,14 @@ +# The Rhomobile Ruby Environment + +Our C/C++ Ruby implementation is based on original Ruby C code, 1.9 release and support such core classes and module as: + +BasicObject, Object, Module, Class, Integer, Float, Numeric, Bignum, Rational, Complex, Math, String, StringScanner, StringIO, Array, Hash, Struct, Regexp, RegexpError, MatchData, Data, NilClass, TrueClass, FalseClass, Comparable, Enumerable, Enumerator, Converter, Marshal, IO, Dir, Time, Date, Signal, Mutex, Thread, ThreadGroup, Process, Fiber, FiberError, Method, UnboundMethod, Binding, RubyVM, GC, Exception, SystemExit, fatal, SignalException, Interrupt, StandardError, TypeError, ArgumentError, IndexError, KeyError, RangeError, ScriptError, SyntaxError, LoadError, NotImplementedError, NameError, NoMethodError, RuntimeError, SecurityError, NoMemoryError, EncodingError, CompatibilityError, SystemCallError, Errno, ZeroDivisionError, FloatDomainError, IOError, EOFError, ThreadError + +We are using Rubinius specs to test Ruby compatibility across different platforms. + +## Rhomobile Ruby Implementation Limitations +Our Ruby implementation is based on Ruby 1.9.2.p290 but, there are a few main differences between our implementation of Ruby and core Ruby 1.9.2: + +* `eval` is disabled for string evaluation because of limitations with iOS. +* `eval` for blocks **is** functional. +* Currently, Ruby threads do not work on Android. This is a known issue and is in the process of being fixed. \ No newline at end of file diff --git a/docs/en/5.5/guide/rhom_angular.md b/docs/en/5.5/guide/rhom_angular.md new file mode 100644 index 00000000..0ffbfdc7 --- /dev/null +++ b/docs/en/5.5/guide/rhom_angular.md @@ -0,0 +1,506 @@ +# Using Rhom in JavaScript with Angular.js +In past versions of RhoMobile, applications were developed with a combination of HTML and JavaScript for the view plus Ruby for the controllers. That approach is still supported but in RhoMobile 5.0 all the features of the platform can be accessed using JavaScript. Anything you can do in Ruby, can be done in JavaScript and it is now possible to build applications without writing any Ruby code at all. In this guide we will see an example of building an application in 100% JavaScript + +## Why Angular.js +If you are familiar with jQuery, you already know that while it provides a very helpful set of functions to manipulate the DOM, following large chains of callbacks and DOM operations becomes a maintenance problem very quickly, not to mention that you still have to write a lot of code to keep your models and views in sync with each other. + +[Angular.js](http://angularjs.org) has emerged as a favorite framework for developing data-intensive applications, thanks to its emphasis on declarative programming and data binding. With Angular.js, you can turn your HTML code into a two-way data binding template just by adding a few attributes and a small snippet of code. Then, without any other effort on your part, Angular.js will keep your views updated whenever you make changes to your model + + +## Getting started with Angular.js +You can get started with Angular.js with very little code. Suppose you have a list of products you want to display, with each product having `name` and `brand` properties. + +HTML: + + :::html + + + + + +
                                                                            +
                                                                            Products
                                                                            + +
                                                                              + +
                                                                            • Name: {{product.name}}, Brand: {{product.brand}}
                                                                            • +
                                                                            +
                                                                            + + + + +JavaScript: + + :::javascript + var myApp = angular.module('myApp',[]); // initialize Angular + + myApp.controller("MyCtrl", function($scope) { // declare a controller with the same name we used previously in our HTML + $scope.products = [{ // populate the "products" array + name: "product1", + brand: "brand1" + },{ + name: "product2", + brand: "brand2" + }]; + }); + +These snippets will, as you would expect, result in the list of products being displayed on the page. In order to know more about how and why they worked, we need to know about some Angular.js concepts such as "application", "scope", "directives" and "services". + +## Directives +A directive is a link between HTML and JavaScript: it is the way you connect a particular HTML tag with some dynamic behavior, either from the built-in Angular library or from your own code. + + :::html + +
                                                                              + ... +
                                                                            + +### Brief notes on directive naming and invocation +* Directives are defined in JavaScript code and they use camelCase for their names +* When adding a directive to an HTML tag, you convert the camelCase name to snake_case and optionally (but highly recommended) prefix it with `data-` to make it valid HTML5 + +Examples: + + :::html +
                                                                              + + +## Scopes +At a high level, a scope contains your model and lets your controllers and views interact with it. When you change a value in the scope, the change is propagated to any other part of the application. Let's expand on our previous example and add a way for the user to minimally interact with the application. + + :::javascript + myApp.controller("MyCtrl", function($scope) { + $scope.products = [{ + name: "product1", + brand: "brand1" + },{ + name: "product2", + brand: "brand2" + }]; + + + + $scope.switchProducts = function() { + this.products=[{ + name: "product3", + brand: "brand3" + },{ + name: "product4", + brand: "brand4" + }]; + }; + }); + +In the HTML code, we will add a simple button: + :::html +
                                                                              +
                                                                              Products
                                                                              +
                                                                                +
                                                                              • Name: {{product.name}}, Brand: {{product.brand}}
                                                                              • +
                                                                              + + +
                                                                              + +What we have done here is: + +* Add a new function to the scope. When this function is called, the "products" member of the scope will be substituted with a different array +* Add an HTML button with an `ngClick` directive. `ngClick` binds the `onclick` event to an expression, which will often be just a function call. The expression is evaluated in the context of the scope, that is, within the expression, `this` refers to the scope, hence why the `switchProducts` function sets `this.products`. + +Note that when we built the first version of the example, we did not write any code to read values from the scope and put them into the HTML, the `{{ }}` syntax took care of that automatically. Note also that we have not written any code to update the HTML after we make changes to the scope either. If you run the example, however, it will do just what you expect: when you click the button, the HTML changes automatically and shows product3 and product4. + +> Note: Scopes are the central concept everything revolves around in Angular.js: the scope becomes the ultimate truth holder for your application; whatever data is inside the scope is what the rest of the application sees. Keep this in mind when designing your services and controllers. + +## Services and Dependency Injection +### Dependency Injection in a nutshell +**NOTE: See the [Wikipedia entry for Dependency Injection](en.wikipedia.org/wiki/Dependency_injection) for a more thorough explanation.** + +In order to create `MyCtrl` in the example, we called `myApp.controller` with two parameters, a name and a function: + + :::javascript + myApp.controller("MyCtrl", function($scope) { + ... + }); + +The function has a parameter called `$scope`, through which it receives the scope for the controller. When Angular.js calls this function, it sees that there is a parameter with the name `$scope`, recognizes that name and passes the appropriate value. This style of declaring your dependencies and having them fulfilled automatically is called "Dependency Injection", because you do not connect your dependencies manually, they are "injected" into your code automatically. + +### Services +In Angular.js, a "Service" is a [singleton](http://en.wikipedia.org/wiki/Singleton_pattern) that can be injected as a dependency. In your own applications, you will often find it useful to define your own services (there is an example below in the section called [Integrating Rhom into Angular.js](#integrating-rhom-into-angularjs)). + +Services allow you to augment the dependency injector, adding your own objects to it. There are several ways to define a service, we will see the "factory" pattern here: create and return the object that will be injected: + + :::javascript + // create a new service with the name "GreetingService" + myApp.factory("GreetingService", function() { + + var greetings=["Hello","Welcome"]; + + // build the service + var service = {}; + + service.randomGreeting = function() { + var random_index = Math.round(Math.random()); // 0 or 1 + return greetings[random_index]; + }; + + // whatever we return from the function is what will be injected afterwards + // when some other code requests a "GreetingService" via dependency injection + return service; + }); + +Now that a service called `GreetingService` exists, it can be injected like any other. You can test that it works by updating `MyCtrl`: + + :::javascript + myApp.controller("MyCtrl", function($scope, GreetingService) { // add GreetingService to the list of parameters + $scope.products = ...; + + $scope.updateProducts = ...; + + // add a new function to test that service injection worked: + $scope.testService = function() { + alert(GreetingService.randomGreeting()); + }; + }); + +Add a new button to the HTML: + + :::html + ... + + + + +When you click the new button, `testService` will be invoked in the scope and `GreetingService` will be called to provide a random greeting. + +## Applications +Angular.js was designed so that it could be added to an existing page and control only part of the DOM without interferring with the rest of the page. It is actually possible to have several Angular applications on the same page, completely independent from one another. However, because mobile devices have to work with limited screen real estate compared to traditional desktop computers, it is common for mobile apps to be composed of a single Angular app. The ability to have more than one is still there, if you want to use it. The `ngApp` directive controls which part of the DOM belongs to which application and in single-app pages, it is common to have it in the `html` tag. + +## Views and Routing +Any non-trivial application will consist of more than one view; in order to work with multiple views, Angular.js provides a `RouteProvider` that maps urls to views and controllers. + +Mapping urls to views and controllers is straightforward: + + :::javascript + // create application and declare a dependency on ngRoute (required) + var productApp = angular.module("ProductApp", ['ngRoute']); + + // application configuration function, request routeProvider via dependency injection + productApp.config(function($routeProvider) { + + // when the url equals "/app"... + $routeProvider.when("/app", { + + // ... load index.html ... + templateUrl: "/public/partials/index.html", + + // ... and use HomeCtrl as the controller + controller: "HomeCtrl" + }) + + // if the url starts with /edit/, and contains a second path element, extract an "id" parameter from it and make + // it available to our code later... + .when("/edit/:id", { + + // ... load edit.html ... + templateUrl: "/public/partials/edit.html", + + // and use EditCtrl as the controller + controller: "EditCtrl", + }) + // if the path is /edit but it does not contain any more information, treat it as creating a new product. The same view + // and controller will take care of that + .when("/edit", { + templateUrl: "/public/partials/edit.html", + controller: "EditCtrl", + }) + .otherwise({ + redirectTo: "/app", + }); + }); + +When the application starts, the router will check the current url and process the rules. If none of them match, it will fallback to the "otherwise" section, if present. Once the router has determined which view to, it will process the template and try to find a tag with an `ngView` directive: + + :::html + +
                                                                              +
                                                                              + + + +## Integrating Rhom into Angular.js +While Angular.js provides a lot of directives and services, out of the box, with just the information above you can already start to build data-driven applications and you will soon want to integrate Rhom for easy database access. In the rest of this guide, we will show how to build a CRUD application for a sample model called `Product` with `name` and `brand` properties. The application will consist of two screens: + +* Home screen + - list of all known products + - button to create new product + - buttons to edit and delete existing products + +* Edit screen + - product edit form + - save button + +> Note: The code for this application is available [here](https://github.com/javiermolina1234/rhomobile-angular-sample). + +The first thing we need in our code in order to use Rhom is a [Rhom model](local_database): + + :::javascript + var rhoProductModel = Rho.ORM.addModel(function(model) { + model.modelName("Product"); + // Uncomment for RhoConnect integration + // model.enable("sync"); + model.property("name", "string"); + model.property("brand", "string"); + model.set("partition", "app"); + }); + +To use Angular.js, we need to instantiate our application. Because we will use Angular.js routes to handle navigation between views, our application will declare a dependency on `ngRoutes`. Also included in the excerpt below is the controller for the Home view, `HomeCtrl`: + + :::javascript + var productApp = angular.module("ProductApp", ['ngRoute']); + + productApp.controller("HomeCtrl", + // request the ProductHelper via dependency injection + function HomeCtrl($scope, $location, ProductHelper) { + + $scope.products = ProductHelper.products; + + $scope.create = function() { + // navigate to edit page without passing an id + // the Edit controller will interpret that as a request to create a new product + $location.url("/edit"); + } + + $scope.create_with_data = function() { + ProductHelper.create({name: "New product"}); + } + + $scope.del = function(product_id) { + ProductHelper.del(product_id); + } + + $scope.sync = function() { + // RhoConnect integration + Rho.RhoConnectClient.doSync(); + } + } + ); + +The HTML code for the Home view is as follows: + + :::html + New product + New product with data + + + + + + + + + + + + + + + + +
                                                                              NameBrand
                                                                              {{ product.name }}{{ product.brand }} + Edit + Delete +
                                                                              + +`HomeCtrl` is very easy to follow: if has a few methods to deal with objects and the only thing it does is delegate those calls to `ProductHelper`, which is where we will place our database integration code. The HTML code is also quite simple: the are some buttons with `ngClick` directives binding them to the appropriate functions in the scope, as well as a table with an `ngRepeat` that loops over a property called `products` in the scope and contains two more buttons to edit and delete products by their primary key. + +`ProductHelper` is a service that follows the [Facade pattern](http://en.wikipedia.org/wiki/Facade_pattern) and wraps Rhom with an interface specific to our use case: + +* a `products` array, that contains all the products we are interested in showing (in our case, every product stored in the database). We will add this `products` property to our scope so that the `ngRepeat` in the table can find it +* CRUD methods +* a `find_by_id` method to load a particular product from the database +* a helper method `to_hash` to extract properties from Rhom model objects and put them into simple JavaScript hashes that Angular knows how to handle + +The code for `ProductHelper` is below: + + :::javascript + productApp.factory("ProductHelper", function() { + var ormModel = Rho.ORM.getModel("Product"); + return { + products: [], + load_products: function() { + // we do not want to reassign the array, because we are binding it in the + // Home controller's scope and that would break the binding. Instead, we + // just empty it before loading products from the database + this.products.splice(0,this.products.length); + + var rhoProducts = ormModel.find("all"); + for (var i = 0; i < rhoProducts.length; i++) { + var rhoProduct = rhoProducts[i]; + this.products.push(this.to_hash(rhoProduct)); + } + }, + create: function(params) { + var rhoProduct = ormModel.create(params); + var hash = this.to_hash(rhoProduct); + this.products.push(hash); + return hash; + }, + del: function(product_id) { + var rhoProduct = this.find_by_id(product_id); + if (rhoProduct) { + // remove the product from the database + rhoProduct.destroy(); + } + + // remove the product from the products array + // this is faster than discarding and re-reading the whole collection + for (var i=0; i +

                                                                              Edit New product

                                                                              + +
                                                                              +
                                                                              + + + + + Save +
                                                                              +
                                                                              + +* `ngShow` displays its contents only when its expression resolves to a truthy value +* `ngHide` does the opposite, it will show the element only if its expression is falsy +* `ngModel` tells `` tags which value they must bind to in the scope + +`EditCtrl` is the controller for that view: + + :::javascript + productApp.controller("EditCtrl", + function EditCtrl($scope,$routeParams,$location,ProductHelper) { + // We will see how to bind route parameters in a moment, for now just assume that + // $routeParams.id will contain the primary key of the product to edit, or be empty + // if we are creating a new product + + var product_id = $routeParams.id; + + if (product_id) { + var rhoProduct = ProductHelper.find_by_id(product_id); + // this "product" member of the scope is what the tags + // in the view are binding to + $scope.product = ProductHelper.to_hash(rhoProduct); + $scope.rhoProduct = rhoProduct; + } else { + $scope.product = {}; + } + + $scope.save = function() { + + if (this.rhoProduct) { + // "this.product" is $scope.product and will have been updated with + // whatever the user has entered in the tags + ProductHelper.update(this.rhoProduct,this.product); + } else { + ProductHelper.create(this.product); + } + // redirect to the home screen + $location.url("/app"); + } + } + ); + +There is nothing particularly surprising in `EditCtrl`, just pure controller logic: move values to and from the database as required. + +All that is missing now is: + +* loading the products from the database on application start +* wiring all the views together to respond to changes in the url + +In order to schedule a task to be performed when the application starts, call `run` on your application passing it a function: + + :::javascript + productApp.run(function(ProductHelper) { + ProductHelper.load_products(); + }); + +To set up routing, inject $routeProvider in your application`s `config` function: + + :::javascript + productApp.config(function($routeProvider) { + $routeProvider.when("/app", { + templateUrl: "/public/partials/index.html", + controller: "HomeCtrl", + }) + .when("/edit/:id", { + templateUrl: "/public/partials/edit.html", + controller: "EditCtrl", + }) + .when("/edit", { + templateUrl: "/public/partials/edit.html", + controller: "EditCtrl", + }) + .otherwise({ + redirectTo: "/app", + }); + }); + +Finally, to prevent jQuery Mobile from conflicting with Angular's routing and view handling, the following code can be used: + + :::javascript + $(document).bind("mobileinit", function () { + $.mobile.ajaxEnabled = false; + $.mobile.linkBindingEnabled = false; + $.mobile.hashListeningEnabled = false; + $.mobile.pushStateEnabled = false; + }); + +Angular.js takes care of two-way data binding throughout the whole application, freeing you from having to write tedious plumbing code for copying values to and from HTML elements. + +## Conclusions and highlights +* During this exercise, not a single line of code was written to touch the DOM; this approach is core to the Angular.js philosophy that controllers should never perform DOM operations. +* CRUD operations are performed through a central `ProductHelper` service that handles all database calls via Rhom and maintains a model of products from which the application feeds its views + +## Related reading +There is much more to Angular.js than what we have covered in this guide. Refer to the [Angular.js tutorial](http://docs.angularjs.org/tutorial) and the [developer guide](http://docs.angularjs.org/guide/) for more in-depth treatment + +* [ORM API documentation](../api/Orm) +* [ORMModel API documentation](../api/OrmModel) \ No newline at end of file diff --git a/docs/en/5.5/guide/rhom_backbone.md b/docs/en/5.5/guide/rhom_backbone.md new file mode 100644 index 00000000..c23e665c --- /dev/null +++ b/docs/en/5.5/guide/rhom_backbone.md @@ -0,0 +1,425 @@ +# Using Rhom in JavaScript with Backbone.js + +## Overview + +In past versions of RhoMobile, applications were developed with a combination of HTML and JavaScript for the view plus Ruby for the controllers. That approach is still supported but in RhoMobile 5.0 is that all the features of the platform can be accessed using JavaScript. Anything you can do in Ruby, can be done in JavaScript and it is now possible to build applications without writing any Ruby code at all. In this guide we will see an example of building an application in 100% JavaScript + +## Why Backbone.js + +If you are familiar with jQuery, you already know that while it provides a very helpful set of functions to manipulate the DOM, following large chains of callbacks and DOM operations becomes a maintenance problem very quickly, not to mention that you still have to write a lot of code to keep your models and views in sync with each other. + +[Backbone.js](http://backbonejs.org) is a JavaScript library that helps you structure your applications in a more maintainable way, including a set of high-level abstractions for models, views and event handling. These primitives are designed to be the basic building blocks of your application and to be extended with your own functionality. + + +## Getting started with Backbone.js + +**NOTE: If you are already familiar with Backbone.js, skip to [Integrating Backbone.js and Rhom](#integrating-backbonejs-and-rhom)** + +### First steps - creating a basic view + +Backbone.js depends on two other libraries to work: [Underscore.js](http://underscorejs.org) and either [jQuery](http://jquery.com/) or [Zepto](http://zeptojs.com/). We will use jQuery in this guide. + +The most basic thing you can do with Backbone.js is to create a simple view with static content. + + :::html + + + + hello-backbonejs + + +
                                                                              + + + + + + + + + + + +See the example running + +That is all there is to creating a basic view - extend Backbone.View and provide a render method. Obviously, you will soon want to add interactive elements to your views and respond to events. This is easily achieved by adding an `events` property to your view as a hash of the format 'event selector' : 'method'. + + :::javascript + var HomeView = Backbone.View.extend({ + el: "content", + events: { + // this hash tells which events we are interested in and where they should be delivered + // the format is + // 'event selector' : method + 'click button.add_greeting' : 'add_greeting', + 'click button.remove_greetings' : 'remove_greetings' + }, + render: function() { + var template = ""+ + "

                                                                              Hello, world!

                                                                              "+ + ""+ // add some buttons + ""+ + "
                                                                              "; // empty placeholder + + $(this.el).html(template); // write the template to our assigned element + }, + add_greeting: function() { + $(this.el).find(".greetings").append("

                                                                              Hello

                                                                              "); + }, + remove_greetings: function() { + $(this.el).find(".greetings").empty(); + } + }); + +See the example running + +Once we know how to respond to interactive events, our next step is to edit some data; Backbone.js expects that you will define a Model to represent each entity in our application, and by default, it will provide functionality to create, read, update and delete objects by talking to a RESTful backend. It is also common to group models of the same type together, to show them in lists for example; Backbone.js provides a `Collection` class for that purpose. + + + :::javascript + + // define our model class + var Greeting = Backbone.Model.extend({ + defaults: { // optional: define default values + greeting: "Hello", + greete: "world", + exclamation: false + }, + toString: function() { + var result = this.escape("greeting")+", "+this.escape("name"); + if (this.get("exclamation")) { + result+='!'; + } + return result; + } + + }); + + // define a collection class + var GreetingList = Backbone.Collection.extend({ + model: Greeting // this collection holds Greeting objects + }); + +### Moving between views - Routing + +We will create a new view to edit greetings but as soon as we have more than one view, we need a way to switch between them. In multi-page applications, that poses no problem, we place links that change the URL and the browser loads the new page when the user clicks on them. In a JavaScript application, because we are trying to avoid page reloads, switching between views requires a bit of thought from our side. Fortunately, Backbone.js provides a `Router` component that does most of the work for us. It listens to changes in the current URL's `fragment` (the part after the hash sign) and fires events we can listen to: + + :::javascript + var Router = Backbone.Router.extend({ + routes: { + // fragment : 'method' + '' : 'home', + 'new' : 'editGreeting', + // routes can also automatically interpret parts of the URL as parameters + 'edit/:id' : 'editGreeting' + }, + }); + + var router = new Router(); + var homeView = new HomeView(); + var editGreetingView = new EditGreetingView(); + + router.on("route:home", function() { + // render home view + }); + + // because there are two different routes that point to this method, one with a parameter and the other without, + // id may contain a value or not, depending on what route was triggered. We can use that to detect if we are + // creating a new greeting or editing an existing one + + router.on("editGreeting", function(id) { + // edit the greeting with a particular id + }); + +With routing in place, it is time to create EditGreetingView so that the user can add greetings to our list, and to update HomeView to display those greetings and allow them to be edited: + + :::javascript + var HomeView = Backbone.View.extend({ + el: "#content", + events: { + // 'event selector' : 'method' + 'click button.remove_greetings' : 'remove_greetings' + }, + render: function() { + var template = ""+ + "

                                                                              Hello, world!

                                                                              "+ + "Add greeting"+ // add some buttons + ""+ + "
                                                                              "+ + "
                                                                                "; + + for (var i=0; i"+greeting.toString()+""; + } + + template+=""+ + "
                                                                              "+ + "
                                                                              "; + + $(this.el).html(template); // write the template to our assigned element + }, + remove_greetings: function() { + greetingList.reset(); // empty the collection + this.render(); + }, + edit_greeting: function(ev) { + var link = $(ev.currentTarget); + console.log(link); + } + }); + + var EditGreetingView = Backbone.View.extend({ + el: "#content", + events: { + // 'event selector' : 'method' + 'click button.save' : 'save', + 'click button.cancel' : 'cancel' + }, + render: function(greeting) { + var is_new = !greeting; + + if (is_new) { + greeting = new Greeting(); + } + + this.greeting = greeting; + + var template = ""+ + "
                                                                              "+ + " "+ + " "+ + " "+ + " "+ + " "+ + " "+ + " "+ + "
                                                                              "; + + this.$el.html(template); + }, + save: function(event) { + console.log("save"); + console.log(event); + + var is_new = this.$el.find('input[name=new]').val(); // are we creating a new greeting or editing an existing one? + + var new_values = {}; + new_values.greeting = this.$el.find('input[name=greeting]').val(); + new_values.name = this.$el.find('input[name=name]').val(); + new_values.exclamation = this.$el.find('input[name=exclamation]').is(':checked'); + + this.greeting.set(new_values); + + if (is_new) { + greetingList.add(this.greeting); + } + // go back home + router.navigate("", {trigger: true}); + }, + cancel: function() { + // go back home + router.navigate("", {trigger: true}); + }, + delete: function() { + if (this.greeting) { + greetingList.remove(this.greeting); + } + return false; + } + }); + +See the example running + +### Templates + +The approach we have taken so far is promising: instead of having our data scattered across a multitude of different DOM elements, it is neatly stored in models that can be easily manipulated. However, the `render` methods in our views are using string operations to build their templates; this style becomes unmanageable very quickly as soon as your views contain anything beyond a handful of elements. + +Backbone.js does not dictate the use of any templating library in particular but because it counts Underscore.js as one of its dependencies, it is common to use the `_.template` function. Underscore templates use a syntax similar to ERB: angle brackets and percent signs: + + :::erb + <% JavaScript code goes here %> + +You an also print values with <%= value %> + :::erb + Today's date in milliseconds: <%= Date.now() %> + +To be safe against XSS, you will frequently use the HTML escaping syntax: + + :::erb + <%- value %> + +Here is the way our HomeView and EditGreetingView templates would look like if we converted them to Underscore.js: + + :::html + ... + + ... + + + + + + +They look much more maintainable now that they are outside JavaScript code and rendering them consists of two easy steps: first, you compile the template into a function; second, that function is called with the parameters its template uses. Let's see how HomeView does it: + + :::javascript + + var HomeView = Backbone.View.extend({ + el: "#content", + events: { + 'click button.remove_greetings' : 'remove_greetings' + }, + initialize: function() { + // compile template into a function and store it for future use + this.template = _.template($("#HomeView-template").html()); + }, + render: function() { + // call the template to render the current list of models + var template_contents = this.template({ greetings : greetingList.models }); + $(this.el).html(template_contents); // write the template to our assigned element + }, + remove_greetings: function() { + greetingList.reset(); // empty the collection + this.render(); + }, + edit_greeting: function(ev) { + var link = $(ev.currentTarget); + console.log(link); + } + }); + +That is the whole code listing for HomeView, now that its template lives independently. + +See the completed example running + +## Backbone.js in RhoMobile + +You can start using Backbone.js in a RhoMobile application right away if you do not need persistent data or if you interact with a RESTful backend, for which Backbone.js provides support out of the box. If, however, you want to store data locally and potentially synchronize it with a RhoConnect server, you must use Rhom for your data storage. + +**NOTE: See the guide called [Using the local database](local_database) for a full description of Rhom** + +A JavaScript application wishing to use Rhom for data storage and, potentially, two-way synchronization via a RhoConnect server, must first define its models: + + :::javascript + var rhoProductModel = Rho.ORM.addModel(function(model) { + model.modelName("Product"); + // Uncomment for RhoConnect integration + // model.enable("sync"); + model.property("name", "string"); + model.property("brand", "string"); + model.property("price", "float"); + model.set("partition", "app"); + }); + +With a reference to the [ORMModel](../api/OrmModel), either retained after creation or the model, or obtained with a call to `Rho.ORM.getModel('Product')`, you can now create instances of your models, get and set their properties or delete them from the database. + + :::javascript + // create a product and save it to the database + var product = rhoProductModel.create({ + name: "ET1", + brand: "Zebra", + price: 199.99 + }); + + + var name = product.get("name"); // "ET1" + + product.destroy(); // remove product from the database + +We have seen that Backbone.js provides a Model class and here we have RhoMobile's models that are similar but cannot be used directly by Backbone.js. Fortunately, there is an integration library available that will help you develop faster and with less effort. + +### Enter RhoTendon + +A tendon is "tissue that connects bone to muscle" and RhoTendon is a small JavaScript glue library that binds Backbone.js to the power of Rhom, allowing you to develop pure-JavaScript applications in a very rapid fashion. [RhoTendon is available for download here](https://github.com/javiermolina1234/rhotendon). Once you define a Rhom model as seen above, you just need to derive your Backbone.js models from `RhoTendon.Model`, which extends Backbone.Model and links with Rhom under the hood: + + :::javascript + + + /// define model + var rhoProductModel = Rho.ORM.addModel(function(model) { + model.modelName("Product"); + // Uncomment for RhoConnect integration + // model.enable("sync"); + model.property("name", "string"); + model.property("brand", "string"); + model.property("price", "float"); + model.set("partition", "app"); + }); + + var Product = RhoTendon.Model.extend({ + ormModel: "Product", // identify the Rhom model this class represents + mirrorAttributes: ["name", "brand"] // enumerate which attributes our Backbone model will care about + }); + + var ProductList = RhoTendon.ModelCollection.extend({ + model: Product, // this collection handles Product models + }); + +That is all you need to do to integrate Backbone.js models and Rhom. Internally, RhoTendon models override the Backbone.js `sync` method so that whatever operations you perform on your instances of the Product model are be reflected in the database: + + :::javascript + + // all the following is standard Backbone.js code, nothing special + var product = new Product(); + + product.set({ + name: "ET1", + brand: "Zebra", + price: 199.99 + }); + + product.save(); + // at this point, your object has been persisted in the Rhom database + + product.destroy(); + // and now it has been deleted + + +There is a [sample application available for download](https://github.com/javiermolina1234/rhomobile-backbonejs-sample) built with RhoMobile, jQuery Mobile, Backbone.js and RhoTendon. It is intended to serve as a short and readable example of bringing all these technologies together and to be a starting point for your own RhoMobile applications. + + +## Related reading +* [Backbone.js](http://backbonejs.org) +* [Underscore.js](http://underscorejs.org) +* [Using the local database](../api/local_database) +* [ORM API documentation](../api/Orm) +* [ORMModel API documentation](../api/OrmModel) \ No newline at end of file diff --git a/docs/en/5.5/guide/rhom_js.md b/docs/en/5.5/guide/rhom_js.md new file mode 100644 index 00000000..985f61b8 --- /dev/null +++ b/docs/en/5.5/guide/rhom_js.md @@ -0,0 +1,259 @@ +# Using Rhom in JavaScript + +The RhoMobile Suite provides several methods of handling device data. For RhoMobile Suite 5.3 and higher is the [ORM common API](../api/NewORM), which supports JavaScript and Ruby. RMS 5.2 and lower support the original [Rhom API](../api/rhom-api) (for Ruby) and the [ORM API](../api/Orm) documented here, which adds JavaScript support to Rhom via the [OPAL library](http://opalrb.org). + +## Creating a JavaScript Model + +The first step in using Rhom is to create a model class with the required attributes. Models are created in JavaScript using the [ORM.addModel](../api/Orm#maddModel) method, which defines a class reference for the model and makes it available to the application. + +When your application pages load, execute the `Rho.ORM.addModel` function for every model defined in the application. + + :::javascript + // Models MUST be defined when your HTML pages load + + // Either set a global reference... + var userModel = Rho.ORM.addModel(function(model) { + model.modelName('User'); + model.property('name','string'); + model.property('email','string'); + // optionally enable sync for rhoconnect applications: + // model.enable('sync'); + // optionally define model as fixedSchema (default is propertyBag): + // model.enable('fixedSchema'); + }); + + // ...or define the model without a global reference + Rho.ORM.addModel(function(model) { + model.modelName('Product'); + model.property('name','string'); + model.property('qty','string'); + }); + + +Once created, models can be retrieved using the `ORM.getModel` method: + + :::javascript + var productModel = Rho.ORM.getModel('Product'); + +**NOTE: It is advisable to use either the Ruby or JavaScript methods for handling model definition and access. DO NOT do this from _both_ languages**. + +## Adding new items + +The fastest way to insert a single item into the database is to use the `create` method to create a new model object and save it to the database: + + + :::javascript + var user = userModel.create({ + name: 'Alice', + email: 'alice@example.com'}); + +You also can create a new model object without saving it automatically, and then explicitly use the `save` method. This is useful for updating some of the object attributes before saving: + + :::javascript + var user = userModel.make({name: 'Alice'}); + // update the object + user.email = 'alice@example.com'; + user.save(); + +## Retrieving objects + +Use the `find` method to retrieve all objects for a model or only those matching given conditions: + +### Getting all objects for a model + + :::javascript + var users = userModel.find('all'); + +### Finding objects matching conditions + + :::javascript + var users = userModel.find( + 'all', + { + conditions: {name: 'Alice'} + } + ); + +### Ordering the objects + +Use the `order` and `orderdir` parameters to retrieve objects sorted by one or more attributes: + + :::javascript + // order by one attribute + var users = userModel.find( + 'all', + { + order: 'name', + orderdir: 'DESC', + conditions: {...} // JavaScript API requires conditions + } + ); + + // order by multiple attributes + var users = userModel.find( + 'all', + { + order: ['name', 'email'], + orderdir: ['ASC', 'DESC'], + conditions: {...} // JavaScript API requires conditions + } + ); + +Sorting also can be done with a user-defined function: + + :::javascript + // order by one attribute + var users = userModel.find( + 'all', + { + orderFunction: function(a, b) { return a <= b } + } + ); + + // order by multiple attributes + var users = userModel.find( + 'all', + { + orderFunction: function(a, b) { + return a.name <= b.name && a.email <= b.email + } + } + ); + +**NOTE: Use `order` instead of `orderFunction` whenever possible; the `order` database command will sort objects faster than the JavaScript `orderFunction` code.** + +### Retrieving specific attributes + +If only some attributes in an object are needed for a particular action, increase app performance by using the `select` parameter to choose only the required attributes: + +JavaScript syntax: + :::javascript + var users = userModel.find( + 'all', + { + select: ['name'], + conditions: {...} // JavaScript API requires conditions + } + ); + +### Retrieving only the first object matching conditions + +Use the `first` method (instead of `all`) when calling `find` to get only the first object matching the given condition(s): + + :::javascript + var user = userModel.find( + 'first', + { + conditions: {name: 'Alice'} + } + ); + +## Counting objects + +Use the `count` parameter with `find` method to get a count of objects matching given condition(s): + +JavaScript syntax: + :::javascript + var count = userModel.find( + 'count', + { + conditions: {name: 'Alice'} + } + ); + +## Updating + +The fastest way to add or update object attributes is to save to the database using the `update_attributes` method: + +JavaScript syntax: + :::javascript + var user = userModel.find('first', {conditions: {name: 'Alice'}); + user.updateAttributes({ + name: 'Bob', + email: 'bob@example.com'}); + +## Deleting + +### Delete one object + +To delete one model object, use the `destroy` method on the object to be deleted: + +JavaScript syntax: + :::javascript + var user = userModel.find('first'); + user.destroy(); + +### Delete multiple objects + +Use the `deleteAll` method to delete all objects for a model or only those matching given condition(s): + +JavaScript syntax: + :::javascript + // delete all objects + userModel.deleteAll(); + + // delete only objects matching :conditions + userModel.deleteAll({conditions: {name: 'Alice'}}) + +## Transactions + +For database operations that must either succeed or fail as a group without leaving any partially completed operations, use transactions to group them together. Combine any set of object/model operations, such as 'insert/update/delete' under a transaction: + + :::javascript + // open 'app' partition + var db = new Rho.Database(Rho.Application.databaseFilePath('app'),'app'); + db.startTransaction(); + try + { + // do multiple operations + db.executeSql("update User set name=?, email=? where object=?",["Alice","alice@example.com","12345"]); + db.executeSql("update User set name=?, email=? where object=?",["Bob","bob@example.com","67890"]); + + // no errors, so commit all the changes + db.commitTransaction(); + } + catch + { + // on error rollback all changes + db.rollbackTransaction(); + } + finally // always close every database connection you open + { + db.close(); + } + +## Executing SQL + +Use the `Database.executeSql` method to execute SQL statements directly on the database: + +JavaScript syntax: + :::javascript + try { + + + var db = new Rho.Database(Rho.Application.databaseFilePath('app'),'app'); + var result = db.executeSql('SELECT * FROM User'); // result is an array of hashes, where each hash is a record + } finally { + db.close(); + } + +Use the `Database.executeBatchSql` to execute a series of SQL statements in a single method call: + + :::javascript + db.executeBatchSql("UPDATE User set valid=0; Update Account set active=0"); + + +## Resetting database + +To recover the database from a bad or corrupt state or if the RhoConnect server returns errors, use the following method to delete all objects for given model(s): + +JavaScript syntax: + :::javascript + Rho.ORM.databaseFullResetEx({'models': ['User'], 'reset_client_info': true, 'reset_local_models': true}); + + +## Related reading + +* [Database API reference](../api/Database) +* [ORM API reference](../api/Orm) +* [ORMModel API reference](../api/OrmModel) diff --git a/docs/en/5.5/guide/rhom_ruby.md b/docs/en/5.5/guide/rhom_ruby.md new file mode 100644 index 00000000..39143cd7 --- /dev/null +++ b/docs/en/5.5/guide/rhom_ruby.md @@ -0,0 +1,820 @@ +# Using Rhom in Ruby + +The RhoMobile Suite provides several methods of handling device data. For RhoMobile Suite 5.3 and higher is the [ORM common API](../api/NewORM), which supports JavaScript and Ruby. RMS 5.2 and lower support the original [Rhom API](../api/rhom-api) (for Ruby) documented here, and the [ORM API](../api/Orm), which adds JavaScript support to Rhom via the [OPAL library](http://opalrb.org). + +## Creating a Ruby Data Model + +Ruby models can be generated using RhoStudio or from the command line. The approaches are functionally equivalent; the generator outputs the model class itself along with a set of sample views that can be customized as needed. + +### From RhoStudio + +1. In Project Explorer, **right-click on the application project and select New -> RhoMobile model**. + + + +2. **Enter the model name in the Model Information window**. + +**NOTE: Models MUST NOT have the same name as any of Ruby's built-in classes. These include: `Config, Settings, helpers, test, Client, Sync`. Best practices call for descriptive model names such as `Product` and `Service`, and to avoid generic names such as `time` and `print`. Descriptive naming will be helpful when the application grows or changes in the future**. + +3. **Enter the model attributes separated by commas only (no spaces)**. + + + +4. **Click Finish**. Model generator results will appear in the output console window similar to the image below. + + + +### From the command line + +The 'Rhodes' tool can be invoked manually to allow use of the command line or an IDE other than RhoStudio. The two steps below are functionally identical to the four above. + +1. **Open a command prompt** and switch to the root directory of the application (the directory that contains `app` as a child). + +2. **Execute the commmand** below: + + :::term + $ rhodes model Product name,brand,price,quantity,sku + + +### What's inside a generated model + +Output from the model generated in the 'Product' example will contain the following files, which can be updated to suit the application: + +* **app/Product/index.erb** - the html view template to display the list of objects +* **app/Product/edit.erb** - the html view template to edit an object +* **app/Product/new.erb** - the html view template to supply values to create a new object +* **app/Product/show.erb** - the html view template to displays the selected object +* **app/Product/product_controller.rb** - contains the the business logic for the model, the basic CRUD actions of create, read, update and delete plus indexing. +* **app/Product/product.rb** - contains the Product model definition +* **app/test/product_spec.rb** - placeholder for Product test specs + +**NOTE: Depending on the data model being used, model attributes might not be visible in the `product.rb` file. See [Using Models (below)](#property_bag) for more information.** + + +## Using Models + +Rhodes offers a choice of PropertyBag and FixedSchema model storage schemes. PropertyBag, the default scheme, stores data in a table that's built dynamically as needed, so no attributes are present in a newly generated model. FixedSchema stores data for each model in a database table, with columns for each attribute defined in advance. Please refer to the [Data Handling](local_database) guide for more information. + +### Property Bag +In the property bag model, data is stored as key-value pairs in a single table using the object-attribute-value or [entity-attribute-value model](http://en.wikipedia.org/wiki/Entity-attribute-value_model). This model is sometimes referred to as 'open schema' because the fields (or keys) do not have to be defined in advance; the API stores and syncs all key-value pairs that are entered. + +#### Advantages +* Simple, doesn’t require advance attribute design +* Attributes can be added or removed without modifying the database schema +* Requires no data migration following a schema change + +#### Disadvantages +* Since all attributes are indexed, the database can be much larger than with fixed schema +* Sync process can be slower because database insertions are performed at the attribute level + +In a Property Bag model, Rhom groups objects by their source ID and object ID. The following example illustrates this idea: + +
                                                                              +Source ID: 1, Model Name: Account
                                                                              ++-----------+----------+--------------+----------------------+
                                                                              +| source_id | attrib   | object       | value                |
                                                                              ++-----------+----------+--------------+------- --------------+
                                                                              +|         1 | name     | 48f39f63741b | A.G. Parr PLC 37862  |
                                                                              +|         1 | industry | 48f39f63741b | Entertainment        |
                                                                              +|         1 | name     | 48f39f230529 | Jones Group          |
                                                                              +|         1 | industry | 48f39f230529 | Sales                |
                                                                              ++-----------+----------+--------------+----------------------+
                                                                              +
                                                                              + +Here, Rhom will expose a class `Account` with the attributes `name` and `industry`: + + :::ruby + account = Account.find('48f39f63741b') + account.name + #=> "A.G. Parr PLC 37862" + + account.industry + #=> "Entertainment" + +#### Using Property Bag Models +1. **Generate a new model** with some attributes: + + :::term + $ rhodes model product name,brand,price,quantity,sku + +This will generate a file called `product.rb` that looks like this: + + :::ruby + class Product + include Rhom::PropertyBag + + # Uncomment the following line to enable sync with Product. + # enable :sync + + #add model specific code here + end + +2. **Enable the requiured features in the model** from the following feature list: + + :::ruby + class SomeModel + include Rhom::PropertyBag + + # rhoconnect settings + # Enable sync for this model. + # Default is disabled. + enable :sync + + # Set the type of sync this model + # will use (default :incremental). + # Set to :bulk_only to disable incremental + # sync and only use bulk sync. + set :sync_type, :bulk_only + + # Set the sync priority for this model. + # 1000 is default, set to lower number + # for a higher priority. + set :sync_priority, 1 + + # Instruct Rhom to send all attributes + # to RhoConnect when an object is updated. + # Default is disabled, only changed attributes + # are sent. + enable :full_update + + # RhoConnect provides a simple way to keep data out of redis. + # If you have sensitive data that you do not want saved in redis, + # add the pass_through option in settings/settings.yml for each source. + # Add pass_through to client model definition + enable :pass_through + + # model settings + + # Define how data is partitioned for this model. + # For synced models default is :user. + # For non-synced models default is :local + # If you have an :app partition + # for your RhoConnect source adapter and use bulk sync, + # set this to :app also. + set :partition, :app + + # Define blob attributes for the model. + # :blob Declare property as a blob type + # + # :overwrite (optional) Overwrite client copy + # of blob with new copy from server. + # This is useful when RhoConnect modifies + # images sent from Rhodes, for example + # zooming or cropping. + property :image_url, :blob, :overwrite + + # You can define your own properties also + property :mycustomproperty, 'hello' + end + + +### Fixed Schema +In a fixed schema model, each model has a separate database table and attributes form the columns of that table. In this sense, the fixed schema model is similar to a traditional relational database. + +#### Advantages +* Smaller database size; indexes can be assigned to specific attributes +* Sync process may be faster because whole objects are inserted at once + +#### Disadvantages +* Schema changes require data migration +* Database performance may be slow without careful index specificity + +#### Using Fixed Schema Models +Using a fixed schema model involves more steps than the Property Bag model. + +1. **Generate the model using the 'rhodes' command**: + + :::term + $ rhodes model product name,brand,price,quantity,sku + +2. **Change the include statement in `product.rb` to**: + + :::ruby + include Rhom::FixedSchema + + +3. **Add the attributes**: + + :::ruby + class Product + include Rhom::FixedSchema + + # Uncomment the following line to enable sync with Product. + # enable :sync + + property :name, :string + property :brand, :string + property :price, :string + property :quantity, :string + property :sku, :string + + property :int_prop, :integer + property :float_prop, :float + property :date_prop, :date #translate to integer type + property :time_prop, :time #translate to integer type + + end + +A table with a fixed schema model will be generated automatically when the application launches. + +Below is a full list of options available to fixed schema models: + + :::ruby + class SomeModel + include Rhom::FixedSchema + + # rhoconnect settings + # Enable sync for this model. + # Default is disabled. + enable :sync + + # Set the type of sync this model + # will use (default :incremental). + # Set to :bulk_only to disable incremental + # sync and only use bulk sync. + set :sync_type, :bulk_only + + # Set the sync priority for this model. + # 1000 is default, set to lower number + # for a higher priority. + set :sync_priority, 1 + + # Instruct Rhom to send all attributes + # to RhoConnect when an object is updated. + # Default is disabled, only changed attributes + # are sent. + enable :full_update + + # RhoConnect provides a simple way to keep data out of redis. + # If you have sensitive data that you do not want saved in redis, + # add the pass_through option in settings/settings.yml for each source. + # Add pass_through to client model definition + enable :pass_through + + # model settings + + # Define how data is partitioned for this model. + # Default is :user. If you have an :app partition + # for your RhoConnect source adapter and use bulk sync, + # set this to :app also. + set :partition, :app + + # Set the current version of the fixed schema. + # Your application may use it for data migrations. + set :schema_version, '1.0' + + # Define fixed schema attributes. + # :string and :blob types are supported. + property :name, :string + property :tag, :string + property :phone, :string + property :image_url, :blob + + # Define a named index on a set of attributes. + # For example, this will create index for name and tag columns. + index :by_name_tag, [:name, :tag] + + # Define a unique named index on a set of attributes. + # For example, this will create unique index for the phone column. + unique_index :by_phone, [:phone] + + # Define blob attributes for the model. + # :blob Declare property as a blob type + # + # :overwrite (optional) Overwrite client copy + # of blob with new copy from server. + # This is useful when RhoConnect modifies + # images sent from Rhodes, for example + # zooming or cropping. + property :image_url, :blob, :overwrite + + # You can define your own properties also + property :mycustomproperty, 'hello' + end + +## Data Migrations +### Fixed Schema Data Migrations +Changes to the data model in a fixed-schema database requires that data be migrated from the old schema to the new one (a requirement not shared by the Property Bag model because of its 'open schema' construction). + +For this reason, Rhom provides an application hook for manually migrating data in the event of a model change. The hook also can be used to run business logic related to updates to a database. For example, it is sometimes desireable to display a custom alert notifying the user to wait a few moments while a data migration is in progress. + +To use this hook: + +1. **Track the `:schema_version`** in the model: + + :::ruby + class Product + include Rhom::FixedSchema + + set :schema_version, '1.1' + end + +2. **In the `application.rb` class, implement the hook `on_migrate_source(old_version, new_src)`** as follows: + + + :::ruby + class AppApplication < Rho::RhoApplication + + # old_version String containing old version value (i.e. '1.0') + # new_src Hash with source information: + # 'schema_version', 'name', 'schema' + # new_src['schema']['sql'] contains new schema sql + def on_migrate_source(old_version, new_src) + # ... do something like alert user ... + + db = Rho::RHO.get_src_db(new_src['name']) + db.execute_sql("ALTER TABLE #{new_src['name']} ADD COLUMN mytest VARCHAR DEFAULT null") + + true # does not create table + end + end + +The code above will call the hook on application start whenever `:schema_version` has changed. + +**NOTE: To modify the schema without recreating the table, use the ADD COLUMN command. Limitations of SQLlite prevent the removal of columns or changes to the type**. + +Return `false` to run the custom sql specified by the new_src['schema']['sql'] string: + + :::ruby + def on_migrate_source(old_version, new_src) + # ... do something like alert user ... + false # create table by source schema - useful only for non-synced models + end + +**NOTE: When migrating a table with source data that was synchronized, data must be copied to the new table before the first sync can occur. The sync function will not populate a blank table**. + +### Property Bag Data Migrations +Since its attributes are dynamic, the Property Bag database requires no data migrations when changes are made to its schema. + +### Removing Local Data From a Device +This scenario will work for Property Bag and Fixed Schema models. + +To remove all local data when upgrading to new application version, simply change `app_db_version` in the `rhoconfig.txt` file. + +## Adding new objects +To create a new model object and save it to the database, use the `create` method: + + :::ruby + user = User.create( + :name => 'Alice', + :email => 'alice@example.com') + +NOTE: This is the fastest way to insert a single item into the database. + +It's possible to create the new model object without saving it automatically, and then explicitly use the `save` method. This is useful for updating some of the object attributes before saving: + + :::ruby + user = User.new(:name => 'Alice') + # update the object + user.email = 'alice@example.com' + user.save + +## Retrieving objects +Use the find method to retrieve all objects for a model or only those matching given conditions. + +### Getting all objects for a model +To retrieve all objects for a model using the `all` parameter: + + :::ruby + users = User.find(:all) + +### Finding objects matching conditions +To retrieve all objects matching given conditions using the `conditions` parameter: + + :::ruby + users = User.find( + :all, + :conditions => {:name => 'Alice'} + ) + +### Numeric field comparisons in property bag models +Because Property Bag models internally store all their values in the same column, this column is defined as `varchar`, which means that a number comparisons might not work as expected. To perform order comparisons on a numeric field in a Property Bag model, use CAST to convert the value to a number of the desired type: + + :::ruby + @accts = Account.find(:all, + :conditions => { {:func=> 'CAST', :name=>'rating as INTEGER', :op=>'<'} => 3 } ) + #or using sql query: + size = 3 + @accts = Account.find(:all, + :conditions => ["CAST(rating as INTEGER)< ?", "#{size}"], :select => ['rating'] ) + +### Ordering the objects +Use the `order` and `orderdir` parameters to retrieve objects sorted by one or more attributes: + + :::ruby + # order by one attribute + users = User.find( + :all, + :order => 'name', + :orderdir => 'DESC' + ) + + # order by multiple attributes + users = User.find( + :all, + :order => ['name', 'email'], + :orderdir => ['ASC', 'DESC'] + ) + +### Retrieving specific attributes +If only some attributes in an object are needed for a particular action, increase app performance by using the `select` parameter to choose only the required attributes: + + :::ruby + users = User.find( + :all, + :select => ['name'] + ) + +### Paginating results + +Pass `offset` and `per_page` parameters to the `find` method to retrieve objects in chunks. + + :::ruby + # get first 10 records + users = User.find(:all, :per_page => 10) + + # get records 21-40 + users = User.find(:all, :offset => 20, :per_page => 20) + +The `paginate` method emulates Rails' classic pagination syntax. The default page size is 10. + +Use `:conditions`, `:order` and `select` parameters in a way similar to the `find` method: + + :::ruby + # get first 10 records + users = User.paginate(:page => 0) + + # get records 21-40 + users = User.paginate(:page => 1, :per_page => 20) + +### Retrieving only the first object matching conditions +Retrieve only the first object matching given conditions using `first` instead of `all` when calling `find`: + + :::ruby + user = User.find( + :first, + :conditions => {:name => 'Alice'} + ) + +### Using SQL queries directly +Retrieve model object(s) directly using SQL queries with the `find_by_sql` method. This method works only for fixed schema models: + + :::ruby + users = User.findBySql('SELECT * FROM User') + +## Counting objects +Get the number of objects matching given condition(s) using the `count` parameter with `find` method: + + :::ruby + count = User.find( + :count, + :conditions => {:name => 'Alice'} + ) + +## Updating +Update an object’s attributes and save to the database using the `update_attributes` method: + + :::ruby + user = User.find(:first, :conditions => {:name => 'Alice'}) + user.update_attributes( + :name => 'Bob', + :email => 'bob@example.com') +NOTE: This is the fastest way to add or update item attributes. + +## Deleting +### Deleting one object +To delete a single model object, use the `destroy` method on the object to be deleted: + + :::ruby + user = User.find(:first) + user.destroy + +### Delete multiple objects +To delete all objects for a model, or only those matching given condition(s), use the `delete_all` method: + + :::ruby + # delete all objects + User.delete_all() + + # delete only objects matching :conditions + User.delete_all(:conditions => {:name => 'Alice'}) + +## Transactions +For database operations that must either succeed or fail as a group without leaving any partially completed operations, use transactions to group them together. Combine any set of object/model operations, such as ‘insert/update/delete’ under a transaction: + + :::ruby + db = Rho::Database.new + db.startTransaction + begin + # do multiple operations + User.create(:name => 'Alice', :email => 'alice@example.com') + User.create(:name => 'Bob', :email => 'bob@example.com') + + # no errors, so commit all the changes + db.commitTransaction + rescue + # on error rollback all changes + db.rollbackTransaction + end + +## Executing SQL +To execute SQL statements directly on the database, use the `Database.executeSql` method: + + :::ruby + begin + db = Rho::Database.new(Rho::Application.databaseFilePath('app'),'app'); + result = db.executeSql('SELECT * FROM User') # result is an array of hashes, where each hash is a record + ensure + db.close + end + + :::ruby + db.executeBatchSql("UPDATE User set valid=0; Update Account set active=0") + +## Resetting database +To recover the database from a bad or corrupt state or if the RhoConnect server returns errors, use the following method to delete all objects for given model(s): + +### Delete all objects for given models. + + :::ruby + Rho::ORM.databaseFullResetEx(:models => ['User'], :reset_client_info => true, :reset_local_models => true) + +## Adding more fields to an existing model + +The list of attributes (fields) in a model can be updated as development progresses. If using the Property Bag storage scheme (the default), all that's required is to add the relevant code to the views (`index.erb`, `edit.erb`, `new.erb` and `show.erb`); Rhodes will take care of the rest. If using Fixed Schema, add the appropriate lines in the `.rb` file: + + :::ruby + property : : + +For example, in the `Product` model, we could add: + + :::ruby + property :color, :string + +For further details, please refer to the [Using the local database](../rhodes/rhom#fixed-schema) guide, which also contains methods to fine-tune data synchronization. + +## Linking a model to a RhoConnect synchronization server + +### What is RhoConnect? +RhoConnect is the server-side component of the RhoMobile Suite that connects mobile applications to external data sources and handles all aspects of data synchronization. Whether data comes from a relational database, NoSQL data store, RESTful web services or any other data source, RhoConnect bridges the gap between mobile clients and server resources. RhoConnect frees the developer from having to write complex synchronization code that's error-prone and hard to maintain. + +### Integrating a RhoMobile app with RhoConnect +Once an application can store data about a particular model, enabling two-way synchronization with a RhoConnect server is a one-step process. + +To enable synchronization in a RhoMobile app, simply open the model file (i.e. `product.rb`) and uncomment the line: + + :::ruby + enable :sync + +As long as RhoConnect server is properly configured, this is all that is required to benefit from automatic, two-way synchronization. See the [RhoConnect Tutorial](../tutorial/rhoconnect) for in-depth information about the benefits RhoConnect provides, as well as [Using the local database](../rhodes/rhom#fixed-schema) to find out how to tune data synchronization according to the needs of the application. + +## Associations +Rhom has a `sync association` called `belongs_to` which can be used to trigger updates on sync-enabled models. This is useful when relationships between backend service objects exists. + +For example, an app might contain a list of customers assigned to a sales person: + + :::ruby + class Customer + include Rhom::PropertyBag + + # Declare container model and attribute. + belongs_to :salesrep_id, 'SalesRep' + end + +The value used as the identifier for linking objects is the `object` property: + + :::ruby + def create + @customer = Customer.new(@params['customer']) + @customer.save + + sales_rep = SalesRep.find(...) # find the appropriate sales representative for new customers + customer.salesrep_id = @sales_rep.object + customer.save + redirect :action => :index + end + +Polymorphic sync associations, or associations across multiple classes, also can be defined using array notations or multiple declarations: + +Using array notation: + + :::ruby + belongs_to :parent_id, ['Product', 'Case'] + +Using multiple declarations: + + :::ruby + belongs_to :parent_id, 'Product' + belongs_to :parent_id, 'Case' + + +If planning to use the bulk sync feature for associated models, consider the corresponding support on the RhoConnect Server side. See [RhoConnect Bulk Sync associations](../rhoconnect/bulk-sync#bulk-sync-associations). + +## Freezed models +To limit model attributes to a specific list, the model can be 'freezed': + + :::ruby + class Customer + include Rhom::PropertyBag + + enable :sync + + set :freezed, true + + property :address, :string + property :city, :string + property :email, :string + end + +If an attempt is made to set a property on a freezed model that has not been explicitly defined, an ArgumentError exception will result: + + :::ruby + obj = Customer.new( :wrong_address => 'test') #will raise ArgumentError exception + obj = Customer.create( :wrong_address => 'test') #will raise ArgumentError exception + + obj = Customer.new + obj.wrong_address = 'test' #will raise ArgumentError exception + + obj = Customer.new + obj.update_attributes(:wrong_address => 'test') #will raise ArgumentError exception + +**NOTE: FixedSchema models are 'freezed' by default.** + +## Resetting the Database +Rhodes provides the following functions for recovering the database from a bad or corrupt state, or if the RhoConnect server returns errors. + +### `Rhom::Rhom.database_full_reset(reset_client_info=false, reset_local_models=true)` +Deletes all records from the property bag and model tables. + + :::ruby + # reset_client_info If set to true, client_info + # table will be cleaned. + # + # reset_local_models If set to true, local(non-synced models) + # will be cleaned. + Rhom::Rhom.database_full_reset(false,true) + +### `Rhom::Rhom.database_full_reset_and_logout` +Perform a full reset and then logout the RhoConnect client. + + :::ruby + Rhom::Rhom.database_full_reset_and_logout + +### `Rhom::Rhom.database_fullclient_reset_and_logout` +Equivalent to `Rhom::Rhom.database_full_reset(true)` followed by `SyncEngine.logout`. + + :::ruby + Rhom::Rhom.database_fullclient_reset_and_logout + +**NOTE: If the sync error "Unknown client" is displayed in the sync callback, this means that the RhoConnect server no longer knows about the client and a `Rhom::Rhom.database_fullclient_reset_and_logout` is recommended. This error requires proper intervention in the app to handle the state before resetting the client. For example, a sync notification could contain the following:** + + :::ruby + if @params['error_message'].downcase == 'unknown client' + puts "Received unknown client, resetting!" + Rhom::Rhom.database_fullclient_reset_and_logout + end + +### `Rhom::Rhom.database_local_reset` +Reset only local(non-sync-enabled) models. + + :::ruby + Rhom::Rhom.database_local_reset + +### `Rhom::Rhom.database_full_reset_ex( :models => [model_name1, model_name2], :reset_client_info=>false, :reset_local_models => true)` +Deletes all records from the property bag and model tables, if models are set then reset only selected models + + :::ruby + # models Array of models names to reset + # reset_client_info If set to true, client_info + # table will be cleaned. + # + # reset_local_models If set to true, local(non-synced models) + # will be cleaned. + Rhom::Rhom.database_full_reset_ex(:models => ['Product', 'Customer']) + +## Advanced Queries +### `find(*args)` (advanced conditions) +Rhom also supports advanced find `:conditions`. Using advanced `:conditions`, rhom can optimize the query for the property bag table. + +Let's say we have the following SQL fragment condition: + + :::ruby + Product.find( + :all, + :conditions => [ + "LOWER(description) like ? or LOWER(title) like ?", + query, + query + ], + :select => ['title','description'] + ) + +Using advanced `:conditions`, this becomes: + + :::ruby + Product.find( + :all, + :conditions => { + { + :func => 'LOWER', + :name => 'description', + :op => 'LIKE' + } => query, + { + :func => 'LOWER', + :name => 'title', + :op => 'LIKE' + } => query + }, + :op => 'OR', + :select => ['title','description'] + ) + +You can also use the 'IN' operator: + + :::ruby + Product.find( + :all, + :conditions => { + { + :name => "image_uri", + :op => "IN" + } => "'15704','15386'" + } + ) + + # or use array notation + Product.find( + :all, + :conditions => { + { + :name => "image_uri", + :op => "IN" + } => ["15704","15386"] + } + ) + +You can also group `:conditions`: + + :::ruby + cond1 = { + :conditions => { + { + :func => 'UPPER', + :name => 'name', + :op => 'LIKE' + } => query, + { + :func => 'UPPER', + :name => 'industry', + :op => 'LIKE' + } => query + }, + :op => 'OR' + } + + cond2 = { + :conditions => { + { + :name => 'description', + :op => 'LIKE' + } => 'Hello%' + } + } + + @accts = Account.find( + :all, + :conditions => [cond1, cond2], + :op => 'AND', + :select => ['name','industry','description'] + ) + +## Find by numeric field +To use number comparison conditions in `find`, use `CAST`: + :::ruby + @accts = Account.find(:all, + :conditions => { {:func=> 'CAST', :name=>'rating as INTEGER', :op=>'<'} => 3 } ) + #or using sql query: + size = 3 + @accts = Account.find(:all, + :conditions => ["CAST(rating as INTEGER)< ?", "#{size}"], :select => ['rating'] ) + +## Database Encryption + +**NOTE: [Rhom data encryption](../../2.2.0/rhodes/rhom#database-encryption) is no longer available as of Rhodes 3.3.3 and higher. This feature is now supported only in Zebra RhoMobile Suite and requires the purchase of a [RhoElements license](licensing).** + +If the application requires local (on-device) database encryption, enable it by setting a flag in `build.yml`: + + :::yaml + encrypt_database: 1 + +**NOTE: Database encryption is not currently supported for applications that use bulk sync.** + +### Platform Notes +* iOS uses an AES 128 encryption algorithm from the iOS SDK. +* Android uses an AES 128 ecryption algorithm from the Android SDK. +* Windows Mobile uses an RC4 algorithm from Windows Mobile SDK. + +## Related reading + +* [Database API reference](../api/Database) \ No newline at end of file diff --git a/docs/en/5.5/guide/rhomobile-install.md b/docs/en/5.5/guide/rhomobile-install.md new file mode 100644 index 00000000..1f84ff61 --- /dev/null +++ b/docs/en/5.5/guide/rhomobile-install.md @@ -0,0 +1,304 @@ +# Install RhoMobile Suite +The RhoMobile Suite allows the development of apps that can run on multiple mobile platforms from a single code base. In essence, these apps employ a web-like front end that renders on a platform-specific webkit, which passes device calls through to the underlying hardware. RhoStudio also can build native apps for Android, iOS and Windows Mobile and Windows Phone 8 using the corresponding SDK(s). + +At minimum, the RhoMobile installer places the Rhodes open-source development framework and the RhoStudio (Eclipse) IDE on the development host system. Also included are Zebra's RhoConnect and RhoElements components, optional modules for creating apps that connect and sync with one or more back-end systems and/or that support Zebra's enterprise-grade devices. Native SDKs, if desired, are installed separately. + +RhoMobile depends on Java, Ruby, Git and other tools. Depending on the development host platform, these components are either installed automatically with the main suite or must be installed manually using the platform-specific processes below. **Please read and follow all instructions carefully to ensure a trouble-free installation.** + +## Upgrading From a Prior Installation +Upgrading a system that already has a prior version of RhoMobile Suite usually requires fewer steps than a full installation, but still requires you to [download the latest software image](http://rhomobile.com/download/). If upgrading, follow those steps first. If that fails, try a full installation. + +NOTE: IMPORTANT: The update function in the "About RhoStudio..." dialog is currently disabled. + +If your machine already has RMS installed, **[get the latest RhoMobile suite for Mac or Windows](http://rhomobile.com/download/), then follow the instructions below.** + +###For Mac OS X (.dmg file): +1- **Drag-copy the RhoStudio folder** from the .dmg to your Applications folder. You'll see a message like the one below. **Be sure your 'workspace' folder is not in the same folder as the RhoStudio application** (by default, it's in the user's home directory, **not** in the RhoStudio folder). + +![img](http://rhomobile-suite.s3.amazonaws.com/install/New_RhoStudio_replace_old.png) + +2- **When you've confirmed that your projects are elsewhere, click 'Replace'**
                                                                              +3- When copying from Step 2 is compete, **run the "Install Gems" script** from the .dmg
                                                                              +4- **Launch RhoStudio from the latest Launcher** script (provided)
                                                                              +5- Go to **RhoMobile>>Preferences>>RhoMobile** and update Java bin path settings + +* **Be sure to browse to your *System* Library**, which is directly below the root +* Do **not** point to your user's Library folder
                                                                              + +6- If you're building locally, click **Android** (under RhoMobile prefs branch) and re-enter path settings for Android SDK and NDK
                                                                              +NOTE: RMS 5.1 is NOT compatible with Android NDK 10; Android NDK 9d is recommended. + +7- **Create or update any application aliases** for the new RhoSuite Launchers.
                                                                              + +![img](http://rhomobile-suite.s3.amazonaws.com/install/Java_bin_path.png) + +###For Windows (.exe file): +1- **Launch the RhoMobile Suite Installer** (.exe)
                                                                              +2- **Update Start Menu/Start Screen shortcuts** as necessary
                                                                              +3- Go to **Window>>Preferences>>RhoMobile** and update Java bin path settings, if necessary
                                                                              +4- If you're building locally, click **Android** (under RhoMobile Preferences branch) and re-enter path settings for Android SDK and NDK if necessary
                                                                              +NOTE: RMS 5.1 is NOT compatible with Android NDK 10; Android NDK 9d is recommended. + +If the upgrade steps have failed, or if you're installing RhoMobile Suite for the first time, follow the instructions below for a first-time installation. + +## Windows First-time Install (32- and 64-bit) +### STEP 1: Run the RhoMobile Suite Installer +[Download the RhoMobile Suite Installer for Windows](http://rhomobile.com/download/) and launch it. This will install Rhodes, RhoStudio, RhoConnect and RhoElements, as well as [Ruby](http://www.ruby-lang.org/en/) and [Redis](http://redis.io/) open source tools. + +Additional installers will automatically launch for [Git](https://github.com/) and [Node.js](https://nodejs.org/). Follow prompts and read and accept their respective open-source license agreements as appropriate. + +**NOTE: During installation, certain virus detectors might warn about a "Suspicious.MLApp" security risk in the "rubyw.exe" file. This false-positive can be safely ignored.
                                                                              ** + +### STEP 1a: For Windows 8.1 Only +Since Windows 8.x lacks a Start Menu, a few extra steps are needed to make the RhoMobile launchers visible. + +After running the RhoMobile installer in Windows 8.x, do the following: + +* Go to the "Start Screen" of Windows 8 (aka "Metro") and right-click at the bottom of the screen until the App Bar appears (on Win8.1, the button should appear without right-clicking). + +* Click the "All Apps" button to show all apps. Locate the "RhoMobile Suite" group (see image, below). Once installation is completed, you can run the desired RhoMobile launcher from there, or... + +* Right-click the desired launcher and select "Pin to Taskbar." This will make it easy to access from the Desktop in the future. Repeat this action for other launchers and for links to Documentation and Developer Community, if desired. + +RhoStudio on Win_8 + +NOTE: By default, the Windows 8 Desktop allows 32-bit applications only. For running the 64-bit version of RhoStudio, see "Notes for 64-bit Windows Systems, below. Additional Windows settings also might be necessary. + +### STEP 2: Install the Java Development Kit +RhoStudio requires the Java Development kit, which is different than the Java that might already be present for browsers. Unless you're sure you already have the JDK, visit [Oracle's Java Developer Kit download page](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) and select, download and install the version that's appropriate for your system. + +### Notes for 64-bit Windows +The 32- and 64-bit versions of RhoMobile are functionally equivalent, and there's no disadvantage to using the 32-bit RhoMobile suite on development hosts with 64-bit Windows. However, if you'd prefer to run the 64-bit version of RhoMobile on your 64-bit Windows machine, you'll need to manually download and install the 64-bit version of the Java development kit. + +*NOTE: The Java Development Kit is different than Java versions that might already be on your system for browsers.* + +####To get the 64-bit JDK: + +* Visit visit [Oracle's Java Developer Kit download page](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) and select, download and install the 64-bit Java version for Windows. +* To confirm the the JDK path, launch RhoStudio and go to **Window>>Preferences>>RhoMobile**. +The "Java bin path" should be: **C:\Program Files\Java\jdk<version number>\bin** + +### STEP 3: Launching RhoStudio + +The RhoMobile installer for Windows places the following items in the Windows Start menu or Start Screen (Windows 8.x in "All Apps" view mode): + +* Launchers for RhoStudio 32- and 64-bit editions +* A link to the Readme file +* Links to the [RhoMobile Developer Community](http://developer.motorolasolutions.com) and [RhoMobile Documentation](/home) sites +* A link to the RhoConnect Push Service files +* An uninstaller for RhoMobile Suite + +**NOTE:To run RhoStudio, you MUST USE THE RHOSTUDIO LAUNCHERS. + +NOTE:Before building your first project, you'll be prompted to create a free account at http://rms.rhomobile.com. Just enter a valid email address and password. + +### *Ruby Notes* +>The RhoMobile Suite installer for Windows contains Ruby 1.9.3-p194. This version of Ruby is used for executing rake commands on the development host computer and for running RhoConnect applications. + +>Native applications built with RhoStudio use Ruby 1.9.2-p290 on the target device. +
                                                                              + + +## Mac OS X First-time Install + +### *Apple XCode Required* + +> The Mac OS X installation relies on Apple's XCode development environment and the corresponding Command Line Tools. If XCode is not already installed, please visit [Apple's developer download site](http://developer.Apple.com/downloads) and download and install the version appropriate for your system before proceeding. + +###The Mac OS X installation steps:
                                                                              +#####`-->> This process requires administrator access and write permissions in all areas. <<-- ` +`-->> Steps MUST be performed in the following order <<-- `
                                                                              +#####0. Download and install XCode and corresponding Command Line Tools
                                                                              +#####1a. Download RhoMobile Suite (.dmg) from [RhoMobile.com](http://rhomobile.com/download)
                                                                              +#####1b. Copy RhoStudio to the development system's Applications folder `DO NOT LAUNCH!`
                                                                              +#####2. Download and install the Java 6 SDK from Java.com (see link, below)
                                                                              +#####3. Use Terminal to install Ruby Version Manager (RVM)
                                                                              +#####4. Use RVM to install Ruby 1.9.3 (even if you have a newer version)
                                                                              +#####5. Run the "install gems" Terminal script from the RhoMobile Suite .dmg +**OPTIONAL STEPS:** +#####Set up native SDKs for specific target devices (Android, iOS)
                                                                              +#####Run the "Install RhoConnect-push" Terminal script

                                                                              + +#### Detailed instructions for Mac OS X Installations: + +###STEP 1: Download and Copy RhoMobile Suite +`-->> Steps MUST be performed in the following order <<-- `
                                                                              + +a. [**Download RhoMobile Suite**](http://rhomobile.com/download) disc image (a .dmg file) and double-click it. A window similar to the following will open:
                                                                              + +![img](http://rhodocs-images.s3.amazonaws.com/guide/RhoMobile_Installer_disc_image.png) + +
                                                                              +b. **Drag the RhoStudio icon to the Applications folder alias** (in the direction of the arrow). This will copy the suite's main executables and some other useful files to the Applications folder of the development Mac. DO NOT ATTEMPT TO LAUNCH RHOSTUDIO AT THIS TIME. + +>Keep the RhoMobile Suite Installer .dmg handy; we'll refer to it again in STEP 5. + +### STEP 2: Install the Java Development Kit +RhoStudio relies on desktop Java, which Apple stopped including with Mac OS X as of version 10.7 (Lion). RhoMobile supports JDK 6.0 and higher. Regardless of what you currently have, we recommend that you [**download the latest JDK** from Java.com](http://www.java.com/en/download/). This is different than the version of Java that might already be on your system for browsers. + +**Download and open the JDK .dmg, double-click the package within it and follow prompts to install the latest JDK.** + +### STEP 3: Install Ruby Version Manager (RVM) +This step installs a tool called Ruby Version Manager (RVM) that we'll use to install Ruby 1.9.3. RhoStudio requires Ruby v1.9.3 and is not compatible with any other version, incuding the newer version (2.0) that comes with Mac OS X Mavericks and Yosemite. Fortunately, RVM makes it easy to switch between Ruby versions if you need to later. + +**NOTE: WARNING: Do not use `sudo` to install RVM; it can cause problems with file permissions when running bundle commands from within RhoStudio.
                                                                              ** + +**To install RVM, open a Terminal* window and enter (or copy and paste) the following command at the `$` prompt:** + +`\curl -sSL https://get.rvm.io | bash -s stable`
                                                                              + +This command securely downloads the latest stable version of RVM from the "get.rvm.io" web site.
                                                                              + +**Follow prompts and enter information as needed.** + +Terminal is included with Mac OS X and is in the Applications folder. +To launch Terminal without having to navigate to the Apps folder: **CMD-SPACE >> Type 'Term' >> Hit ENTER** + +### STEP 4: Install Ruby 1.9.3 +Now that you have RVM, you can use it to install Ruby 1.9.3 and some other useful stuff. Remember, RhoMobile requires Ruby 1.9.3 and will not work with other versions. This step will not effect existing Ruby version(s) on your Mac, but Ruby 1.9.3 will become the default. + +**Open a _NEW_ Terminal window and install Ruby 1.9.3 with the following command:** + +`rvm install 1.9.3` + +**You also might be prompted to install [homebrew](http://brew.sh/).** If so, just hit ENTER to install it in the default `/user/local` directory. Respond to additional prompts as needed. This step may take a few minutes. + +**Once complete, verify that Ruby 1.9.3 is the default by entering this command:** + +`ruby -v` + +The result should be something similar to this: +`ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-darwin14.0.0]` + + +### STEP 5: Install Ruby Gems + +**Almost done!** The final required step is to install Ruby gems. Gems are platform- and processor-specific Ruby apps and libraries that deliver much of the key functionality of the RhoMobile platform. Gems are copied from the installation disk image (.dmg) to your hard drive using a Terminal script included with the installer image. + +**Double-click "Install gems" from the RhoMobile Suite Installer .dmg (below) introduced earlier.
                                                                              ** +A Terminal window will open and execute an installation script.
                                                                              + +![img](http://rhodocs-images.s3.amazonaws.com/guide/RhoMobile_Installer_Install_gems.png) + +**When prompted, select N to avoid using `sudo` to install gems.** This process might take a while; it copies several groups of gems. + +**NOTE: WARNING: If additional gems are needed in the future, do not use `sudo` to install them; it can cause problems with file permissions when running bundle commands from within RhoStudio.
                                                                              ** + +**If you're given a choice similar to the one below, select option 1.** + +![img](http://rhodocs-images.s3.amazonaws.com/guide/which_ruby.png) + +**NOTE: CAUTION: In the unlikely event that you've mounted more than one disc image containing gems, it's important to unmount all except the current RhoMobile Suite version. Failure to do so might result in an improper installation.**
                                                                              + +>That's it! You've completed all the required steps to use your Mac and RhoMobile to develop cross-platform applications from a single code base!

                                                                              + +**IMPORTANT: To launch RhoMobile, you MUST use one of the RhoMobile Launchers indicated in the image below.** + +>![img](http://rhodocs-images.s3.amazonaws.com/guide/RhoMobile_launchers.png)

                                                                              +> FYI: The 32- and 64-bit versions of RhoMobile are functionally equivalent. + +>Before building your first project, you'll be prompted to create a free account at [rms.rhomobile.com](http://rms./rhomobile.com). Just enter a valid email address and password). + +>The installer image also contains files labeled "Launchpad" and "RhoMobile Docs" (scroll down in the .dmg window if you can't see them). You can copy these or bookmark their links to the [RhoMobile developer community](https://developer.motorolasolutions.com/welcome) and [RhoMobile documentation](http://docs.rhomobile.com/) sites.
                                                                              +
                                                                              + + +## Installing Native SDKs (Optional) +RhoStudio permits development of native apps for Android, iOS and Windows Mobile and Windows Phone 8 on the local development host or in the cloud using [Rhohub.com](https://rms.rhomobile.com/). If you plan to build native apps locally, you'll need to install the corresponding SDKs for each. For detailed instructions, please visit RhoMobile's [native SDK setup documentation page](/guide/nativesdksetup).
                                                                              +
                                                                              + +## Troubleshooting Windows Installs + +###PROBLEM +>"Failed to create the Java Virtual Machine"
                                                                              + +>**POSSIBLE CAUSE**
                                                                              +>Insufficient memory + +>**SOLUTION**
                                                                              +>Reduce the size of the JVM heap:
                                                                              + +>1) Use a text editor to open the file:

                                                                              +`\rhostudio\win32.win32.x86_64\RhoStudio.ini`

                                                                              +>2) Search for `-Xmx1024m`

                                                                              +>3) Change it to `-Xmx512m`
                                                                              + +>This will halve the memory used by the Java Virtual Machine
                                                                              + +###PROBLEM +>"Failed to load the JNI shared library..."
                                                                              + +>**POSSIBLE CAUSE**
                                                                              +>Incompatibility between the RhoStudio launcher and the JDK version installed. + +>**POSSIBLE SOLUTIONS**
                                                                              +>- Make sure the JDK and RhoStudio launcher match x86 vs. x64) +>- Reinstall the JDK + +###PROBLEM +>RhoStudio fails to start and displays no message
                                                                              + +>**POSSIBLE CAUSE**
                                                                              +>Attempting to launch 64-bit RhoStudio without 64-bit Java + +>**SOLUTION**
                                                                              +Install 64-bit Java (see above)
                                                                              + +###PROBLEM +>RhoConnect applications don't work properly
                                                                              + +>**POSSIBLE CAUSE**
                                                                              +>Spaces exist in the Workspace path + +>**SOLUTION**
                                                                              +>Go to **Window>>Preferences>>Startup and Shutdown>>Workspaces** and select a Workspace path that contains no spaces.
                                                                              +
                                                                              + +## Troubleshooting Mac OS X Installs + +###PROBLEM +>![img](http://rhomobile-suite.s3.amazonaws.com/install/Cannot_find_Rhodes.png) + +>**POSSIBLE CAUSE**
                                                                              +>Failed to use one of the RhoStudio launcher scripts + +>**SOLUTION**
                                                                              +>Launch RhoStudio using either "RhoStudio 32-bits" or "RhoStudio 64-bits" scripts in the RhoStudio folder. **DO NOT** launch apps in the "cocoa" folders.
                                                                              + +>**FACT:** The 32- and 64-bit versions of RhoMobile are functionally equivalent. +>![img](http://rhodocs-images.s3.amazonaws.com/guide/RhoMobile_launchers.png)

                                                                              + +###PROBLEM +>![img](http://rhomobile-suite.s3.amazonaws.com/install/You_need_Java_SE.png) + +>**POSSIBLE CAUSES**
                                                                              +>Java not installed, installed incorrectly or wrong version + +>**SOLUTION**
                                                                              +>Install Java using instructions found in the Mac OS X section of this page + +###PROBLEM +>![img](http://rhomobile-suite.s3.amazonaws.com/install/Rho_cannot_be_opened.png) + +>**POSSIBLE CAUSE**
                                                                              +>Mac OS X security policy is preventing an unsigned/downloaded app from launching + +>**SOLUTION**
                                                                              +>1) Open the Mac OS X Preferences panel
                                                                              +>2) Click on "Security & Privacy" prefs, then hit General (below)
                                                                              +>3) The last blocked app will be shown. Click the "Open Anyway" button
                                                                              +>4) if necessary, re-launch RhoStudio using the launcher script
                                                                              + +>![img](http://rhomobile-suite.s3.amazonaws.com/install/Mac_Security_Prefs.png) + +###PROBLEM +>Random Java-related issues + +>**POSSIBLE CAUSE**
                                                                              +Incorrect Java bin path + +>**SOLUTION**
                                                                              +>Go to **RhoStudio>>Preferences>>RhoMobile** and set the Java bin path. The correct path should be similar to the image below:
                                                                              + +>![img](http://rhomobile-suite.s3.amazonaws.com/install/Java_bin_path.png) + diff --git a/docs/en/5.5/guide/ruby_extensions.md b/docs/en/5.5/guide/ruby_extensions.md new file mode 100644 index 00000000..ca3dcb2b --- /dev/null +++ b/docs/en/5.5/guide/ruby_extensions.md @@ -0,0 +1,291 @@ +# Ruby Native Extensions + +This doc will explain extensions to the Rhodes framework using Ruby and how to add them to your Rhodes app, including the handling of JSON and XML data with regards to your app's data. + +## Extensions + +In order to strike a balance between functionality and size, some Ruby libraries are available as extensions instead of being compiled into your application by default. Available extensions are located within the rhodes-4.x.x gem in `lib/extensions`. To use any of them in your application, all you need to do is add its name to the `extensions` section in `build.yml`. For example: + + :::yaml + extensions: ["pdf-writer"] + +If you are adding more than one, separate them with commas: + + extensions: ["pdf-writer", "json", "net-http"] + +Some extensions are specific to a particular platform. If an extension has an `ext.yml` file, open it and look for a `platforms` line listing the supported platforms. For example, the `serialport` extension is only available for Windows Mobile and desktop Windows. + +## JSON library support + +For parsing use Rho::JSON.parse, no extension required. + +Ruby code example: + :::ruby + parsed = Rho::JSON.parse("[{\"count\":10}]") + +If you need to generate (not parse) JSON, add the `json` extension. + +Add to build.yml: + + extensions: ["json"] + +Ruby code example: + :::ruby + require 'json' + json_data = ::JSON.generate(some_object) + +See JSON tests in [Rhodes System API Samples application](http://github.com/rhomobile/rhodes-system-api-samples/tree/master/app/JsonTest/controller.rb) as an example. + +## XML handling +There are two ways of handling XML directly in Rhodes. The Rexml library and the much faster RhoXML library. + +### Rexml + +Add to build.yml: + + extensions: ["rexml", "set"] + +Ruby code example: + :::ruby + require 'rexml/document' + file = File.new("bibliography.xml") + doc = REXML::Document.new(file) + puts doc + +### RhoXML +This is a reduced version of rexml. Rhoxml has the same syntax as rexml, but smaller in size and faster. + +Change rexml to rhoxml in build.yml: + + extensions: ["rhoxml"] + +No more changes required. + +Rhoxml limitations: + +1. Decoding xml text is not fully implemented. See document.rb line 503 (Text::unnormalize). Need to implement non regular expression decoding. +2. No DTD, validation and formatters support +3. Support only elements and attributes. No cdata, comments, etc. + +### XML Stream parser + +To process xml faster (without building DOM xml tree in memory) you can use StreamParser: + :::ruby + class MyStreamListener + + def initialize(events) + @events = events + end + + def tag_start name, attrs + #puts "tag_start: #{name}; #{attrs}" + @events << attrs if name == 'event' + end + def tag_end name + #puts "tag_end: #{name}" + end + def text text + #puts "text: #{text}" + end + def instruction name, instruction + end + def comment comment + end + def doctype name, pub_sys, long_name, uri + end + def doctype_end + end + def attlistdecl element_name, attributes, raw_content + end + def elementdecl content + end + def entitydecl content + end + def notationdecl content + end + def entity content + end + def cdata content + #puts "cdata: #{content}" + end + def xmldecl version, encoding, standalone + end + end + + def parse_xml(str_xml) + @events = [] + list = MyStreamListener.new(@events) + REXML::Document.parse_stream(str_xml, list) + ... + +It supported in RhoXml and Rexml extensions. For example see : [`\spec\phone_spec\app\spec\xml_spec.rb`](https://github.com/rhomobile/rhodes/blob/master/spec/phone_spec/app/spec/xml_spec.rb) ("should stream parse" spec) and rexml stream parser documentation + +## net/http + +Add to build.yml: + + extensions: ["net-http", "thread", "timeout", "uri"] + +## hmac + +Add to build.yml: + + extensions: ["hmac", "digest", "digest-sha1"] + +Example: + :::ruby + require 'base64' + require 'hmac-sha1' + + def test_hmac + key = '1234' + signature = 'abcdef' + hmac = HMAC::SHA1.new(key) + hmac.update(signature) + + puts Rho::RhoSupport.url_encode(Base64.encode64("#{hmac.digest}\n")) + end + +## FileUtils + +Add to build.yml: + + extensions: ["fileutils"] + +DryRun, NoWrite and Verbose are commented out modules since they use the `eval` function, which is not available in RhoMobile. + +Before adding the FileUtils extension, consider using the built-in Ruby class `Dir` whenever possible. + +## Adding Ruby Extension Libraries to Your Rhodes Application + +Create folder 'extensions' under application root if it does not exist already. + +Copy the folder with the Ruby library to the 'extensions' folder. This will work for "pure ruby" extensions. Extensions which are implemented in c/c++ or such, you will have to compile as [native extensions](native_extensions) for the target platform. + +Add extension with folder library name to build.yml: + + extensions: ["myext"] + +This library will be available for require: + :::ruby + require 'myext' + +Using this technique you can easily remove extension from application or include some extension for particular platform: + + iphone: + extensions: ["mspec", "fileutils"] + + wm: + extensions: ["json"] + +## Adding Libraries to Your Rhodes Application + +During the course of your app development you might need to add an external ruby library with extra features that the Rhodes framework doesn't provide. While we don't guarantee that all ruby libraries will work on the mobile device, you can follow the steps below to add and test libraries as needed. + +In RhoMobile, the require path is relative to the "app" subdirectory, since this is what gets bundled with the application. + +Assuming your application is called "mynewapp", create a directory called `lib` (if it does not exist already) and, within it, a directory to store the library: + + :::term + $ cd mynewapp + $ mkdir lib + $ mkdir lib/my_lib + +Add your ruby files to this directory: + :::term + $ cp /path/to/my_lib.rb lib/my_lib/my_lib.rb + + +Now, in your application (controller.rb for example), you can load this library with a simple `require` statement: + + :::ruby + require 'rho/rhocontroller' + require 'lib/my_lib' + + class TicketController < Rho::RhoController + def use_lib + @a = MyLib.new + ... + end + end + +Please note that "rubygems" are not loaded on the device Ruby VM because of size constraints, see the next section "Adding an external gem" for instructions therefore all third-party ruby library source files must be put into the extensions directory as described above. + +## Adding 3rd party gems + +Although other gems in your computer are not available within a RhoMobile application by default, some gems can be added and used: + +* download the gem from [RubyGems](http://www.rubygems.org) and save it to your machine +* gems are actually zip files with a different extension: rename the .gem file to .zip and unzip it +* the zip file will contain two other files, data.tar.gz and metadata.gz . Uncompress data.tar.gz +* although there is no hard requirement for this, most gems follow the pattern of having their code inside a directory called `lib` or, in some cases, a directory with the same name as the gem. This is the directory we are interested in + +Once you locate the directory with the library, copy it to your application following the procedure outlined above in "Adding Libraries to Your Rhodes Application". + +**NOTE: Many gems will not work out of the box in a RhoMobile application because gems are often developed with desktop/server computers in mind, not mobile devices and tend to use features that are simply not available within RhoMobile. In particular, gems requiring access to external libraries (.so/.dll) or platform-specific features will not work. You have a better chance of success if the gem is simple and has few or no dependencies; the more complex the code, the higher the possibility that it uses a module that is not available on a mobile device. Some gems with platform-native (C) code can be made to work if you convert them into a [native extension](native_extensions).** + + +## Adding Libraries to Rhodes Framework + +If you find yourself using the same library in most of your applications, you can add it directly to the base framework so that it is available by default when building any application. + +There are two ways to add Ruby libraries to the RhoMobile framework: + +* If you are using Rhodes via the RubyGems installation, you must add external Ruby libraries to your RubyGems installation directory for the 'rhodes-4.x.x' gem. Your RubyGems installation directory can be found with `gem env` in a terminal. + +For example, a user on Linux might place additional libraries in the following directory: + + /usr/local/lib/ruby/gems/1.9/gems/rhodes-x.x.x/lib/framework + +Similarly, a user on Mac OSX running the recommended RVM setup might place them here: + + ~/.rvm/gems/ruby-1.9.x-pxxx/gems/rhodes-x.x.x/lib/framework + +For Windows, this location might be: + + C:/ruby/lib/ruby/gems/1.9/gems/rhodes-x.x.x/lib/framework + + +If you are using a clone of the Rhodes Git repository, you can put additional libraries in the following directory (preferably on your own github fork): + + /lib/framework + +Including the library into your application is simple once the library is in the proper directory. + +Assuming the library has been added to the correct location, require the library from a controller in your Rhodes application: + :::ruby + require 'libname' + +You can now use the added library to access additional functionality not provided by the RhoMobile framework. + +**NOTE: The same notice applies no matter the location. Some libraries will simply not work on a RhoMobile application due to assumptions they make about the environment/operating system.** + +If you follow this procedure, remember that you will have to redo the steps whenever you upgrade to a new version of RhoMobile + + +## Encryption libraries +### digest - based extensions + +digest, digest-sha1, digest-md5 + +Add to build.yml: + + extensions: ["digest", "digest-sha1", "digest-md5"] + +NOTE: digest should be included in extensions list to use digest-base libraries + +### OpenSSL - based libraries + +openssl, ezcrypto + +Add to build.yml: + + extensions: ["openssl.so", "openssl", "digest-sha2", "ezcrypto"] + +digest-sha2 + +Add to build.yml: + + extensions: ["openssl.so", "openssl", "digest", "digest-sha2" ] + +NOTE: openssl.so is native c-library and should be included in extensions list to use openssl-base libraries \ No newline at end of file diff --git a/docs/en/5.5/guide/runtime_config.md b/docs/en/5.5/guide/runtime_config.md new file mode 100644 index 00000000..32905318 --- /dev/null +++ b/docs/en/5.5/guide/runtime_config.md @@ -0,0 +1,1390 @@ +# Application Runtime Configuration +Runtime configuration settings of RhoElements apps are managed through `Config.xml` and `rhoconfig.txt` files. **`Config.xml` is *required* for RhoElements execution, and your app will not start without it**. The `Config.xml` file determines features of the RhoElements runtime itself, such as the keys that can be intercepted by the application and whether to pre-load modules on startup. An example configuration file is provided as part of the installation and many (though not all) settings contain sensible defaults. The example `Config.xml` file is bundled with the `rhoelements` gem. Location of the file on various device installations is detailed below. + +The `rhoconfig.txt` file controls the app's startup page, the address of the `RhoConnect` synchronization server, if applicable, and some other settings. + +This guide explains the meanings of each of the settings and their possible values. + +###Vulnerability Alert + +>**Applies to Windows Mobile and Windows CE apps built with RMS 5.1 or higher**. + +>In Oct., 2014, a vulnerability was discovered affecting applications that use SSL3, which is part of the Zebra Webkit (Ekioh 3.1.1). Known as POODLE (Padded Oracle On Downgraded Legacy Encryption), the vulnerability [as described by the U.S. Comuputer Emergency Readiness Team](https://www.us-cert.gov/ncas/alerts/TA14-290A) would allow an attacker to exploit the means by which SSL 3.0 handles block cipher mode padding to decrypt and **extract information from inside an encrypted transaction**.

                                                                              To protect against this, **Zebra now ships the Zebra Webkit with SSL3 disabled by default**.

                                                                              + +>To forego this safeguard and enable SSL3, you must append the `` section of the `Config.xml`:
                                                                              + +>In `Config.xml`: + :::yaml + + ... + + # value="0" (SSL3 disabled) + # value="1" (SSL3 enabled) + # If not specified, SSL3 is enabled + ... + + + +## rhoconfig.txt +You can use `rhoconfig.txt` to add arbitrary values that are specific to your application and apart from settings recognized by the platform: + +Sample yaml code: + + :::yaml + # application-specific value + foo = 'bar' + +All values will be accessible at runtime via `Rho::RhoConfig`: + +Sample Ruby code: + :::ruby + foo = Rho::RhoConfig.bar + start_path = Rho::RhoConfig.start_path + +You also can check if a configuration property actually exists before accessing it: + +Sample Ruby code: + :::ruby + start_path_exists = Rho::RhoConfig.exists?("start_path") # will return true + +The `rhoconfig.txt` file generated with each new application contains the following default values along with descriptions of each setting: + +Sample yaml code: + :::yaml + # startup page for your application + start_path = '/app' + + # path to the options page (in this case handled by JavaScript) + options_path = '/app/Settings' + + # location of bundle url (i.e. from rhohub.com); used by desktop win32 simulator + rhobundle_zip_url = '' + + # optional password to access bundle (usually not required); used by desktop win32 simulator + rhobundle_zip_pwd = nil + + # Rhodes log properties + # log level + # 0-trace, 1-info(app level), 2-warnings, 3-errors + # for production set to 3 + MinSeverity = 1 + + # enable copy log messages to standard output, useful for debugging + LogToOutput = 1 + + # '*' means all categories, otherwise list them : Cat1, Cat2 + LogCategories = * + + # what categories to exclude + ExcludeLogCategories = + + # max log file size in Bytes, set 0 to unlimited size; when limit is reached, log wraps to beginning of file + MaxLogFileSize=50000 + + # turn on local http server traces, off by default + #net_trace = 0 + + # timeout of network requests in seconds (30 by default) + #net_timeout = 60 + + # where log will be posted by RhoConf.send_log or from the log menu + # source is also open and up on http://github.com/rhomobile/rhologs, so you can deploy your own logserver + logserver = 'http://rhologs.heroku.com' + + # log file prefix - contain human-readable text + logname='rhodes-app' + + # Keep track of the last visited page + KeepTrackOfLastVisitedPage = 0 + LastVisitedPage = '' + + # sync server url, typically this will look like 'http://:/application' + # for example: 'http://localhost:9292/application' + syncserver = '' + + # 0 will disable auto sync + sync_poll_interval=0 + + # geo location inactivity timeout (in seconds) + # geo_location_inactivity_timeout = 30 + + # open rhodes app in full screen mode + # default 1 for Android up to Rhodes 2.2.5. + # on all other platforms and on Android from Rhodes > 2.2.5 default 0 + full_screen = 0 + + # show top menu on Windows desktop in full screen mode (default is 0=don't show top menu) + # w32_fullscreen_menu = 1 + + # disable the Android page loading progress bar + disable_loading_indication = 1 + + # Port of the local (embedded) HTTP server. This parameter is mainly for debug purposes. + # If not specified, application will use dynamically selected one. + # WARNING!!! Remove this parameter before put application to production. + # local_server_port = 8080 + + # show status bar on windows mobile. default 1 + # wm_show_statusbar = 1 + + # disable screen rotation (enabled by default) - disable possible for ANDROID and iPhone ONLY + # disable_screen_rotation = 1 + + # disable close app when pressing back on home screen on blackberry + # bb_disable_closebyback = 0 + + # load images in background, this improve reaction speed on user actions, 0 by default + # bb_loadimages_async = 0 + + # set to 0 to reset the bulksync_state and trigger a bulk sync the next time rhodes synchronizes + # bulksync_state = 1 + + # hides forward button and animates back button transition + jqtouch_mode=1 + + splash_screen='zoom' + + use_bb_full_browser=6 + + esri_map_url_roadmap: type: string + + ESRI server url with roads map tiles. + iOS - supported in esri extension. + Android - supported with ESRI map type. + WM - supported with WM mapview. + WP8 - mapping is not supported. + + esri_map_url_satellite: type: string + ESRI server url with satellite map tiles. + iOS - supported in esri extension. + Android - supported with ESRI map type. + WM - supported with WM mapview. + WP8 - mapping is not supported. + + OSM_map_url_roadmap: type: string + OSM server url with road map tiles. + iOS - not supported as only Google and ESRI maps are supported. + Android - supported with OSM map type. + WM - supported with WM mapview. + WP8 - mapping is not supported. + + disable_loading_indication:type - Bool + If enabled, blocks loading indication in webview + Supported only on Android. + +### Additional parameters that can be used in rhoconfig.txt + + :::yaml + iswindowskey=1 + # When set to '1' the Android version of the application will generate Windows Mobile + # keycode values for all keys in place of normal Android keycodes. This can be + # useful for supporting both Android and Windows device platforms with a single + # codebase. When tag value is '0' (default) or is left unspecified, the standard + # keycodes of the platform will be used. Works with the KeyCapture API of RhoElements + # 4.x or 2.x. + + http_proxy_host = 'server' + http_proxy_port = port + # Address and port of proxy server. This settings uses Network module. + # Do not include 'http://' while setting the http_proxy_host + + Example: + http_proxy_host = 'wwwxyz123.abc.com' + http_proxy_port = 6060 + + http_proxy_login = 'user' + http_proxy_password = 'password' + # Login and password for access to proxy server. Only basic authentication is supported + + clientSSLCertificate = 'certificate path' + clientSSLCertificatePassword = 'password' + # CLient SSL Configuration. The path to the p12 formatted certificate file and the password used with the client certificate. + # The path to the p12 formatted certificate file used for client SSL authentication. This setting is used in any Network API calls which setting up secured SSL + # connections requiring client authentication (get, post, downloadFile, uploadFile). This setting only takes effect if `verifyPeerCertificate` is enabled. + # Therefore, if `verifyPeerCertificate` is set to fail and remote server requests the client certificate, connection will fail. + # These two settings are only supported for use on Android devices. + + + ios_net_curl=0 + #If true, an old libCURL-based Net request will be used. This option can be enabled for regression testing or if custom proxy support is required. Default is TRUE, but to support per-app VPN (i.e. MobileIron) this option should be set to FALSE. + + ios_direct_local_requests=1 + #If true, request to local server will be applied directly, bypassing socket intercommunication, no network requests are involved. If false, a legacy client-server intercommunication will be made for local requests. Default is FALSE, but to support per-app VPN (i.e. MobileIron) this option should be set to TRUE. + + +## Config.xml + +####General notes about Config.xml +* The `Config.xml` file affects only applications that use Zebra's Webkit. + +* It determines features of the RhoElements runtime, including keys that can be intercepted by the application and whether to pre-load modules on startup. +* The `CaFile` setting applies only to apps built with RMS 4.0 that use the stock browser. + +* Full screen mode is currently unavailable for the iOS 7 SDK. For details and other differences, please refer to the [Differences in iOS7](build_ios#differences-building-for-ios7) section in the [Build for iOS](build_ios) doc. + + +###Location on desktops + +####Windows: +`\ruby\lib\ruby\gems\1.9.1\gems\rhoelements-4.0.0\libs\data\Config\Config.xml` + +#####Mac OS X: +`~/.rvm/gems/ruby-1.9.3-p392/gems/rhoelements-4.0.0/libs/data/Config/Config.xml` + +###Location on a mobile devices + +####On the Zebra Enterprise Tablet: +`/Android/data/com.motorolasolutions.rhoelements/Config.xml` + +####All other devices: +`\Config` + +####For persistent installations: +**On cold boot, `Config.xml` is copied from `\Application\RhoElements\Config\Config.xml`
                                                                              to `\Program Files\RhoElements\Config\Config.xml`**. + +* To persist settings after a cold boot, **store desired settings in both locations**. + +* **Modify this behavior by editing** `\Application\RhoElements.cpy`. + +* **Switch between `Config.xml` files using the /C: configuration option**. + +## Config.xml File Format +**Typical Config.xml file**: + :::xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Configuration settings and values + +The following section describes each Config.xml setting and all of its possible values. + +##ApplicationCache +###ApplicationCacheQuota +Application Cache data maximum quota per application.
                                                                              + +**Configuration Identifier**: APPLICATIONCACHEQUOTA
                                                                              +**Possible Values**: Size in bytes
                                                                              +**Platforms**: WM/CE Webkit
                                                                              + +###ApplicationCachePath +Path to an existing directory to store Application Cache data.
                                                                              + +**Configuration Identifier**: APPLICATIONCACHEPATH
                                                                              +**Possible Values**: Fully qualified local path (case sensitive)
                                                                              +**Platforms**: WM/CE Webkit
                                                                              + +##Authentication +###Password +Specifies the password to be provided automatically when RhoElements is instructed to navigate to any page which requires basic or digest HTTP authentication. If this setting is absent, a login prompt will be displayed with a password of "". + +NOTE: RhoElements permits the user to enter incorrect credentials twice before presenting the HTTP 401 Unauthorized page. Your application should be designed to handle this scenario.
                                                                              + +**Configuration Identifier**: AUTHPASS_GLOBAL
                                                                              +**Possible Values**: ASCII text
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Username +Specifies the username to be provided automatically when RhoElements is instructed to navigate to a page that requires basic or digest HTTP authentication. If this setting is absent, a login prompt will be displayed with a username of "". + +NOTE: RhoElements permits the user to enter incorrect credentials twice before presenting the HTTP 401 Unauthorized page. Your application should be designed to handle this scenario.
                                                                              + +**Configuration Identifier**: AUTHUSER_GLOBAL
                                                                              +**Possible Values**: ASCII text
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##DebugButtons +###DebugButtonsEnabled +When enabled, presents a set of controls useful for development and debugging purposes.
                                                                              + +**Configuration Identifier**: DEBUGBUTTONSENABLED
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##DefaultMetaTags +###MetaTag +Permits a default meta tag to be specified so that a tag required by the application need not be present on every HTML page. Set a default tag by specifying the tag's module, followed by the tilde character (~) and the properties of the module you wish to set, as specified in [EMML 1.1](../../2.2.0/rhoelements/EMMLOverview#emml-11-the-current-standard). If the meta tag is present in both the configuration and a loaded page, the page will take priority. Only persistent tags can be set logically in the configuration. Tag persistence is covered in the 'additional information' section in the help file.
                                                                              + +**Configuration Identifier**: DEFAULTMETATAG
                                                                              +**Possible Values**: [Module]~[Contents expressed in EMML1.1]
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + + + + + + +##DeviceKeys + +####About DeviceKeys + +* **DeviceKey settings are applied globally on the device**; they're not contained to a single application. +* **Once set, DeviceKey settings persist until reset by a warm boot**. + +[Read more about the interaction between FunctionKeysCapturable and EnableFunctionKey_X](#_fnbehavior).
                                                                              + +###EnableApplicationKey_X +* **Requires a preload of the KeyCapture module**. +* **Applies to Windows Mobile and Windows CE only; disabled by default**. +* **Application-key mapping is device-specific; behavior may vary from one device to another.** + +Specifies which WM/CE Application keys (numbered A1 to A16) should be enabled (all are disabled by default). For each key to be enabled, define a tag using `EnableApplicationKey_X`, replacing the 'X' with the key being enabled. For example, to enable key A5, your tag will include `EnableApplicationKey_A5` as below. See the [sample Config.xml file](#configxml-file-format) for correct branch placement. + +**Configuration Identifier**: Not Configurable
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Windows Mobile/CE
                                                                              + +**Sample XML code**: + :::xml + + ... + + ... + + +###EnableBacklightSlider +**Applies to Zebra's [MC2100 mobile computer](https://www.zebra.com/us/en/products/mobile-computers/handheld/mc2100.html) only**. + +Controls whether the backlight slider is available using the Orange+F2 key combination on the [MC2100](https://www.zebra.com/us/en/products/mobile-computers/handheld/mc2100.html). This setting is not application specific; it will be applied globally on the device.
                                                                              + +**Configuration Identifier**: ENABLEBACKLIGHTSLIDER
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Windows CE
                                                                              + +###EnableCtrlKey_X +Specifies which control-key combinations (copy, paste, etc.) should be enabled. **All are disabled on Windows CE by default**. + +To enable a control-key combination, define a tag using `EnableCtrlKey_X`, replacing the 'X' with the key being enabled. For example, to enable copying with control-C, your tag will include `EnableCtrlKey_C` as below. See the [sample Config.xml file](#configxml-file-format) for correct branch placement. + +**Configuration Identifier**: Not Configurable
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + + :::xml + + ... + + ... + + + +###EnableFunctionKey_X +**Requires a preload of the KeyCapture module**. + +This setting is used to specify which Function keys (F1 to F24) should be enabled (all Function keys are disabled by default). For each key to be enabled, define a tag using `EnableFunctionKey_X`, replacing the 'X' with the key number being enabled. For example, to enable F1, your tag will include `EnableFunctionKey_F1` as below. See the [sample Config.xml file](#configxml-file-format) for correct branch placement. + +**Configuration Identifier**: ENABLEFUNCTIONKEY_FX
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +**Sample XML code**: + + :::xml + + ... + + ... + + +####Device-specific notes +* **On the Enterprise Tablet, this tag can be used to enable the 'P' keys**. For example, if the sample code above were run on an Enterprise Tablet, it would enable the 'P1' key. +* This setting **on Windows Mobile and Windows CE** is applied globally to the device and can be reset with a warm boot. +* **On the Zebra MC40**, F1 is mapped to the volume-down button, F2 to the volume-up button and F3 to the search button. + +[Read more about the interaction between FunctionKeysCapturable and EnableFunctionKey_X](#_fnbehavior).
                                                                              + +###EnableVolumeSlider +**Applies to Zebra's [MC2100 mobile computer](https://www.zebra.com/us/en/products/mobile-computers/handheld/mc2100.html) only**. + +Controls whether the speaker volume slider is available using the Orange+F1 key combination on the [MC2100](https://www.zebra.com/us/en/products/mobile-computers/handheld/mc2100.html). **This setting is not application specific; it will be applied globally on the device**.
                                                                              + +**Configuration Identifier**: ENABLEVOLUMESLIDER
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Windows CE
                                                                              + +##FileLocations +###RegExFile +**Applies only to Windows Mobile/CE**. + +Defines the location of the XML file that contains the conversions to be used for backward compatibility with EMML 1.0.
                                                                              + +**Configuration Identifier**: REGEXFILE
                                                                              +**Possible Values**: Fully qualified path to file defining the regular expressions (case sensitive)
                                                                              +**Platforms**: Windows Mobile/CE
                                                                              + +###FunctionKeysCapturable +**Applies to Windows Mobile and Windows CE only; disabled by default**. + +Determines behavior of Function keys on Windows Mobile and Windows CE devices. When enabled, F-keys on WM/CE devices are capturable using the [Key Capture API](/api/keycapture). When disabled, keys revert to the device's default behavior. **This setting is not specific to an application. When enabled, settings are applied globally to the device**. + +**Configuration Identifier**: FUNCTIONKEYSCAPTURABLE
                                                                              +**Possible Values**: 0 - 'F keys' not capturable, 1 - 'F keys' capturable
                                                                              +**Platforms**: Windows Mobile/CE
                                                                              + +###PluginFile +Specifies location of the plug-in file (a .DLL on the device), which facilitates mapping between RhoElements modules. **Not applicable to the Enterprise Tablet**.
                                                                              + +**Configuration Identifier**: +PLUGINFILE
                                                                              +**Possible Values**: +Fully qualified path to file defining the plugins (case sensitive)
                                                                              +**Platforms**: +Android, iOS, WM/CE
                                                                              + +##General +###Name +Stores the name of the application.
                                                                              + +**Configuration Identifier**: Not Configurable
                                                                              +**Possible Values**: ASCII text
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###StartPage +Defines the start page of a RhoElements application, displayed at launch. This should be a local file to avoid connectivity issues on startup.
                                                                              + +**Configuration Identifier**: STARTPAGE
                                                                              +**Possible Values**: Fully qualified path to start page (case sensitive)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###UseRegularExpressions +**Applies only to apps for Windows Mobile/CE devices built with RhoMobile Suite 2.2 or higher that need backward compatibility with PocketBrowser**.
                                                                              + +Regular Expressions are used to maintain backward compatibility with PocketBrowser syntax for controlling device capabilities. If backward compatibility is not required, regular expressions can safely be disabled, possibly improving app performance. + +**Configuration Identifier**: USEREGULAREXPRESSIONS
                                                                              +**Possible Values**: 0 - Do Not Use Regular Expressions, 1 - Use Regular Expressions
                                                                              +**Platforms**: ###FunctionKeysCapturable +**Applies to Windows Mobile and Windows CE only; disabled by default**. + +Determines behavior of Function keys on Windows Mobile and Windows CE devices. When enabled, F-keys on WM/CE devices are capturable using the [Key Capture API](/api/keycapture). When disabled, keys revert to the device's default behavior. **This setting is not specific to an application. When enabled, settings are applied globally to the device**. + +**Configuration Identifier**: FUNCTIONKEYSCAPTURABLE
                                                                              +**Possible Values**: 0 - 'F keys' not capturable, 1 - 'F keys' capturable
                                                                              +**Platforms**: Windows Mobile/CE
                                                                              +
                                                                              + +##Geolocation +###GeolocationEnabled +Controls HTML5 Geolocation. When enabled on a device that supports geolocation and is in range of a GPS network, the geolocation data is returned to the defined JavaScript callback. When disabled the defined JavaScript error callback is called, notifying the app that the permission to using Geolocation is disabled.
                                                                              + +**Configuration Identifier**: Not Configurable
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##GUI +###BatteryRefresh +Specifies the refresh rate of the battery display. See the [Battery API](/api/battery) for more information. **Not applicable to the Enterprise Tablet**. [More info](#_batteryRefresh).
                                                                              + +**Configuration Identifier**: BATTERYREFRESH
                                                                              +**Possible Values**: Refresh rate in milliseconds
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###HourglassEnabled +Controls whether the [RhoElements Hourglass](/v/2.2/rhoelements/hourglass) icon will be displayed while navigating between pages (enabled by default) + +**Configuration Identifier**: HOURGLASSENABLED
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###HourglassLeft +Controls the horizontal position of the [RhoElements Hourglass](/v/2.2/rhoelements/hourglass) icon, which is displayed by default while navigating between pages. If not specified, the hourglass will appear at the center of the screen.
                                                                              + +**Configuration Identifier**: HOURGLASSLEFT
                                                                              +**Possible Values**: Horizontal position, in pixels
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###HourglassTop +Controls the vertical position of the [RhoElements Hourglass](/v/2.2/rhoelements/hourglass) icon, which is displayed by default while navigating between pages. If not specified, the hourglass will appear at the center of the screen.
                                                                              + +**Configuration Identifier**: HOURGLASSTOP
                                                                              +**Possible Values**: Vertical position, in pixels
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###SignalRefresh +Specifies the refresh rate of the signal display. See the [Signal API](/api/signalindicators) for more information.
                                                                              + +**Configuration Identifier**: SIGNALREFRESH
                                                                              +**Possible Values**: Refresh rate in milliseconds
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##HTMLStyles +###CaretWidth +**Applies only to Webkit on Windows Mobile or Windows CE**. + +Specifies the width (in pixels) of the textbox / text-area caret. If unspecified, defaults to '1'.
                                                                              + +**Configuration Identifier**: CARETWIDTH
                                                                              +**Possible Values**: Integer values from 1 to 5
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###FontDirectory +Specifies the font directory containing truetype fonts. The default font directory for all Zebra WM/CE devices is `\Windows`. **Not applicable to the Enterprise Tablet**. + +**Configuration Identifier**: FONTDIRECTORY
                                                                              +**Possible Values**: \Windows
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###FontFamily +Specifies the default font when rendering text in web pages. The specified font should be a TrueType font present on the device. On Windows, the default font has been set to 'Tahoma', which is present on all Zebra WM/CE devices. On the Enterprise Tablet the default is font Droid Sans Fallback. + +* Tahoma has no italic or oblique variants +* On WM/CE, specified font must be stored in `\Windows` +* On Enterprise Tablet, specified font must be stored in `/system/fonts` + +**Configuration Identifier**: FONTFAMILY
                                                                              +**Possible Values**: Font name
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###UseNativeFonts +**Applies to Windows Mobile and Windows CE only**. + +Controls which fonts will be used. When set to '0' (default) the FreeType library will be used as on apps built with RMS 2.x. When set to '1' the native font engine on the device is used. **A setting of '1' overrides the 'FontFamily' setting**. + +* On localized devices from 4.1 and higher, the native font engine will be used by default. +* The FreeType library cannot render localized characters such as Asian and some accented European characters. +* Some early BSPs of CE7 do not support the native font render. +* The log file displays the font engine in use on launch. + +NOTE: This configuration element is currently unavailable on MC92, VC70 or WT41N0 devices.
                                                                              + +**Configuration Identifier**: USENATIVEFONTS
                                                                              +**Possible Values**: 0 - Use FontFamily Setting, 1 - Use FreeType font library
                                                                              +**Platforms**: ###FunctionKeysCapturable +**Applies to Windows Mobile and Windows CE only; disabled by default**. + +Determines behavior of Function keys on Windows Mobile and Windows CE devices. When enabled, F-keys on WM/CE devices are capturable using the [Key Capture API](/api/keycapture). When disabled, keys revert to the device's default behavior. **This setting is not specific to an application. When enabled, settings are applied globally to the device**. + +**Configuration Identifier**: FUNCTIONKEYSCAPTURABLE
                                                                              +**Possible Values**: 0 - 'F keys' not capturable, 1 - 'F keys' capturable
                                                                              +**Platforms**: Windows Mobile/CE
                                                                              +
                                                                              + +##HTTP_Proxy +###HTTP_Proxy +**Applies only to the Zebra WebKit engine.** + +Specifies the URL and port number for the HTTP Proxy. For Internet Explorer, proxy settings are picked up from the Windows connection manager. Leave this field blank if no proxy is to be used.
                                                                              + +**Configuration Identifier**: HTTPPROXY
                                                                              +**Possible Values**: URL:PortNo
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###HTTPS_Proxy +**Applies only to the Zebra WebKit engine.** + +Specifies the HTTPS Proxy settings. For Internet Explorer, proxy settings are picked up from the Windows connection manager. Leave this field blank if no proxy is to be used.
                                                                              + +**Configuration Identifier**: N/A
                                                                              +**Possible Values**: URL:PortNo
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###No_Proxy +**Applies only to the Zebra WebKit engine.** + +Used to specify sites to be accessed directly rather than through a proxy. Accepts a comma-separated list of host names, domain names (beginning with a dot), IP addresses, or CIDR-format IP network addresses. Examples: myhost, .mydomain.com, 192.168.1.1 and 192.168.0.0/24.
                                                                              + +**Configuration Identifier**: NOPROXY
                                                                              +**Possible Values**: Comma-separated list of direct-access addresses
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##Logger +###LogError +Controls logging of error messages generated by RhoElements. If set to 1, it enables error-level logging only (can be overridden by LogWarning).
                                                                              + +**Configuration Identifier**: LOGERROR
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###LogInfo +Controls the logging of all information messages generated by RhoElements. If set to 1, **enables Info, Warning and Error** logging (Overrides LogWarning and/or LogError settings; can be overridden by LogUser).
                                                                              + +**Configuration Identifier**: LOGINFO
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###LogMaxSize +Specifies the maximum allowable size of the log file, after which no more logs will be saved.
                                                                              + +**Configuration Identifier**: +LOGMAXSIZE
                                                                              +**Possible Values**: +File size in kilobytes
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###LogMemory +Controls the logging of memory usage in the system. **Not applicable to the Enterprise Tablet.
                                                                              + +**Configuration Identifier**: +LOGMEMORY
                                                                              +**Possible Values**: +0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: +Android, iOS, WM/CE
                                                                              + +###LogMemPeriod +Specifies the time interval after which memory logs will be generated. **Not applicable to the Enterprise Tablet**. + +**Configuration Identifier**: +LOGMEMPERIOD
                                                                              +**Possible Values**: +Time in milliseconds
                                                                              +**Platforms**: +Android, iOS, WM/CE
                                                                              + +###LogPort +Sets the port over which logging data will be sent (ignored for file protocol).
                                                                              +**Configuration Identifier**: +LOGPORT
                                                                              +**Possible Values**: +Any valid HTTP port
                                                                              +**Platforms**: +Android, iOS, WM/CE
                                                                              + +###LogProtocol +Sets the protocol over which the logging data will be sent.
                                                                              + +**Configuration Identifier**: +LOGPROTOCOL
                                                                              +**Possible Values**: +"File" or "HTTP"
                                                                              +**Platforms**: +Android, iOS, WM/CE
                                                                              + +###LogURI +Specifies the URL or file name and path to which logged data should be sent.
                                                                              + +**Configuration Identifier**: +LOGURI
                                                                              +**Possible Values**: +Any valid URL or fully qualified file name
                                                                              +**Platforms**: +Android, iOS, WM/CE
                                                                              + +###LogUser +Controls logging of User, Info, Warning and Error messages from the user application. **Overrides LogWarning, LogError and/or LogInfo settings**. Data can be logged using the Log API.
                                                                              + +**Configuration Identifier**: +LOGUSER
                                                                              +**Possible Values**: +0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: +Android, iOS, WM/CE
                                                                              + +###LogWarning +Controls logging of warning messages generated by RhoElements. If set to 1, **enables warning *and* error messages** (overrides LogError setting; can be overridden by LogInfo).
                                                                              + +**Configuration Identifier**: LOGWARNING
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##Navigation +###AcceptLanguage +Specifies the Accept-Language HTTP header that will be sent from the client. For details, see the [RFQ documentation](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
                                                                              + +**Configuration Identifier**: ACCEPTLANGUAGE
                                                                              +**Possible Values**: Comma-separated lists of languages and quality values. The two lists are separated by a semicolon
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###BadLinkURI +Specifies the 'badlink' URI file to be displayed when one of the following occurs:
                                                                              + +* **An error occurs when attempting to navigate to a page** (i.e. no network connection) +* **A page times out** (timeout interval is set in NavTimeout) +* **The user presses the stop button** + +The browser will automatically append the querystring value "badlink" containing the URL of the page that could not be reached and "stop=true" if the page was loaded because the user pressed the stop button. The page specified in the badlink setting should be an offline file using the `file://` protocol so it's accessible by the browser.
                                                                              + +**Configuration Identifier**: BADLINKURI
                                                                              +**Possible Values**: Fully qualified local path to badlink URI file (case sensitive)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Cache +The browser cache size, in whole MBs. **Applies to RhoMobile Suite version 2.2 and higher**.
                                                                              + +**Configuration Identifier**: NAVIGATIONCACHE
                                                                              +**Possible Values**: Whole MBs, eg. 5M
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###CaFile +**Applies to Android and Windows Mobile/CE only. Not supported on iOS**. + +Specifies the location of a file of CA certificates in PEM format. [See openSSL](http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html) for more information.
                                                                              + +**Configuration Identifier**: CAFILE
                                                                              +**Possible Values**: Fully qualified local path (case sensitive)
                                                                              +**Platforms**: Android, WM/CE
                                                                              + +###ClientSSLCertificate +Specifies location of the '.p12' formatted certificate file used for client SSL authentication. This setting is used in any [Network API](/api/Network) call that sets up a secured SSL connection requiring client authentication, including get, post, downloadFile and uploadFile. This setting takes effect only if `verifyPeerCertificate` is enabled. If `verifyPeerCertificate` is set to fail and remote server requests the client certificate, connection will fail.
                                                                              + +**Configuration Identifier**: CLIENTSSLCERTIFICATE
                                                                              +**Possible Values**: Fully qualified local path. (case sensitive)
                                                                              +**Platforms**: Android
                                                                              + +###ClientSSLCertificatePassword +Specifies the password used with a client certificate. This setting takes effect only if `verifyPeerCertificate` is enabled. If `verifyPeerCertificate` is set to fail and remote server requests the client certificate, connection will fail.
                                                                              + +**Configuration Identifier**: CLIENTSSLCERTIFICATEPASSWORD
                                                                              +**Possible Values**: Password
                                                                              +**Platforms**: Android
                                                                              + +###DisableTLS +Controls whether to request SSLv3 connections instead of TLS. By default, all requests will be sent using TLS. If TLS is not supported, then SSLv3 will be used. The protocol used in both directions for the entire session is determined by the first interaction the client has with the server. To eliminate the possibility of using TLS, set DisableTLS to '1' (true).
                                                                              + +**Configuration Identifier**: DISABLETLS
                                                                              +**Possible Values**: 0 - TLS Not Disabled, 1 - TLS Disabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###EnableSSL3 +When enabled, SSL 3.0 is used. The Zebra Webkit is shipped with SSL3 disabled by default to protect against
                                                                              the POODLE attack vulnerability.
                                                                              + +**Configuration Identifier**: ENABLESSL3
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Keepalive +Controls whether HTTP connections will be maintained between requests. **Enabled by default** or is unspecified. When disabled, a connection is closed when its request is complete. Applies to release 5.0 and greater.
                                                                              + +**Configuration Identifier**: KEEPALIVE
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###NavTimeout +Defines the amount of time (in milliseconds) the application should wait *to establish communication with the relevant server* (as opposed to waiting for a page to fully load) before displaying the 'bad link' message. If the destination is unreachable, the bad link message might be displayed before the timeout is reached. The navigation timeout will not be invoked when navigating to an application's start page. The recommended best practice is to store the first page locally to avoid connectivity issues at startup. The app can then redirect to an online page if desired.
                                                                              + +**Configuration Identifier**: NAVTIMEOUT
                                                                              +**Possible Values**: Timeout in Milliseconds (max, value=45000)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###NetworkCookieDatabase +Specifies the location of the database to hold persistent cookies, if desired. If the specified file does not exist, one will be created. Persistent cookies will be loaded from this file and saved back to it when RhoElements exits. If the file is read-only, it will not be overwritten. If not specified, cookies will not persist.
                                                                              + +**Configuration Identifier**: NETWORKCOOKIEDATABASE
                                                                              +**Possible Values**: Fully qualified local path (case sensitive)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###ViewportEnabled +Controls viewport meta tag processing (enabled by default).
                                                                              + +**Configuration Identifier**: VIEWPORTENABLED
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###ViewportWidth +Sets the default viewport width for pages that do not have a viewport meta tag. If not specified, uses 1:1 scaling.
                                                                              + +**Configuration Identifier**: VIEWPORTWIDTH
                                                                              +**Possible Values**: Number
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###VerifyPeerCertificate +Controls whether server certificates will be verified against the internal certificates. **Enabled by default**. Useful for debugging, a value of 0 (disabled) is equivalent to automatically clicking 'OK' on a web browser's dialog when requesting approval for an untrusted certificate. + +NOTE: It is strongly recommended that this feature be enabled for deployment.
                                                                              + +**Configuration Identifier**: VERIFYPEERCERTIFICATE
                                                                              +**Possible Values**: 0 - disabled (do not verify peer certificates), 1 - enabled (verify peer certificates)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###UserAgent +Stores information about the device's operating environment. Can be used to spoof the device to a web server, for example to view content designed for the desktop on the mobile screen. When visiting a web server, the WebKit browser will report its User-Agent header as the value specified. Use the following substitution variables:
                                                                              + +* %p - Platform name ("Windows CE " + version number) +* %w - WebKit version number +* %e - Zebra WebKit version number + +In RhoElements 2.1 and higher, the default value was changed to work out of the box with a greater number of server configurations. Prior to RhoElements 2.1 the default user agent was "Mozilla/5.0, AppleWebKit (KHTML, i.e. Gecko), MotorolaWebKit, Safari."
                                                                              + +**Configuration Identifier**: USERAGENT
                                                                              +**Possible Values**: String
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##NPAPI +###NPAPIDirectory +Not applicable to the Enterprise Tablet:
                                                                              Path to an existing directory containing the NPAPI Plugins.
                                                                              + +**Configuration Identifier**: NPAPIDIRECTORY
                                                                              +**Possible Values**: Fully qualified local path (case sensitive)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Preloads\\PreloadLegacyActiveX +**Applies to Windows Mobile / CE with the Zebra Webkit only.**. + +Determines whether to preload the ActiveX object in WebKit. Use this for backward compatibility with code written in PocketBrowser that used the ActiveXObject.
                                                                              + +**Configuration Identifier**: PRELOADLEGACYACTIVEX
                                                                              +**Possible Values**: 0 - Do Not Preload, 1 - Preload
                                                                              +**Platforms**: WM/CE Webkit
                                                                              + +###Preloads\\PreloadLegacyAirBeam +Determines whether to preload the NPAPI plugin to mimic the AirBeam ActiveX object in WebKit. **Not applicable to the Enterprise Tablet**. + +**Configuration Identifier**: PRELOADLEGACYAIRBEAM
                                                                              +**Possible Values**: 0 - Do Not Preload, 1 - Preload
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Preloads\\PreloadLegacyAPD +Determines whether to preload the NPAPI plugin to mimic the APD ActiveX object in WebKit.
                                                                              + +**Configuration Identifier**: PRELOADLEGACYAPD
                                                                              +**Possible Values**: 0 - Do Not Preload, 1 - Preload
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Preloads\\PreloadLegacyGeneric +Determines whether to preload the NPAPI plug-in to mimic the Generic ActiveX object in WebKit. On the Enterprise Tablet this plugin is automatically loaded when the JSObjects plugin is preloaded.
                                                                              + +**Configuration Identifier**: PRELOADLEGACYGENERIC
                                                                              +**Possible Values**: 0 - Do Not Preload, 1 - Preload
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Preloads\\PreloadLegacyODAX +**Does not apply to the Enterprise Tablet.** + +Determines whether to preload the NPAPI plugin to mimic the ODAX ActiveX object in WebKit.
                                                                              + +**Configuration Identifier**: PRELOADLEGACYODAX
                                                                              +**Possible Values**: 0 - Do Not Preload, 1 - Preload
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Preloads\\PreloadLegacyNoSIP +Determines whether to preload the NPAPI plug-in to mimic the NoSIP ActiveX object in WebKit.
                                                                              + +**Configuration Identifier**: PRELOADLEGACYNOSIP
                                                                              +**Possible Values**: 0 - Do Not Preload, 1 - Preload
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + + +###Preloads\\PreloadJSObjects +Determines whether to preload the NPAPI plugin to provide native JavaScript objects for each of the modules
                                                                              + +**Configuration Identifier**: PRELOADLEGACYJSOBJECTS
                                                                              +**Possible Values**: 0 - Do Not Preload, 1 - Preload
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##Preloads +###Preload +Defines plug-ins to be pre-loaded with RhoElements rather than loading as needed by a program function. Pre-loading prevents application lag when a program function is called for the first time. For example, when `Barcode.enable` is called by an app, a slight lag will be seen as the `Barcode` DLL loads into memory. Specify a Preload tag for each module to be loaded when RhoElements starts up. + +* While multiple modules may be defined in the same DLL, **list all pre-loaded modules for maximum benefit**. + +* For memory-constrained devices, **pre-load all required modules to prevent an out-of-memory condition during execution**. + +* **Plug-ins are integral to RhoElements on the Enterprise Tablet**, and therefore do not apply. + +**Configuration Identifier**: PRELOAD
                                                                              +**Possible Values**: 0 - Do Not Preload, 1 - Preload
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##Scanner +###DisableScannerDuringNavigation +**Applies to RhoMobile 2.2 and higher**. + +Controls whether scanner will be automatically disabled when navigating away from a page on which it was enabled. Override this default behavior by setting this option to '0'. Once enabled (either through meta tags, JavaScript or Ruby), the scanner will remain enabled in the foreground application until manually disabled.
                                                                              + +**Configuration Identifier**: DISABLESCANNERDURINGNAV
                                                                              +**Possible Values**: 0 - Scanner remains enabled during page navigation, 1 - Scanner disabled during page navigation
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##Screen +###FullScreen +Forces RhoElements to display in full screen mode, hiding the OS from the user unless specifically minimized using the [Application API](../api/Application#minimize). For Windows Mobile devices that include a custom Zebra user interface, access is provided to the status bar at the top of the screen.
                                                                              + +**Configuration Identifier**: +FULLSCREEN
                                                                              +**Possible Values**: +0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: +Android, iOS, WM/CE
                                                                              + +###PageZoom +Sets the zoom factor of the page. Default zoom value is 1.0 (if unspecified). On Android, zero and negative values are not supported. On Windows, zoom value less than 1.0 reverts to 1.0 since lower values would not be readable. [More info](#_pageZoom)
                                                                              + +**Configuration Identifier**: +PAGEZOOM
                                                                              +**Possible Values**: +Zoom factor of the page
                                                                              +**Platforms**: +Android, iOS, WM/CE
                                                                              + +###ShowLicenseConfirmation +Controls the display of the "licensed to..." dialog at launch (on licensed devices only). Has no effect on unlicensed devices.
                                                                              + +**Configuration Identifier**: +SHOWLICENSECONFIRMATION
                                                                              +**Possible Values**: +0 - Do not show license confirmation, 1 - Show license confirmation
                                                                              +**Platforms**: WM/CE
                                                                              + + +##ScreenOrientation +###AutoRotate +Acts as a rotation lock. When AutoRotate is disabled, screen will remain in a fixed position regardless of device orientation. When enabled, screen will automatically adjust orientation as the device is rotated.
                                                                              + +**Configuration Identifier**: AUTOROTATE
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + + +##Scrolling +###ScrollTechnique +Specifies the technique used to scroll the viewport:
                                                                              + +* **FingerScroll:** Permits scrolling around a page with finger swiping
                                                                              +* **Scrollbars:** Scrollbars will be presented when the page is too large to fit the viewport
                                                                              +* **None:** No scrollbars will be displayed and the page will not respond to finger swipes
                                                                              + +NOTE: FingerScroll may interfere with drawing on a Canvas element.
                                                                              + +**Configuration Identifier**: SCROLLTECHNIQUE
                                                                              +**Possible Values**: FingerScroll, Scrollbars, None
                                                                              +**Platforms**: iOS, WM/CE
                                                                              + +##SIP +###EnableSIP +**Applies to Android only**. + +Controls whether soft input panel (on-screen keyboard) will appear. On Windows Mobile/CE, this feature can be mimicked by manipulating the top and left position parameters of the SIP module to position the SIP off the screen, thereby 'disabling' its use.
                                                                              + +**Configuration Identifier**: Not Configurable
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android
                                                                              + +###ResizeOnSIP +**Applies to Windows Mobile only. Requires SIP module preload**. + +Controls window resizing when the soft input panel (on-screen keyboard) is displayed. When enabled, the browser window will resize to accommodate the SIP, when displayed. If the SIP has been moved to the top half of the screen, the browser window will reduce in size from the top. + +* Not compatible with Windows CE +* Not compatible with Finger Scrolling +* The SIP always appears at the bottom of the screen + +**Configuration Identifier**: RESIZEONSIP
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Windows Mobile
                                                                              + +##Sound +###DecodeDuration +Controls the duration of the device beeper sound when a barcode is scanned.
                                                                              + +**Configuration Identifier**: DECODEDURATION
                                                                              +**Possible Values**: Milliseconds
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###DecodeFrequency +Controls the frequency of the device beeper sound when a barcode is successfully decoded. This value (in hex) must be a frequency within the range of the device beeper.
                                                                              + +**Configuration Identifier**: DECODEFREQUENCY
                                                                              +**Possible Values**: 0 to 0xFFFF
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###DecodeVolume +Controls the volume of the device beeper when a barcode is scanned.
                                                                              + +**Configuration Identifier**: DECODEVOLUME
                                                                              +**Possible Values**: 0 - off, 1 - 5 (lowest to loudest)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###ImagerCaptureWav +Specifies a .wav file to be played when the Imager captures an image.
                                                                              + +**Configuration Identifier**: IMAGERCAPTUREWAV
                                                                              +**Possible Values**: Fully qualified local path to .wav file (case sensitive)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + + +###InvalidDecodeFrequency +Controls the frequency of the device beeper sound when a barcode is scanned but not successfully decoded. This value (in hex) must be a frequency within the range of the device beeper. **Not applicable to the Enterprise Tablet**.
                                                                              + +**Configuration Identifier**: INVALIDDECODEFREQUENCY
                                                                              +**Possible Values**: 0 to 0xFFFF
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###ScanDecodeWav +Specifies a .wav file to be played when the scanner successfully decodes a barcode. **Overrides all scanner beeper settings**.
                                                                              + +**Configuration Identifier**: SCANDECODEWAV
                                                                              +**Possible Values**: Fully qualified local path to .wav file (case sensitive)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###ScanInvalidWav +Specifies a .wav file to be played when a barcode is scanned but not successfully decoded. This setting overrides the scanner beeper. **Overrides all scanner beeper settings. Not applicable to the Enterprise Tablet**.
                                                                              + +**Configuration Identifier**: SCANINVALIDWAV
                                                                              +**Possible Values**: Fully qualified local path to .wav file (case sensitive)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + + +##System +###LowBatteryScan +**Applies to Windows Mobile and Windows CE only**. + +Controls whether the scanner can be used when battery charge level is low. Set to '0' to disable scanning with low battery and '1' to enable. **Can be overridden by calling `Barcode.enable`**.
                                                                              + +**Configuration Identifier**: LOWBATTERYSCAN
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Windows Mobile/CE
                                                                              + +##TabInstance +###NewTabPhysicalMemLimit +Controls whether a new Tab will be created using the [NativeTabbar.create API](../api/NativeTabbar#mcreate) when physical memory percentage hits a specific threshold. For example, if set to 80, no new tabs will be created once the physical memory usage on the device reaches 80 percent or more. Once the defined limit is reached, the NativeTabbar.create API callback will contain `tabEvent` = `onTabNewError`. + +**Configuration Identifier**: NEWTABPHYSICALMEMLIMIT
                                                                              +**Possible Values**: 0-100 (100 = no limit)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###NewTabVirtualMemLimit +Controls whether a new Tab will be created using the [NativeTabbar.create API](../api/NativeTabbar#mcreate) when a virtual memory usage percentage is hit. For example, if set to 80, no new tabs will be created once the device virtual memory usage reaches 80 percent or more. Once the defined limit is reached, the NativeTabbar.create API callback will contain `tabEvent` = `onTabNewError`. + +**Configuration Identifier**: NEWTABVIRTUALMEMLIMIT
                                                                              +**Possible Values**: 0-100 (100 = no limit)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##UserData +Used to persist data when using Read/WriteUserSetting.
                                                                              + +**Configuration Identifier**: N/A
                                                                              +**Possible Values**: Any valid user setting
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##VoidConnection +###HostURL +Used to specify the URL to which your application will connect. Supports IP addresses, host names and specific ports (when appended to URL with a colon. If no port is specified, default=80).
                                                                              + +**Configuration Identifier**: HostURL
                                                                              +**Possible Values**: Fully qualified host name or IP address, with or without port number
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Message +Use to specify a custom message to be displayed in a pop-up window.
                                                                              + +**Configuration Identifier**: Message
                                                                              +**Possible Values**: Alpha-numeric text
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###PollInterval +Defines the amount of time (in milliseconds) the application should pause before subsequently checking for a connection to the URL specified in 'HostURL.' The minimum value is 5000; lower values will revert to 5000. The value in 'Timeout' should be a multiple of this number.
                                                                              + +NOTE: This parameter is not testable. + +**Configuration Identifier**: PollInterval
                                                                              +**Possible Values**: PollInterval
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Timeout +Defines the amount of time (in milliseconds) the application should wait for a connection to the URL specified in 'HostURL' before displaying the 'bad link' message. The minimum value is 30000; lower values will revert to 30000. Value should be a multiple of the value set in PollInterval.
                                                                              + +**Configuration Identifier**: Timeout
                                                                              +**Possible Values**: Whole number greater than 30000 (ms)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###TrackConnection +Controls connection tracking. When enabled, will display an alert whenever a connection with the URL defined in "HostURL" element is lost, removed when connection is restored, and changed to 'bad link' message if timeout is reached. Alert is modal on Android, and prevents any UI actions while displayed. Although alert is non-modal on Windows, interaction with the background app is not recommended while alert is being displayed.
                                                                              + +**Configuration Identifier**: TrackConnection
                                                                              +**Possible Values**: 0 - disabled, 1- enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###PollInterval +Defines the amount of time (in milliseconds) the application should pause before subsequently checking for a connection to the URL specified in 'HostURL.' The minimum value is 5000; lower values will revert to 5000. The value in 'Timeout' should be a multiple of this number.
                                                                              + +NOTE: This parameter is not testable. + +**Configuration Identifier**: PollInterval
                                                                              +**Possible Values**: PollInterval
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +##WebDB +###WebStorageDBPath +Sets the path to an existing directory for storage of web storage databases.
                                                                              + +**Configuration Identifier**: WEBSTORAGEDBPATH
                                                                              +**Possible Values**: Fully qualified local path (case sensitive)
                                                                              +**Platforms**: Windows Mobile / CE Webkit
                                                                              + +###WebSQLDBQuota +Sets the maximum per-database quota for Web SQL databases.
                                                                              + +**Configuration Identifier**: WEBSQLDBQUOTA
                                                                              +**Possible Values**: Size in bytes
                                                                              +**Platforms**: WM/CE Webkit
                                                                              + +###WebSQLDBPath +Path to an existing directory to store Web SQL databases
                                                                              + +**Configuration Identifier**: WEBSQLDBPATH
                                                                              +**Possible Values**: Fully qualified local path (case sensitive)
                                                                              +**Platforms**: WM/CE Webkit
                                                                              + +##WebServer +###Enabled +Determines whether a web server will be running locally on the device to service the application. When multiple Webview applications are deployed, all can run from a single embedded server or use discrete servers, each running on a different port.
                                                                              + +**Configuration Identifier**: WEBSENABLED
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Port +Specifies the port number of the web server running locally on the device (default= 8080)
                                                                              + +**Configuration Identifier**: WEBSPORT
                                                                              +**Possible Values**: 8080
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Public +Controls access to the local web server from an external device. Generally used only for debugging. + +NOTE: Enabling this feature in a production deployment is a potential security risk.
                                                                              It is highly recommended that this feature be disabled before deployment.
                                                                              + +**Configuration Identifier**: WEBSPUBLIC
                                                                              +**Possible Values**: 0 - Disabled, 1 - Enabled
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###WebFolder +Specifies the folder on the device in which the web application and its initial page are stored. By default, the initial page is 'index.html' unless another page is requested.
                                                                              + +**Configuration Identifier**: WEBFOLDER
                                                                              +**Possible Values**: Fully qualified path to folder containing web application (case sensitive)
                                                                              +**Platforms**: Android, iOS, WM/CE
                                                                              + +###Vulnerability Alert + +>A vulnerability has been discovered that affects applications using SSL3, which is part of the Zebra Webkit (Ekioh 3.1.1). **This applies only to apps for Windows Mobile and Windows CE built with RMS 5.1 or higher**. Known as POODLE (Padded Oracle On Downgraded Legacy Encryption), the vulnerability [as described by the U.S. Comuputer Emergency Readiness Team](https://www.us-cert.gov/ncas/alerts/TA14-290A) would allow an attacker to exploit the means by which SSL 3.0 handles block cipher mode padding to decrypt and **extract information from inside an encrypted transaction**.

                                                                              To protect against this, **Zebra now ships the Zebra Webkit with SSL3 disabled by default**.

                                                                              + +## Programming Notes +### Case Sensitivity +The operating systems of some devices have case sensitive file systems. Therefore it is good practice to always keep URL values in the Config.xml file case identical to the names of the actual files. + +### *Page Zoom Configuration +Sometimes, while navigating from any page to any other page, the actual page zoom setting reflects after few milli seconds delay. This doesn't happens everytime. + +Setting page zoom property on page load event does not reflect the set value for the Application start page for the first time. Users are advised to set the page zoom property with a minimum of 1 second delay on page load. + +Setting page zoom property on page load will reflect only for that page. + +### *Battery Polling on the Enterprise Tablet +On the Enterprise Tablet the battery notification is asynchronous. For this reason, BatteryRefresh is not supported on the Enterprise Tablet. The effect of this is that a batteryEvent is fired only when the battery level changes. This has been done to save battery power compared to polling. + +### Interaction between FunctionKeysCapturable and EnableFunctionKey configuration settings +On Windows Mobile and Windows CE devices full control is given to the developer over how their application handles function keys. Because of the limitations of the operating system any settings applied will persist until the device is next warm booted. Which function keys have default operating system behavior will vary from device to device, e.g. on the MC75a F3 and F4 represent the red and green phone keys and on many devices the volume keys are also mapped as Function keys. Not all function keys will have default operating system behavior. + +Unblocking function keys may expose the underlying operating system, particularly the red and green phone keys will give access to the start menu and programs. + +The table below shows the behavior of RhoElements when Function Keys are pressed given the possible configuration settings: + + + + + + + + + + + + + + + + + + + +
                                                                              Function Keys Capturable = TRUEFunction Keys Capturable = FALSE
                                                                              Enable Function Key = TRUE +
                                                                                +
                                                                              • All Function Keys can be captured by the Key Capture Module +
                                                                              • Function Key will not have its default Operating system behavior +
                                                                              +
                                                                              +
                                                                                +
                                                                              • Function Keys with default OS behavior can not be captured by the Key Capture Module +
                                                                              • Function Keys without default OS behavior can be captured by the Key Capture Module +
                                                                              • Function Key will have its default Operating system behavior (if any) +
                                                                              +
                                                                              Enable Function Key = FALSE +
                                                                                +
                                                                              • All Function Keys can be captured by the Key Capture Module +
                                                                              • Function Key will not have its default Operating system behavior +
                                                                              +
                                                                              +
                                                                                +
                                                                              • All Function Keys can not be captured by the Key Capture Module +
                                                                              • Function Key will not have its default Operating system behavior (if any)
                                                                              • +
                                                                              +
                                                                              + +### HTTP Authentication Limitations +On Windows Mobile/CE with the Zebra Webkit, only "Basic" and "Digest" forms of the Authenticate header are supported. Therefore, usernames and passwords are passed over the network as clear text on those platforms. Keep this in mind when considering app security. For more information, please refer to the IETF article on [HTTP Authentication: Basic and Digest Access Authentication](https://www.ietf.org/rfc/rfc2617.txt). diff --git a/docs/en/5.5/guide/screen_orientation.md b/docs/en/5.5/guide/screen_orientation.md new file mode 100644 index 00000000..70d011f7 --- /dev/null +++ b/docs/en/5.5/guide/screen_orientation.md @@ -0,0 +1,226 @@ +# Screen Orientation + +You can use the `ScreenOrientation` module to control the screen orientation and to set a callback to receive orientation change events. + +## Prerequisite + +Before you can make use of the `ScreenOrientation` API, you need to include the `screenorientation` extension in your `build.yml` + + :::yaml + extensions: ["screenorientation"] + +## Get current screen orientation + +You can get the current orientation of the device by using the `System.screenOrientation` property. + +Ruby syntax: + :::ruby + screen_orientation = Rho::System.screenOrientation + if screen_orientation == "portrait" + # do something specific to portrait mode + elsif screen_orientation == "landscape" + # do something specific to landscape mode + end + +JavaScript syntax: + :::javascript + var screen_orientation = Rho.System.screenOrientation; + if (screen_orientation === "portrait") { + // do something specific to portrait mode + } else if (screen_orientation === "landscape") { + // do something specific to landscape mode + } + +## Control screen orientation + +### Locking the orientation + +In some applications, it may be necessary to force the display to always be locked to an orientation. You can do this by setting the `disable_screen_rotation` in `rhoconfig.txt` + + :::ruby + #disable screen rotation (enabled by default) + disable_screen_rotation = 1 + +### Enable / disable auto-rotation + +You can enable or disable the autorotation of the display when the device is rotated by setting the `autoRotate` property + +Ruby syntax: + :::ruby + # enable auto-rotate + Rho::ScreenOrientation.autoRotate = true + + # disable auto-rotate + Rho::ScreenOrientation.autoRotate = false + +JavaScript syntax: + :::javascript + // enable auto-rotate + Rho.ScreenOrientation.autoRotate = true; + + // disable auto-rotate + Rho.ScreenOrientation.autoRotate = false; + +### Changing to default orientation + +Set the screen to the default orientation of the device using the `normal` method. + +Ruby syntax: + :::ruby + Rho::ScreenOrientation.normal + +JavaScript syntax: + :::javascript + Rho.ScreenOrientation.normal(); + +### Changing to right-handed orientation + +Set the screen to right-handed orientation using the `rightHanded` method. + +Ruby syntax: + :::ruby + Rho::ScreenOrientation.rightHanded + +JavaScript syntax: + :::javascript + Rho.ScreenOrientation.rightHanded(); + +### Changing to left-handed orientation + +Set the screen to left-handed orientation using the `leftHanded` method. + +Ruby syntax: + :::ruby + Rho::ScreenOrientation.leftHanded + +JavaScript syntax: + :::javascript + Rho.ScreenOrientation.leftHanded(); + +### Changing to upside-down orientation + +Set the screen to upside-down orientation using the `upsideDown` method. This can be useful, for example, when the user offers the device to a customer to obtain a signature. If you set the orientation to `upsideDown`, the application's user interface will be in the correct position from the customer's point of view, without them having to physically rotate the device. This streamlines the capture process, avoids cumbersome manual operations and reduces the risk of the device being dropped. + +Ruby syntax: + :::ruby + Rho::ScreenOrientation.upsideDown + +JavaScript syntax: + :::javascript + Rho.ScreenOrientation.upsideDown(); + +## Responding to screen orientation change + +When the device is rotated, it is sometimes necessary to update your application's UI layout to better suit the new orientation. There are two different approaches, depending on where the logic for change is placed: The first is to handle UI adaptations yourself (with code) and the second is to use responsive design. + +### Handling rotation in code + +If you want to respond to the device being rotated by running some code, there are two steps that must be completed. +The first is to set a callback in order to be notified of orientation change events and the second is to update the UI layout accordingly. + +Set the callback for screen orientation events by using the `setScreenOrientationEvent` method. + +Ruby syntax: + :::ruby + def set_callback + Rho::ScreenOrientation.setScreenOrientationEvent(url_for(:action => :screen_orientation_callback)) + end + + def unset_callback + Rho::ScreenOrientation.setScreenOrientationEvent(nil) + end + + def screen_orientation_callback + puts "Screen Rotated. New orientation: #{@params["result"]}" + end + +JavaScript syntax: + :::javascript + function set_callback() { + Rho.ScreenOrientation.setScreenOrientationEvent(screen_orientation_callback); + } + + function unset_callback() { + Rho.ScreenOrientation.setScreenOrientationEvent(null); + } + + function screen_orientation_callback(params) { + console.log("Screen Rotated. New orientation: "+params.result); + } + +### Updating the UI on screen orientation change + +You can make your application handle different screen orientations by creating two different screen layouts for portrait and landscape orientation. + +In your ERB files, You can write `if ... else` code in your layout using the `System.screenOrientation` property to change the layout of elements. + + :::ruby + <% if System.screenOrientation == 'portrait' %> + + <% else %> + + <% end %> + +While this method works, there is a better solution: responsive design. + +## Responsive design + +The easiest way to show different UI layouts to the user based on the orientation and even automatically adjust to various device sizes is by using [responsive design](http://en.wikipedia.org/wiki/Responsive_web_design). + +Using responsive design helps avoid creating entirely different versions of the same content for different orientations and sizes. This technique makes use of [CSS3 Media queries](http://en.wikipedia.org/wiki/Media_queries) to allow content to adapt to conditions such as screen size or aspect ratio. + +For example, you can make the layout on your UI show content stacked in portrait mode and side-by-side in landscape mode. + + :::html + + + + + + +
                                                                              Block 1
                                                                              +
                                                                              Block 2
                                                                              +
                                                                              Block 3
                                                                              + + + +Here is how the layout looks in portrait... + +![Portrait](http://rhodocs-images.s3.amazonaws.com/guide/screen_orientation/portrait_layout.png) + +...and here is how it adapts to landscape + +![Landscape](http://rhodocs-images.s3.amazonaws.com/guide/screen_orientation/landscape_layout.png) + +##### Responsive design frameworks + +There are some CSS frameworks available that are designed to make it easier to use responsive design in your applications. Two of the most popular are: + +* [Twitter Bootstrap](http://getbootstrap.com/) +* [Zurb Foundation](http://foundation.zurb.com/) + +Both are modern frameworks, designed to take advantage of the latest capabilities of today's mobile browsers. They provide a number of features to shorten your development time while simultaneously making your code more maintainable and future-proof. Particularly if you are developing for more than one screen size, using a responsive framework is highly recommended. + +## Related reading + +* The [CSS3 Media Queries specification](http://www.w3.org/TR/css3-mediaqueries/) is the formal specification for media queries. +* [ScreenOrientation API](../api/screenorientation) documentation +* [System API](../api/system) documentation + diff --git a/docs/en/5.5/guide/signature.md b/docs/en/5.5/guide/signature.md new file mode 100644 index 00000000..9a9b1598 --- /dev/null +++ b/docs/en/5.5/guide/signature.md @@ -0,0 +1,45 @@ +# Signature Capture + +The [Signature Capture API](../../2.2.0/rhodesapi/signaturecapture-api) allows your device to take a signature and save it as an image. + +Click [here for information about the SignatureCapture.take method](../../2.2.0/rhodesapi/signaturecapture-api#take). This method opens a window for hand writing, where the user draws his signature. Signature is saved to an image file. + +Example: + :::ruby + Rho::SignatureCapture.take(url_for( :action => :signature_callback), { :imageFormat => "jpg", :penColor => 0xff0000, :penWidth=>3, :bgColor => 0x00ff00 }) + +**NOTE: To take signature on Blackberry devices, press the Menu button, then select 'Capture'.** + +### Inline Signature Capture +**NOTE: As of Rhodes version 3.3.3, the Inline Signature API is removed from Rhodes. This feature is only supported in Zebra RhoMobile Suite. If you wish to use this feature, you will need to [upgrade to RhoMobile Suite](rhomobile-install). Your application's build.yml will also need to be modified to [indicate the application type is 'Rhoelements'](../../2.2.0/rhoelements/rhoelements2-native#enabling-motorola-device-capabilities). Additionally, a [RhoElements license](../../2.2.0/rhoelements/licensing) is required.** + +Windows Mobile and Windows CE devices support signature capture started in window, which you can show over the current page (scrolling is not supported in this case). + +Refer to the [Inline Signature API](../../2.2.0/rhodesapi/signaturecapture-api#inline-signature-api) for the inline signature capture methods. + +* [visible](../../2.2.0/rhodesapi/signaturecapture-api#visible) - Display a window for hand writing, where the user draws his signature. +* [capture](../../2.2.0/rhodesapi/signaturecapture-api#capture) - Save the signature to an image file and call a callback. +* [clear](../../2.2.0/rhodesapi/signaturecapture-api#clear) - Clear the signature in the window. + +Example of visible method: + + :::ruby + Rho::SignatureCapture.visible(true, { :imageFormat => "jpg", :penColor => 0xff0000, :penWidth=>3, :bgColor => 0x00ff00 }) + +To save Signature to an image file and call callback: + :::ruby + Rho::SignatureCapture.capture(callback_url) + +Example of capture method: + + :::ruby + Rho::SignatureCapture.capture(url_for( :action => :signature_callback)) + +Example of clear method: + + :::ruby + Rho::SignatureCapture.clear() + +### Sample +See controller and view in the /app/SignatureUtil folder of the [System API Samples application](http://github.com/rhomobile/rhodes-system-api-samples/tree/master/app/SignatureUtil/controller.rb) for more information. + diff --git a/docs/en/5.5/guide/synchronization.md b/docs/en/5.5/guide/synchronization.md new file mode 100644 index 00000000..ad8dad6e --- /dev/null +++ b/docs/en/5.5/guide/synchronization.md @@ -0,0 +1,461 @@ +# Synchronization with Rhodes +As we've shown in the [Rhom section](../../2.2.0/rhodes/rhom), adding synchronized data via RhoConnect to your Rhodes application is as simple as generating a model and enabling a `:sync` flag. This triggers the internal Rhodes sync system called the [**`RhoConnectClient`**](../api/RhoConnectClient) to synchronize data for the model and transparently handle bi-directional updates between the Rhodes application and the RhoConnect server. + +This section covers in detail how the RhoConnectClient works in Rhodes and how you can use its flexible APIs to build data-rich native applications. + +## Sync Workflow +The RhoConnectClient interacts with RhoConnect over http(s) using [JSON](http://www.json.org/) as a data exchange format. With the exception of [bulk sync](../rhoconnect/bulk-sync), pages of synchronized data, or "sync pages" as we will refer to them here, are sent as JSON from RhoConnect to the RhoConnectClient. + +Below is a simplified diagram of the RhoConnectClient workflow: + + + +This workflow consists of the following steps: + +* RhoConnectClient sends authentication request to RhoConnect via [`RhoConnectClient.login`](../api/RhoConnectClient#mlogin). RhoConnect calls [`Application.authenticate`](../rhoconnect/authentication) with supplied credentials and returns `true` or `false`. + +* If this is a new client (i.e. fresh install or reset), the RhoConnectClient will initialize with RhoConnect: + + * It requests a new unique id (client id) from RhoConnect. This id will be referenced throughout the sync process. + + * It will register platform information with RhoConnect. If this is a [push-enabled application](device-caps#push-notifications) application, the RhoConnectClient will send additional information like device push pin. + +* RhoConnectClient requests sync pages from RhoConnect, one model(or [Rhom](rhom) model) at a time. The order the models are synchronized is determined by the model's [`:sync_priority`](rhom#property-bag), or determined automatically by the RhoConnectClient. + +## Sync Authentication +When you generate a Rhodes application, you'll notice there is an included directory called `app/Settings`. This contains a default `settings_controller.rb` and some views to manage authentication with [RhoConnect](../rhoconnect/introduction). + +### `login` +In `settings_controller.rb#do_login`, the [`RhoConnectClient.login`](../api/RhoConnectClient#mlogin) method is called: + + :::ruby + RhoConnectClient.login( + @params['login'], + @params['password'], + url_for(:action => :login_callback) + ) + +Here login is called with the `login` and `password` provided by the `login.erb` form. A `:login_callback` action is declared to handle the asynchronous result of the [`RhoConnectClient.login`](../api/RhoConnectClient#mlogin) request. + +### `login_callback` +When [`RhoConnectClient.login`](../api/RhoConnectClient#mlogin) completes, the callback declared is executed and receives parameters including success or failure and error messages (if any). + + :::ruby + def login_callback + error_code = @params['error_code'].to_i + if error_code == 0 + # 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 + +This sample checks the login `error_code`, if it is `0`, perform a full sync and render the settings page. Otherwise, it sets up an error message and re-displays the login page with an error. + +## Notifications +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. One 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. Below are two flowcharts describing the notification process during sync along with details of each of the steps. Each part in the flow chart also has an associated section below the two charts for even more in-depth description. + +### Notifications Flow +The flow charts below shows the logic flow for notifications concerning model sync. Bulk sync and incremental sync are handled differently and therefore are illustrated in two separate flow charts. The details of each step are spelled out further down this page. + +
                                                                              +
                                                                              +

                                                                              Incremental Sync

                                                                              + +
                                                                              +
                                                                              +

                                                                              Bulk Sync

                                                                              + +
                                                                              +
                                                                              + +It is important to note that, for bulk sync, the value of `@params["status"]` will only ever be "in_progress", "error", or "complete". There is no step in the process that will return an `@params["status"]` of "ok" status. Instead, `@params["bulk_status"]` (described in detail below) can be accessed to get the status of the bulk sync job. This is done because of the asynchronous nature of the bulk sync process. + +### Set Notifications +To set a notification for a model, you can use the [setNotification](../api/RhoConnectClient#msetNotification) method using this syntax `RhoConnectClient.setNotification(STRING sourceName, CallBackHandler callback)`: + + :::ruby + RhoConnectClient.setNotification( + Account.get_source_name, + url_for(:action => :sync_notify), + "sync_complete=true" + ) + +Which is the same as: + + :::ruby + Account.setNotification( + url_for(:action => :sync_notify), + "sync_complete=true" + ) + +In this example, once the sync process for the `Account` model is complete, the view will be directed to the `Account.sync_notify()` action (with params 'sync_complete=true') if user is on the same page. The `Account.sync_notify()` action is scaffolded by default in Ruby, in JavaScript, the action must be implemented in order to use it. + +**NOTE: In these examples, after the sync is complete the notifications are removed.** + +You can also set a notification for all models: + + :::ruby + RhoConnectClient.setNotification( + "*", url_for(:action => :sync_notify), + "sync_complete=true" + ) + +**NOTE: This notification will not be removed automatically.** + +### Notification 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. + +* `@params["source_id"]` - The id of the current model that is synchronizing. +* `@params["source_name"]` - Name of the model (i.e. "Product") +* `@params["sync_type"]` - Type of sync used for this model: "incremental" or "bulk" +* `@params["status"]` - Status of the current sync process: "in_progress", "error", "ok", "complete", "schema-changed" + +#### "in_progress" - incremental sync +* `@params["total_count"]` - Total number of records that exist for this RhoConnect source. +* `@params["processed_count"]` - Number of records included in the sync page. +* `@params["cumulative_count"]` - Number of records the RhoConnectClient has processed so far for this source. + +#### "in_progress" - bulk sync +* `@params["bulk_status"]` - The state of the bulk sync process: + * "start": when bulk sync start and when specific partition is start syncing + * "download": when client start downloading database from server + * "change_db": when client start applying new database + * "blobs": when client start downloading remote blob files + * "ok": when sync of partition finished without error + * "complete": when bulk sync finished for all partitions without errors + +* `@params["partition"]` - Current bulk sync partition. + +#### "error" +* `@params["error_code"]` - HTTP response code of the RhoConnect server error: 401, 500, 404, etc. +* `@params["error_message"]` - Response body (if any) +* `@params["server_errors"]` - Hash of <model> objects of RhoConnect adapter error (if exists): "login-error", "query-error", "create-error", "update-error", "delete-error", "logoff-error". + * For **"login-error"**, **"query-error"**, **"logoff-error"**: + * <model> object is a hash containing a "message" from server - `@params["server_errors"]["query-error"]['message']` + * For **"create-error"**, **"update-error"**, **"delete-error"**: + * <model> object is hash each containing an "object" as a key (that failed to create) and a corresponding "message" and "attributes": + * `@params["server_errors"]["create-error"][object]['message']` + * `@params["server_errors"]["create-error"][object]['attributes']` + * These errors should be handled by their respective on_sync_*_error method in the [RhoConnectClient API](../api/RhoConnectClient) + +**NOTE: "create-error" has to be handled in sync callback. Otherwise sync will stop on this model. To fix create errors you should call [RhoConnectClient.on_sync_create_error](../api/RhoConnectClient#mon_sync_create_error)** + +#### "ok" +* `@params["total_count"]` - Total number of records that exist for this RhoConnect source. +* `@params["processed_count"]` - Number of records included in the last sync page. +* `@params["cumulative_count"]` - Number of records the RhoConnectClient has processed so far for this source. + +#### "complete" +This status returns only when the RhoConnectClient process is complete. + +#### "schema-changed" +This status returns for bulk-sync models that use [`FixedSchema`](rhom#fixed-schema) when the schema has changed in the RhoConnect server. + +**NOTE: In this scenario the sync callback should notify the user with a wait screen and start the bulk sync process.** + +## Server error processing on client +### create-error +has to be handled in sync callback. Otherwise sync will stop on this model. To fix create errors you should call Model.on_sync_create_error or RhoConnectClient.on_sync_create_error: + + :::ruby + RhoConnectClient.on_sync_create_error( src_name, objects, action ) + Model.on_sync_create_error( objects, action ) + + * objects - One or more error objects + * action - May be :delete or :recreate. :delete just remove object from client, :recreate will push this object to server again at next sync. + +### update-error +If not handled, local modifications, which were failing on server, will never sync to server again. +So sync will work fine, but nobody will know about these changes. + + :::ruby + RhoConnectClient.on_sync_update_error( src_name, objects, action, rollback_objects = nil ) + Model.on_sync_update_error( objects, action, rollback_objects = nil) + + * objects - One or more error objects + * action - May be :retry or :rollback. :retry will push update object operation to server again at next sync, :rollback will write rollback_objects to client database. + * rollback_objects - contains objects attributes before failed update and sends by server. should be specified for :rollback action. + +### delete-error +If not handled, local modifications, which were failing on server, will never sync to server again. +So sync will work fine, but nobody will know about these changes. + + :::ruby + RhoConnectClient.on_sync_delete_error( src_name, objects, action ) + Model.on_sync_delete_error( objects, action ) + + * objects - One or more error objects + * action - May be :retry - will push delete object operation to server again at next sync. + +For example: + :::ruby + RhoConnectClient.on_sync_create_error( @params['source_name'], + @params['server_errors']['create-error'], :delete) + + RhoConnectClient.on_sync_update_error( @params['source_name'], + @params['server_errors']['update-error'], :retry) + RhoConnectClient.on_sync_update_error( @params['source_name'], + @params['server_errors']['update-error'], :rollback, @params['server_errors']['update-rollback'] ) + + RhoConnectClient.on_sync_delete_error( @params['source_name'], + @params['server_errors']['delete-error'], :retry) + +### unknown-client error +Unknown client error return by server after resetting server database, removing particular client id from database or any other cases when server cannot find client id(sync server unique id of device). +Note that login session may still exist on server, so in this case client does not have to login again, just create new client id. +Processing of this error contain 2 steps: + +When unknown client error is come from server, client should call database_client_reset and start new sync, to register new client id: + + :::ruby + rho_error = Rho::RhoError.new(err_code) + + if err_code == Rho::RhoError::ERR_CUSTOMSYNCSERVER + @msg = @params['error_message'] + end + + @msg = rho_error.message unless @msg and @msg.length > 0 + + if rho_error.unknown_client?(@params['error_message']) + Rhom::Rhom.database_client_reset + RhoConnectClient.dosync + end + +If login session also deleted or expired on the server, then customer has to login again: + + :::ruby + rho_error = Rho::RhoError.new(err_code) + + if err_code == Rho::RhoError::ERR_CUSTOMSYNCSERVER + @msg = @params['error_message'] + end + + @msg = rho_error.message unless @msg and @msg.length > 0 + + if err_code == Rho::RhoError::ERR_UNATHORIZED + WebView.navigate( + url_for( + :action => :login, + :query => { :msg => "Server credentials expired!" } + ) + ) + end + +### push_changes Method +If at any time you have records sitting on you server that have yet to be processed you'll need to use the [`push_changes`](../api/rhom-api#push_changes) Rhom API method to force the server to process those records. The reason for this is that the server will not process records that are in its queue unless there are new records to sync. To artificially send a POST to the server and force it to process those records, you must use the `push_changes` method. For example, if you had a model called `Product` and you needed the server to process all pending product models sitting the the queue, you would use `Product.push_changes()`. + +## Examples +### Notification Example +Here is a simple example of a sync notification method that uses some of the parameters described above: + + :::ruby + def sync_notify + status = @params['status'] ? @params['status'] : "" + bulk_sync? = @params['sync_type'] == 'bulk' + + if status == "in_progress" + # do nothing + + elsif status == "complete" or status == "ok" + WebView.navigate Rho::RhoConfig.start_path + + elsif status == "error" + + if @params['server_errors'] && + @params['server_errors']['create-error'] + RhoConnectClient.on_sync_create_error( @params['source_name'], + @params['server_errors']['create-error'], :delete) + end + + err_code = @params['error_code'].to_i + rho_error = Rho::RhoError.new(err_code) + + if err_code == Rho::RhoError::ERR_CUSTOMSYNCSERVER + @msg = @params['error_message'] + end + + @msg = rho_error.message unless @msg and @msg.length > 0 + + if rho_error.unknown_client?(@params['error_message']) + Rhom::Rhom.database_client_reset + RhoConnectClient.dosync + + elsif err_code == Rho::RhoError::ERR_UNATHORIZED + WebView.navigate( + url_for( + :action => :login, + :query => { :msg => "Server credentials expired!" } + ) + ) + else + WebView.navigate( + url_for( + :action => :err_sync, + :query => { :msg => @msg } + ) + ) + end + end + end + +**NOTE: If the view was updated using AJAX calls, this mechanism may not work correctly as the view location will not change from one AJAX call to another. Therefore, you might need to specify the `:controller` option in WebView.navigate.** + +### Sync Object Notifications +The RhoConnectClient can also 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. + +To use object notifications, first set the notification callback in `application.rb#initialize`: + + :::ruby + class AppApplication < Rho::RhoApplication + def initialize + super + + RhoConnectClient.set_objectnotify_url( + 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: + + :::ruby + class ProductController < Rho::RhoController + + # GET /Product + def index + @products = Product.find(:all) + + add_objectnotify(@products) + render + end + + # ... + + def sync_object_notify + #... do something with notification data ... + + # refresh the current page + WebView.refresh + # or call System.execute_js to call JavaScript function which will update list + end + end + +#### Object Notification Parameters +The object notification callback receives three arrays of hashes: "deleted", "updated" and "created". Each hash contains values for the keys "object" and "source_id" so you can display which records were changed. + +## Binary Data and Blob Sync +Synchronizing images or binary objects between RhoConnect and the RhoConnectClient is declared by having a 'blob attribute' on the [Rhom model](../api/rhom-api). Please see the [blob sync section](../rhoconnect/blob-sync) for more information. + +## Filtering Datasets with Search +If you have a large dataset in your back-end service, you don't have to synchronize everything with the RhoConnectClient. Instead you can filter the synchronized dataset using the RhoConnectClient's `search` function. + +Like everything else with the RhoConnectClient, `search` requires a defined callback which is executed when the `search` results are retrieved from RhoConnect. + +### Using Search +First, call `search` from your controller action: + + :::ruby + def search + page = @params['page'] || 0 + page_size = @params['page_size'] || 10 + Contact.search( + :from => 'search', + :search_params => { + :FirstName => @params['FirstName'], + :LastName => @params['LastName'], + :Company => @params['Company'] + }, + :offset => page * page_size, + :max_results => page_size, + :callback => url_for(:action => :search_callback), + :callback_param => "" + ) + render :action => :search_wait + end + + +Your callback might look like: + + :::ruby + 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 + +**NOTE: Typically you want to forward the original search query `@params['search_params']` to your view that displays the results so you can perform the same query locally.** + +Next, the resulting action `:show_page` will be called. Here we demonstrate using Rhom's [advanced find query syntax](../api/rhom-api#advanced-queries) since we are filtering a very large dataset: + + :::ruby + 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 + +If you want to stop or cancel the search, return "stop" in your callback: + + :::ruby + def search_callback + if(status and status == 'ok') + WebView.navigate( url_for :action => :show_page ) + else + 'stop' + end + end + +Finally, you will need to implement the `search` method in your source adapter. See the [RhoConnect search method](../rhoconnect/source-adapters#source-adapter-api) for more details. + +## RhoConnectClient API +Find the full list of methods available in the RhoConnectClient API [here](../api/RhoConnectClient) + +## Backround synchronization on iOS +On iOS, if application is put to background, it will be suspended. To allow application finish sync after application goes to background, you can use 'finish_sync_in_background' parameter in [`rhoconfig.txt`](configuration). When this parameter is set to '1', if sync is active in the time of background transition ( e.g. started from app_deactivate handler ), application will not be suspended until sync is finished. \ No newline at end of file diff --git a/docs/en/5.5/guide/testing.md b/docs/en/5.5/guide/testing.md new file mode 100644 index 00000000..c59a5b7c --- /dev/null +++ b/docs/en/5.5/guide/testing.md @@ -0,0 +1,70 @@ +# Testing +## Adding Unit Tests +When you [generate a model](rhom_ruby#creating-a-ruby-data-model), you get an _spec.rb file generated along with your controller. You would get the following for a model named "Person". + + Generating with model generator: + .... + [ADDED] app/test/person_spec.rb + +This file contains tests for your controller and is in the mspec format: [rubyspec.org](http://rubyspec.org/) + + :::ruby + describe "Person" do + #this test always fails, you really should have tests! + + it "should have tests" do + true.should == false + end + end + +We use this test format internally as well. You can see our specs for the core framework [here](http://github.com/rhomobile/rhodes/tree/1.4.0/spec/framework_spec/app/spec/) which use many functions of mspec. + +To run these tests however, you need the testing framework to be included in your app. To add this, you would run the rhogen task in your application folder: + + :::term + $ rhogen spec + +You will then see the mspec framework added to your application: + + Generating with spec generator: + [ADDED] app/SpecRunner + [ADDED] app/mspec.rb + [ADDED] app/spec_runner.rb + +**NOTE: You can also [create the mspec framework and run the test on applications within RhoStudio](../../2.2.0/rhostudio.tutorial#running-a-unit-test-in-rhostudio).** + +Finally, add the fileutils and mspec extensions to your build.yml: + + extensions: ["fileutils", "mspec"] + +You are now ready to run the tests. Simply add a link to the SpecRunner controller, and you will get a summary of number of passing/failing tests + +In your index.erb: + :::html +
                                                                            • Run tests
                                                                            • + +A summary of the results will be displayed on the screen. + +Detailed results will be displayed in your rholog.txt: + + I 01/15/2010 16:36:33 b0185000 APP| FAIL: Product - Expected true + to equal false + + apps/app/mspec/expectations/expectations.rb:15:in `fail_with' + apps/app/mspec/matchers/base.rb:8:in `==' + apps/app/Product/product_spec.rb:5:in `block (2 levels) in
                                                                              ' + ... + +And finally, a summary will be printed in rholog.txt as well: + + I 01/15/2010 16:36:33 b0185000 APP| ***Total: 3 + I 01/15/2010 16:36:33 b0185000 APP| ***Passed: 1 + I 01/15/2010 16:36:33 b0185000 APP| ***Failed: 2 + +## Disabling tests +When you are ready to do a production build of your application, change build.yml's build property to 'release' and the specs will not be included in the binary: + + ... + vendor: Acme, Inc. + build: release + ... \ No newline at end of file diff --git a/docs/en/5.5/guide/uichoices.md b/docs/en/5.5/guide/uichoices.md new file mode 100644 index 00000000..1a064a06 --- /dev/null +++ b/docs/en/5.5/guide/uichoices.md @@ -0,0 +1,193 @@ +# User Interface Architecture +## What is included in the box +When using RhoMobile Application Generator, a [default application structure](creating_a_project#project-structure) is created that includes jQuery Mobile and associated CSS stylesheets to control the user interface of the application. + +The RhoMobile framework also includes stylesheets customized for each device to give your applications a native look and feel. These stylesheets are included by default in all generated Rhodes applications (public/css/), and are included in the application layout file (app/layout.erb). + +The default styles will automatically be applied to all supported content found in the "header", "footer", and "content" divs. If you prefer using different names for any of these divs, you will need to update your stylesheets to reflect the new names in order to retain native styling. Conversely, if you prefer not to use any of the customized styles in your applications, you can either delete the links to the default stylesheets from your application, or simply place any content you wish to create custom styles for in a div that does not descend from "header", "footer", or "content". + +## Using Other Frameworks +You are free to remove the contents of layout.erb and implement your own CSS as well as 3rd party frameworks. There are many popular UI frameworks besides jQuery Mobile to choose from. Some frameworks that are traditionally geared towards mobilizing web sites like Twitter BootStrap or Zurb Foundation can be useful for those looking to take advantage of Responsive Design that these frameworks offer. Other frameworks like jQuery Mobile are geared towards providing many mobile enhance controls or elements. When choosing a UI framework, it is important to consider not only the features that it provides, but how they will perform on the intended targeted operating systems. Most of these frameworks use modern CSS3 techniques for UI effects and transitions that perform well on devices that provide a dedicated GPU typically found on Android and iOS devices. These frameworks may not be suitable for other platforms like Windows Mobile/CE. + +## View Layouts + +RhoMobile supports a layout mechanism based on ERB templates. The default layout template is called "layout.erb" and is located in the application root folder. Unless overridden, this layout is rendered on all non-Ajax requests. + +You may use layout.erb to define what CSS and JavaScript libraries are used by your views. + + :::html + + + + + + Test + + + + <% if System::get_property('platform') == 'WP7' %> + + <% end %> + + <% if System::get_property('platform') == 'APPLE' || System::get_property('platform') == 'ANDROID' || ( System::get_property('platform') == 'UNKNOWN' && System::get_property('webview_framework') =~ /^WEBKIT/) %> + + + + <% if System::get_property('platform') == 'APPLE' %> + + <% end %> + + + + + <% end %> + + <% if System::get_property('platform') == 'APPLE' %> + + <% elsif System::get_property('platform') == 'ANDROID' %> + + <% elsif System::get_property('platform') == 'WP7' %> + + <% elsif System::get_property('platform') == 'WINDOWS' %> + + <% elsif System::get_property('webview_framework') =~ /^WEBKIT/ %> + + <% end %> + + + + data-do-fix-forms="true" + <% end %> > + <%= @content %> + + + + +### Customizing Layouts + +If you would like to override or customize layout behavior for individual application pages, you can call the render function with the following parameters: + + :::ruby + render :action => 'index', + :layout => 'mycustomlayout', :use_layout_on_ajax => false + +The first argument is the action you would like to render. Next is the (optional) layout name, which assumes the application root as a base directory. In the above example, RhoMobile would look for a file called "mycustomlayout.erb" in the application root directory (you also may use :layout => false to disable the use of a layout template). The use_layout_on_ajax argument tells Rhodes whether or not to use the layout on Ajax calls (default is false). + +You can call the layout method on the controller to overwrite the default layout name: + + :::ruby + layout :mycustomlayout + +This will force the render call to use mycustomlayout.erb in place of the default layout file for all actions of this controller. + +## UI handling for multiple platforms + +While there are enough similarities between most browsers to facilitate the use of a single view file across platforms, you may encounter some differences which may necessitate the use of custom view files for specific devices. RhoMobile supports such differences in several ways: + +### Conditional display in view files + +To render content in some browsers but not others, you can include conditional statements within your views. For example, this code can be used to conditionally display the name of the phone's operating system in your model views. + + :::ruby + <% if platform == 'APPLE' %> + iPhone + <% elsif platform == 'ANDROID' %> + Android + <% else %> + Windows Mobile + <% end %> + +To see the appropriate conditional logic for determining the current platform in the application index (or other page outside a model), refer to the generated application layout.erb - this file contains conditional logic for loading the appropriate automatically-generated stylesheets. + +If you use more complex conditionals on a regular basis, you can also create custom helper methods in /app/helpers/browser_helper.rb. The following helper method can be used to + +a) determine if a browser is webkit based + + :::ruby + def is_webkit? + platform == "APPLE" || platform == "ANDROID" + end + +b) and if it is, include a custom webkit stylesheet in the html header in the application layout file. + + :::ruby + <%= '' if is_webkit? %> + +### Dynamic loading of custom view files based on the current platform +For more significant differences between browsers, RhoMobile supports platform-specific loading of view files. At runtime, the application detects the current platform, and checks first for a platform-specific file before loading the default view file. + +To create a platform-specific view file, simply name the file using the following convention +`[action_name].[platform_abbreviation].erb` (e.g., `show.wm.erb`) + + + + + +
                                                                              Android: androidindex.android.erb
                                                                              iPhone:iphoneindex.iphone.erb
                                                                              Windows Mobile: wmindex.wm.erb
                                                                              + +Keep in mind that any changes made to the standard view files are not incorporated into the custom views, so if you're developing custom views for a specific platform, ensure that any necessary changes are applied to all relevant view files. + +### Escaping HTML +If you need to output values that might contain HTML-unsafe characters, you can use ERB's `escape_html` to ensure that your code is escaped properly. This will help against accidental breakage as well as intentional XSS attempts. In your controller, include the `ERB::Util` module and in your templates, print values with `<%=html_escape @value %>` or the shorthand version `<%=h @value %>` + +Example: + +Ruby code: + + :::ruby + class ProductController < Rho::RhoController + include BrowserHelper + # We include the ERB::Util module so that the escape_html function is accessible from the view + include ERB::Util + + +HTML view: + + :::ruby +
                                                                              Message received: <%=h @message %>
                                                                              + +## Advanced Usage of Render +Render does not need to be called at the end of each controller action method. If render was not called, then it will default to rendering the action of the method you are in. + +Rendering of views works with no method in controller. If the method does not exist for an action, but a view exists for that action, then the view will be rendered. + +Rendering of files: render :file => "Settings/wait.erb" will render that file with the current controller's instance. By default, layout is false when rendering a file. + +Rendering of partials, with collections or locals. Either collections or locals must be provided: + + :::ruby + render :partial => "ad", :collection => ["foo1","foo2","foo3"] + +or + + :::ruby + render :partial =>"ad", :locals => { :ad => "foo_ad" } + +Will render the partial "_ad.erb" and the local variable "ad" will be available. With a collection, the partial will be rendered once per element. + +Load from 'partials' folder: + + :::ruby + render :partial =>"partials/ad", :locals => { :ad => "foo_ad" } + +### Partial Efficiency +Some developers may shy-away from partials because they have the mistaken impression that they are inefficient. You might easily imagine a file being read and parsed every time you use a partial however, that is not the reality. + +What really happens: + +* At build time, the partial is transformed from ERB to Ruby code +* Then (still at build time) the Ruby code is compiled to Ruby bytecode +* At run time, a file of Ruby bytecode is read into memory upon first encounter. Then it stays there (in memory). +* Other than that initial load, the overhead of using a partial is the overhead of a Ruby call and return. In other words, insignifigant. + +You should still use CSS to alter appearance but, if you use inline styles, etc. it is much more manageable with partials. And now you have the freedom to alter structure, add a CSS class you thought you wouldn't need, etc. etc. much more easily, and efficiently, than with some massive editor search-and-replace. \ No newline at end of file diff --git a/docs/en/5.5/guide/urlschemes.md b/docs/en/5.5/guide/urlschemes.md new file mode 100644 index 00000000..220047e0 --- /dev/null +++ b/docs/en/5.5/guide/urlschemes.md @@ -0,0 +1,81 @@ +# Launch a RhoMobile application from a URL Scheme + +Android and iOS support ways to launch your appication from a custom URL scheme. For example opening the following url in an iOS device will launch the Twitter application: + + :::html + twitter://user?screen_name=rhomobile + + +By properly configuring your build.yml, you can also take advantage of being able to launch your application from a URL scheme. This is useful for use on your application's website as well as for interapp communication. + +## Android +On Android it is possible to start RhoMobile app from a browser by a http link or a redirect response. It is also possible to register a custom URI scheme for the app. +The URI must strictly follow standard URI rules. Additionally Android makes and additional restriction that the the host part of the URI must be resolvable. +By default the http://rhomobile.com/com.vendor.appname URI format is used by RhoMobile. + +`vendor` and `appname` are parameters that are found in your build.yml + +It is possible to customize the URI with build.yml settings. By default a custom RhoMobile URI Scheme contains four parts: +- scheme +- host name +- path prefix +- optional path and query + :::html + http://rhomobile.com/com.vendor.appname/Product/new + +You can customize the scheme and host name parts with following build.yml parameters: + :::ruby + android: + URIScheme: myapp + URIHost: www.myhost.com +If the URIHost is specified no path prefix will be used. If no custom URIHost is specified then the default one is used (rhomobile.com) and the path prefix must contain java package name of your application used in your build.yml. +The optional path and query parameters are not needed in the build.yml but are just passed to your application for further processing. + +**NOTE: Google recommends to always use common scheme such as 'http', 'https', 'ftp', etc.** + +http scheme example: + :::html + Open System API Samples +build.yml: + :::ruby + vendor: "rhomobile" + name: "rhodessystemapisamples" + +Custom scheme examples: + :::ruby + android: + URIScheme: rho + + :::html + Open System API Samples + + + :::ruby + android: + URIScheme: rho-sas + URIHost: rhomobile.com + + :::html + Open System API Samples + +## iPhone +On iOS devices it is possible to start your RhoMobile app by link with a special registered URI scheme. You should register your custom URI scheme for the app by setting it up in the build.yml. + +Custom scheme example: + :::ruby + iphone: + BundleURLScheme: myapp + + :::html + Open MyApp application + +In your application you can get start params by + :::ruby + System.get_start_params() + +For the previous example the start params will be "string_with_params". + +From another RhoMobile application use can use the [System.openUrl](../api/system#mopenUrl) api: + :::ruby + System.openUrl('myapp:string_with_params') + diff --git a/docs/en/5.5/guide/using_certificates.md b/docs/en/5.5/guide/using_certificates.md new file mode 100644 index 00000000..999c2414 --- /dev/null +++ b/docs/en/5.5/guide/using_certificates.md @@ -0,0 +1,45 @@ +# Using Certificates +## Windows Mobile and CE +When using RhoMobile, any required certificates beyond the pre-loaded ones can be specified using the `CaFile` configuration setting in Config.xml. This points to a file containing the certificate data. The certificate(s) specified are treated as trusted authorities. Note this only applies to HTTPS requests. + +For example, to use certificates in the file 'mycert.pem' the file should be copied to the device and the appropriate entry made in Config.xml, e.g. if the file is in the root directory of the device: + + :::xml + + +## Android +On Android HTTPS requests can be done in two ways: + +* Using system browser navigation with WebView component: + * There are some differences in usage of these two ways: the system browser uses built-in system-trusted storage for root CAs. Root certificates should be installed from the system menu and will be used by any application that utilizes WebView UI component ( like browsers etc ) and reference navigation will also use this method. Only server SSL auth is currently implemented for WebView. Android 5 introduced the ability to use client auth in a browser and we are planning to implement it in future releases. +* Certificate formats: + * There are several formats of certificate available and any format is accepted which represents the certificate as encoded text. These typically have the extension .crt or .pem, but what's important is that they contain the certificate data between BEGIN and END lines. Certificates in the .der format are not supported and should be converted, e.g. using OpenSSL as shown below. + +## OpenSSL usage +The OpenSSL utility has many command line options which are well documented on the web, e.g. [here](https://www.sslshopper.com/article-most-common-openssl-commands.html) and [here](https://www.openssl.org/docs/HOWTO/certificates.txt): + +Some typical usages are shown below: + +### Generating a self-signed certificate: +1. You need to have a private key in order to encrypt to the certificate. Either use an existing private key, or generate one for the purpose. The easiest way to generate a basic, no passphrase, one is to use: + + +> openssl genrsa -out privkey.pem + +2. A self-signed certificate can then be generated from the key using: + +> openssl req -new -x509 -key privkey.pem -out capturableacert.pem -days 365 + +3. You will be asked a series of questions. For all _but_ Common Name you can press return to leave the field blank, but for Common Name enter the domain name which will serve the certificate. Add the private key to your web server according to the server's documentation, and add the certificate to the web client as described above. + +### Inspecting a certificate +1. To decode the contents of a certificate use: + +> openssl x509 -in cacert.pem -text -noout + +2. The Common Name is shown as Subject: CN=. The signing authority is shown as Issuer: CN=, which will be the same as Subject for a self-signed certificate. + +### Converting a certificate +To convert a .der format certificate to a .pem one use: + +> openssl x509 -inform der -in cacert.der -out cacert.pem \ No newline at end of file diff --git a/docs/en/5.5/guide/using_emulators.md b/docs/en/5.5/guide/using_emulators.md new file mode 100644 index 00000000..4569853d --- /dev/null +++ b/docs/en/5.5/guide/using_emulators.md @@ -0,0 +1,78 @@ +# Using OS Emulators + +## Overview + +There are three ways to run your RhoMobile application: + +* On a device +* On RhoSimulator +* On a platform-specific emulator + +This guide covers the last option, platform-specific emulators. + +Most mobile platforms provide a way to emulate a device on a regular PC for development purposes; this allows you to test on a variety of simulated hardware (different screen sizes, different amounts of RAM, etc.) without the need to have every type of device on hand. + +iOS provides a simulator instead of an emulator. The difference lies in that, while an emulator virtualizes the target hardware and runs the same code as the real device, a simulator, as the name imples, merely simulates the device, but the code running underneath is not the same as what a real device would execute. Technically, an emulator is a more faithful representation of the device, but in practice, both options work sufficiently well to be able to develop and test applications. + + +## What to expect. Differences between emulators and a real device + +Due to several key differences, testing on an emulator / simulator is unfortunately not a substitute for testing on actual hardware. You should expect to test on real hardware often and, at a minimum, before releasing your application to end users. + +Some differences between the emulated / simulated environment and real devices are outlined below. + +* Speed: Emulators tend to be slower than a real device, while the iOS simulator is typically faster than a hardware iPhone/iPad. + +* Hardware access: Emulators do not attempt to replicate the functionality of peripherals such as a magnetic card reader or barcode scanner. + +* Network: By default, mulators use the host computer's network connectivity as-is. This usually provides the application with much better network speed and reliability than it will have on a mobile device. + +* Battery: Emulators do not provide a way to measure battery usage. + + +## Android + +The Android SDK includes an Android Virtual Device (AVD) manager with which you can create as many different configurations as you need and run each independently. Once an AVD is running, load your application on it from the command line with + + :::term + rake run:android:emulator + +or from RhoStudio by editing your run configuration and selecting Android - Emulator as the target. + +Refer to [Google's documentation on using the Android emulator](http://developer.android.com/tools/devices/emulator.html) for a detailed overview of all the possibilities. Be aware, however, that while some features can only be invoked from the command line, other tasks like reviewing logs in real time, taking screenshots or setting fake GPS coordinates for geolocation apps can be performed from [Google's Android Developer Tools Eclipse plugin](http://developer.android.com/sdk/index.html). Use the DDMS perspective and select a device or emulator from the left, then use the "Emulator Control" tab and scroll down to set device coordinates or load them from a previously saved file. + +Android DDMS perspective + + +## iOS + +The iOS simulator is integrated with XCode. Unlike trying to deploy an application on a real iPhone/iPad, running on the simulator does not require a paid developer account or provisioning certificate. + +Refer to the section [Running your application](creating_a_project#running-your-application) and select "Simulator" instead of "RhoSimulator" to use the iOS simulator. Alternatively, you can also invoke the iOS simulator from the commad line with: + + :::term + rake run:iphone + +Once running, use the `Hardware` menu to simulate rotating or shaking the device, or the `Debug / Location` option if your application uses geolocation and you want to test that feature. + +The complete documentation for all iOS Simulator features can be found at [Interacting with iOS Simulator](http://developer.apple.com/library/ios/documentation/IDEs/Conceptual/iOS_Simulator_Guide/InteractingwiththeiOSSimulator/InteractingwiththeiOSSimulator.html#//apple_ref/doc/uid/TP40012848-CH3-SW1) + +## Windows Phone 8 + +The Windows Phone 8 SDK can be [freely downloaded](https://dev.windowsphone.com/en-us/downloadsdk) and will integrate with Visual Studio 2013 automatically. + +**NOTE: If you are running Windows on a virtual machine, the emulator may fail to start and the system will show an error message like "xde.exe has stopped working". Running the WP8 emulator on a virtual machine is not officially supported by Microsoft, but it is possible to make it work if you enable "Nested VT" (Parallels) / "Virtualize Intel VT-x/EPT or AMD-V/RVI" (VMWare) on your virtualization host software. At the time of this writing, VirtualBox does not support nested virtualization.** + +When the emulator is running, locate the toolbar: + +Windows Phone 8 emulator toolbar + +and click the icon with the double arrow pointing to the right to reveal an additional set of tools, where you can simulate + +* moving the device in 3D space, to [test the accelerometer](http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202936(v=vs.105).aspx) + +Windows Phone 8 emulator accelerometer test + +* [Test location data](http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202933(v=vs.105).aspx) + +Windows Phone 8 emulator fake GPS coordinates \ No newline at end of file diff --git a/docs/en/5.5/guide/using_rhoconnect.md b/docs/en/5.5/guide/using_rhoconnect.md new file mode 100644 index 00000000..c21a3a88 --- /dev/null +++ b/docs/en/5.5/guide/using_rhoconnect.md @@ -0,0 +1,276 @@ +# Using RhoConnect + +RhoConnect is the part of RhoMobile Suite that synchronizes data between a server and a mobile application. It consists of two parts: RhoConnect Server, which interfaces with your back-end systems and/or database, and RhoConnect Client, integrated in RhoMobile by means of the [RhoConnectClient API](../api/RhoConnectClient). + +Adding data synchronization via RhoConnect to your RhoMobile application is as simple as enabling the `:sync` flag in your models. This triggers the internal sync system to synchronize data for the model and transparently handle bi-directional updates between the application and the RhoConnect server. By default, the system will automatically keep your data updated in the background but the provided `RhoConnectClient` class allows you to trigger the sync process programmatically and offers fine-grained control of which models to sync. + + +## Prerequisite + +Before you can make use of RhoConnectClient on the device, you need to include the `rhoconnect-client` extension in your `build.yml` + + :::yaml + extensions: ["rhoconnect-client"] + +This extension is added to all newly generated RhoMobile applications by default. If it is missing in yours, you can add it manually. + +## Authenticating + +The first step in making use of RhoConnect is to authenticate with the RhoConnect server using the [RhoConnectClient.login](../api/RhoConnectClient#mlogin) method. + +Ruby syntax: + :::ruby + Rho::RhoConnectClient.login('guest', 'password', url_for(:action => :login_callback)) + + def login_callback + error_code = @params['error_code'].to_i + if error_code == Rho::RhoError::ERR_NONE + # login success, start sync + Rho::RhoConnectClient.doSync + else + if error_code == Rho::RhoError::ERR_CUSTOMSYNCSERVER + # application defined error message + msg = @params['error_message'] + end + if not msg or msg.length == 0 + msg = Rho::RhoError.new(error_code).message + end + + # do something for the login error + end + end + + +JavaScript syntax: + :::javascript + Rho.RhoConnectClient.login('guest', 'password', function(result) { + var errorCode = parseInt(result.error_code); + if (errorCode == Rho.RhoError.ERR_NONE) { + // login success, start sync + Rho.RhoConnectClient.doSync(); + } else { + var errorMessage = result.error_message; + // do something for the login error + } + }); + + +## Setting up notifications + +RhoConnectClient uses notifications to provide information about the sync process to the application: which model is currently being processed, how many items have been completed and how many remain. Notifications can be setup once for the entire application lifetime or each time a sync is triggered; your application can use this information to provide feedback to the user displaying different indicators, progress bars etc. + +To setup notifications for a model + +Ruby syntax: + :::ruby + def sync_notify + # handle the notification + end + + # Request notifications for the "Account" model + Rho::RhoConnectClient.setNotification('Account', url_for(:action => :sync_notify)) + +JavaScript syntax: + :::javascript + function syncNotify(params) { + // handle the notification + } + Rho.RhoConnectClient.setNotification('Account', syncNotify); + +You can also set notifications for all models at once: + +Ruby syntax: + :::ruby + Rho::RhoConnectClient.setNotification('*', url_for(:action => :sync_notify)) + +JavaScript syntax: + :::javascript + Rho.RhoConnectClient.setNotification('*', syncNotify); + +## Controlling synchronization programmatically + +Call the [RhoConnectClient.doSync](../api/RhoConnectClient#mdoSync) method to start the sync process + +Ruby syntax: + :::ruby + # start the RhoConnectClient sync process + Rho::RhoConnectClient.doSync() + + # start sync process with status popup + Rho::RhoConnectClient.doSync(true) + + # dont show status popup and pass parameters to sync server + Rho::RhoConnectClient.doSync(false, "param1=abc") + + # sync only sources that have local changes + Rho::RhoConnectClient.doSync(false, "", true) + +JavaScript syntax: + :::javascript + // start the sync process + Rho.RhoConnectClient.doSync(); + + // start sync process with status popup + Rho.RhoConnectClient.doSync(true); + + // dont show status popup and pass parameters to sync server + Rho.RhoConnectClient.doSync(false, "param1=abc"); + + // sync only sources that have local changes + Rho.RhoConnectClient.doSync(false, "", true); + +Use the `doSyncSource` method to start the sync process for only one source + +Ruby syntax: + :::ruby + # start the RhoConnectClient sync process + Rho::RhoConnectClient.doSyncSource('Account') + + # start sync process with status popup + Rho::RhoConnectClient.doSyncSource('Account', true) + + # dont show status popup and pass parameters to sync server + Rho::RhoConnectClient.doSyncSource('Account', false, "param1=abc") + +JavaScript syntax: + :::javascript + // start the sync process for given source + Rho.RhoConnectClient.doSyncSource('Account'); + + // start sync process with status popup + Rho.RhoConnectClient.doSyncSource('Account', true); + + // dont show status popup and pass parameters to sync server + Rho.RhoConnectClient.doSyncSource('Account', false, "param1=abc"); + +## Handling Notifications + +RhoConnectClient returns information about the ongoing synchronization via the notification callback in the form of a `hash`. + +The below 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. “Account”) +* `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: + +Additionally, depending on the value of `status`, additional information will be present: + +### Status "in_progress" + +The parameters returned for `in_progress` status vary according to the sync type + +#### "incremental" sync parameters + +* `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 processed so far for this source. + +#### "bulk" sync parameters + +* `partition` – Current bulk sync partition. +* `bulk_status` – The state of the bulk sync process as a `hash` with the below values: + * `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 + +### 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 + * `unknown-client-error` - An error wherein the server cannot find the client ID. + +Each error contains a `message` key with the error message. For example: + +Ruby syntax: + :::ruby + err_msg = @params["server_errors"]["query-error"]["message"] + +JavaScript syntax: + :::javascript + var errMsg = params["server_errors"]["query-error"]["message"]; + + +### Status "ok" + +* `total_count` – Total number of records that exist for this RhoConnect source. +* `processed_count` – Number of records included in the last sync page. +* `cumulative_count` – Number of records processed so far for this source. + +### Status "complete" + +This status is returned only when the synchronization is complete (all partitions are done synchronizing). + +### Status "schema-changed" + +This value is present if a `FixedSchema` model has changed during the current sync run. A new bulk sync run should be triggered (by setting `RhoConnectClient.bulksyncState` to 0 followed by a call to `RhoConnectClient.doSync`) and the user should be alerted in the UI. + +## Using search + +If you have a large dataset in your backend service, you can use the `RhoConnectClient.search` method to perform a server-side search and receive the models that match your query, without having to fetch the whole dataset. + +NOTE: this method is available for Ruby only. + +Ruby syntax: + :::ruby + RhoConnectClient.search( + { + 'Account', + :from => 'search', + :search_params => { + :FirstName => 'FirstName', + :LastName => 'LastName' + }, + :offset => 0, + :max_results => 10 + }, + url_for(:action => :search_callback) + ) + + def search_callback + status = @params["status"] + if (status == "ok") + # success, local database will contain the matching records + else + # search error + end + end + +## Stopping Synchronization + +Call the `RhoConnectClient.stopSync` method to stop any sync operations currently in progress. + +Ruby syntax: + :::ruby + Rho::RhoConnectClient.stopSync + +JavaScript syntax: + :::javascript + Rho.RhoConnectClient.stopSync(); + +## Logging out + +To logout the user from the RhoConnect server and remove the local user session, use the `RhoConnectClient.logout` method. + +Ruby syntax: + :::ruby + Rho::RhoConnectClient.logout + +JavaScript syntax: + :::javascript + Rho.RhoConnectClient.logout(); + +## Related reading + +* The [RhoConnectClient API reference](../api/RhoConnectClient) contains the documentation for the `RhoConnectClient` class and its methods +* Detailed documentation for RhoConnect Server is available in the [RhoConnect Guides](../rhoconnect/introduction) diff --git a/docs/en/5.5/guide/view_extensions.md b/docs/en/5.5/guide/view_extensions.md new file mode 100644 index 00000000..ed55c5b4 --- /dev/null +++ b/docs/en/5.5/guide/view_extensions.md @@ -0,0 +1,109 @@ +# Native View Extensions + +The Native View interface allows developers to implement a custom native view and seamlessly integrate it into the Rhodes framework. (This is currently only supported on iPhone; Android, WM and Blackberry is coming soon). + +To access implemented view navigate to a url where url schema is the register type name of your view: + + view_type_name:path?query_string#anchor + +Example: + + :::ruby + WebView.navigate("my_video_view:/app/files/barak_obama_0123.mpg") + + +When Rhodes application navigates to a native view it will replace current view (WebView in most cases) with requested native view and pass path?query_string#anchor to created native view. If application navigate to that view again new instance of the view will not be created but the rest of url will be passed to the view. + +To provide custom native view native extension should implement NativeViewFactory interface and register it with Rhodes framework using `RhoNativeViewManager::registerViewType(const char* viewType, NativeViewFactory* factory)` call (or similar call on BB, see definition below). Rhodes framework will use registered factory to create and display view of given type. + +## Native view manager, factory, and view interface definitions on iPhone, Android, Windows Mobile + + :::cpp + class NativeView { + public: + // that function must return native object provided view functionality : + // UIView* for iPhone + // jobject for Android - jobject must be android.view.View class type + // HWND for Windows Mobile + virtual void* getView() = 0; + // Used by Rhodes to pass path?query_string#anchor to the view + virtual void navigate(const char* url) = 0; + }; + + class NativeViewFactory { + public: + virtual NativeView* getNativeView(const char* viewType) = 0; + virtual void destroyNativeView(NativeView* nativeView) = 0; + }; + + class RhoNativeViewManager { + public: + static void registerViewType(const char* viewType, NativeViewFactory* factory); + static void unregisterViewType(const char* viewType); + }; + +## Native view manager, factory, and view interface definitions on Blackberry + + :::java + interface NativeView { + net.rim.device.api.ui.Field getView(); + void navigate(String url); + } + + interface NativeViewFactory { + NativeView getNativeView(String viewType); + }; + + class RhoNativeViewManager extends Object{ + public: + static void registerViewType(String viewType, NativeViewFactory factory); + static void unregisterViewType(String viewType); + }; + +## Sample +See [Rhodes-System-Api-Samples](http://github.com/rhomobile/rhodes-system-api-samples) for details of how to implement and use the native view interface. This sample implements a "rainbow_view" native view; you should add rainbow to the list of extensions to include it to the application. + +See [/app/NativeView/controller.rb](http://github.com/rhomobile/rhodes-system-api-samples/blob/master/app/NativeView/controller.rb) and [/app/NativeView/index.erb](http://github.com/rhomobile/rhodes-system-api-samples/blob/master/app/NativeView/index.erb) for details how to call native view from your controller. + +** NOTE: Windows Mobile: Visual Studio 2008 has issues with long paths. If you have problems with building rainbow extension, move your rhodes folder to a shorter path. ** + +* To navigate to rainbow view in your controller, call `WebView.navigate('rainbow_view:red')`. In your url schema indicates view type you want to open and rest of the url (red) passed to the after it was created. + +* To pass parameters to created view you may call WebView.navigate again: `WebView.navigate('rainbow_view:green')`. In your native code you may pass parameters to the native view by calling `pNativeView->navigate(url)` where pNativeView is an instance of native view created by the `RhoNativeViewManager` using registered factory. + +* To close the view you created, navigate to any other url. + +See [/extensions/rainbow](http://github.com/rhomobile/rhodes-system-api-samples/tree/master/extensions/rainbow/) for implementation of the "rainbow" native view. + +* See how to register your view type with Rhodes here: [RainbowViewFactoryRegister.cpp](http://github.com/rhomobile/rhodes-system-api-samples/blob/master/extensions/rainbow/ext/rainbow/platform/iphone/Classes/RainbowViewFactoryRegister.cpp) + +* See implementation of native view factory here: [RainbowViewFactory.mm](http://github.com/rhomobile/rhodes-system-api-samples/blob/master/extensions/rainbow/ext/rainbow/platform/iphone/Classes/RainbowViewFactory.mm) + +* See sample implementation of native view object here: [RainbowView.h](http://github.com/rhomobile/rhodes-system-api-samples/blob/master/extensions/rainbow/ext/rainbow/platform/iphone/Classes/RainbowView.h) and [RainbowView.m](http://github.com/rhomobile/rhodes-system-api-samples/blob/master/extensions/rainbow/ext/rainbow/platform/iphone/Classes/RainbowView.m). + + * In the "rainbow" view you can see several buttons: + * [Red], [Green], [Blue] buttons change color by calling controller action using rho_net_request(url). Controller in turn execute WebView.navigate("rainbow_view:color") on the same view to change color. + * [Stop] and [Play] buttons execute native code inside native view object. + * [Close Native View] button return you to the web view by executing rho_webview_navigate(url, tab_index). + +This sample extension uses functionality provided by Rhodes framework and therefore include few framework header files: + +* [$(RHO_ROOT)/platform/shared/common/RhoNativeViewManager.h](http://github.com/rhomobile/rhodes/blob/master/platform/shared/common/RhoNativeViewManager.h) +* [$(RHO_ROOT)/platform/shared/common/RhodesApp.h](http://github.com/rhomobile/rhodes/blob/master/platform/shared/common/RhodesApp.h) +* [$(RHO_ROOT)/platform/shared/rubyext/WebView.h](http://github.com/rhomobile/rhodes/blob/master/platform/shared/rubyext/WebView.h) + +Make sure the following folders are added to your compiler include path: + +* [$(RHO_ROOT)/platform/shared/rubyext](http://github.com/rhomobile/rhodes/tree/master/platform/shared/rubyext/) +* [$(RHO_ROOT)/platform/shared/ruby/include](http://github.com/rhomobile/rhodes/tree/master/platform/shared/ruby/include/) +* [$(RHO_ROOT)/platform/shared](http://github.com/rhomobile/rhodes/tree/master/platform/shared/) +* [$(RHO_ROOT)/platform/shared/ruby/iphone](http://github.com/rhomobile/rhodes/tree/master/platform/shared/ruby/iphone/) +* [$(RHO_ROOT)/platform/shared/common](http://github.com/rhomobile/rhodes/tree/master/platform/shared/common/) + +## url_for_nativeview +Examples of how to use the url_for_nativeview method: + + url_for_nativeview :name => 'rainbow_view', :param => 'red' + ==> rainbow_view:red + + diff --git a/docs/en/5.5/guide/viewport.md b/docs/en/5.5/guide/viewport.md new file mode 100644 index 00000000..27c75c5c --- /dev/null +++ b/docs/en/5.5/guide/viewport.md @@ -0,0 +1,68 @@ +# Viewport Configuration + +Using the Viewport configuration setting in your app's config.xml, as well as in the HTML source of your app, you can configure the way your app will appear on a device based on either the device's width or a width you otherwise specify. We will go over a few of the less intuitive parts of the viewport configuration here. + +## Enabling Viewport Modification +This will enable you to use your stnadard viewport settings within the Zebra Webkit. For more information on the Viewport metatag see the [Mozilla Viewport Docs](https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag). + +Firstly, to enable the viewport in Zebra WebKit on Windows Mobile / CE you need to specify the following configuration option: + +`config.xml` + + + +## Specifying Device Widths +Specifying `width=device-width` in your meta tag will either: + +* Use the value specified at `` if one is specified. +* Use the actual physical device width if no configuration option is specified, 480 pixels on an MC75a. + +Pages that specify an initial or maximum scale means the width property actually translates into a minimum viewport width. For example, if your layout needs at least 500 pixels of width then you can use the following markup. When the screen is more than 500 pixels wide, the browser will expand the viewport (rather than zoom in) to fit the screen: + +### With Specified initial-scale + +The same page rendered on iPhone, Nexus 5 and MC75a will appear as follows: + +In your app's html: + + +
                                                                              +
                                                                              +

                                                                              iPhone 5c iOS 7

                                                                              + +
                                                                              +
                                                                              +

                                                                              Nexus 5 Android 5 (KitKat)

                                                                              + +
                                                                              +
                                                                              +

                                                                              MC75A Windows Mobile 6.5

                                                                              + +
                                                                              +
                                                                              + +* An iPhone will render pages with a device width of 320 pixels, [by design](https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag), even though the physical screen dimensions are different. +* An Android device's viewport appears similar but is not identical; the screen width is rendered at 360 pixels, presumably because the device resolution is different for Android. +* The MC75a is behaving within the parameters of documented behavior when specifying both device-width and initial-scale, as detailed above, expanding the viewport to fit the contents. + +### Without Specified initial-scale + +Let us consider the same page without specifying an initial-scale: + +In your app's html: + + +
                                                                              +
                                                                              +

                                                                              Nexus 5 Android 5 (KitKat)

                                                                              + +
                                                                              +
                                                                              +

                                                                              MC75A Windows Mobile 6.5

                                                                              + +
                                                                              +
                                                                              + +Note that without specifying an initial-scale the MC75a will display the page with a viewport width of 320 pixels. This is with a specified device width of 320 pixels in the `config.xml` file, had this been left blank, the page would again render with a width of 480 pixels.The specification of a 320 pixel width is used to match the appearance on the iPhone as closely as possible. + +We suggest that you not specify an initial-scale in the viewport if you want the page to be locked to a resolution of 320 pixels on Windows Mobile. You can modify the layout.erb file to have a custom viewport for Windows Mobile if required. diff --git a/docs/en/5.5/guide/visualstudio.md b/docs/en/5.5/guide/visualstudio.md new file mode 100644 index 00000000..dd90712a --- /dev/null +++ b/docs/en/5.5/guide/visualstudio.md @@ -0,0 +1,128 @@ +#Visual Studio Plug-in + +The RhoMobile Visual Studio Plug-in allows you to build Rhodes-based applications that target Windows Phone 8. The current version allows you to: + +* Generate an application structure +* Generate data models +* Edit application code +* Build apps for Windows Phone 8 +* Deploy and run the apps + +## Prerequisites + +* Visual Studio 2012 Professional +* Windows Phone 8 SDK +* RhoMobile Suite 4.0 or higher +* Silver or Gold RhoMobile subscription +* A copy of the plug-in (see below) + +## Installing +1. Visit the [RhoMobile vsplugin page](https://github.com/rhomobile/vsplugin/tree/master/Installer) on GitHub and click on the VSIX file to begin the download +2. Locate and **double-click the downloaded file** in Windows Explorer +3. When prompted, **select only the editions of Visual Studio in which the extension will be used** +4. **Click OK** to begin installation +5. When finished, **close and re-open any open Visual Studio windows** + +NOTE: During installion (and removal) of the extension, a User Account Control prompt might appear in Windows. This is expected behavior; the current version of the extension installs for all users. + +## Generating an application + +1. In Visual Studio 2012, **select File > New Project** +2. **Select RhoMobile** then **RhoMobile Windows Phone 8 Project** +3. **Name the project, click OK** +4. When prompted, **select a Rhodes or RhoElements framework** (If you're not sure which to select, read about [the differences between Rhodes and RhoElements](welcome#rhomobile)) +5. **Click Finish** + +Once the app is generated, a folder structure like the one below will appear in your workspace in a folder with the name you gave your app. + +![Anatomy of a Rho app](https://github.com/rhomobile/rhomobile-docs/blob/master/public/images/rhoelementstutorial/Anatomy_of_a_Rho_application.png?raw=true =350x) + +## Adding a productid GUID + +The process above generates all the files and folders to define the structure of your new application. This structure is the same as when [creating an app using RhoStudio](creating_a_project). However, ro run your new Windows Phone app you'll have to add a 'productid GUID' to its `build.yml` file. As seen above, the [build.yml](build_config) is located in the app's root directory. + +Using Visual Studio or any text editor**, append the `build.yml` file as follows**: + + + wp: + productid: 632621d0-5ecb-012e-2c97-482a1411c191 + + +## Generating data models +RhoMobile includes Rhom, a database object mapper (ORM) that provides a powerful high level interface to an on-device SQLite database. Rhom works hand in hand with the RhoConnectClient to enable two-way synchronization between your application and a RhoConnect server. + +To create a data model: + +1. In Visual Studio, **right-click the project name** +2. Select **Add New Item** +3. In the Add New Item dialog, **select RhoMobile Model** +4. **Click Add** +5. In the Add New RhoMobile Model dialog, **enter a model name and a list of attributes (separated by commas)** +6. **Click Finish** + +This will automatically generate a folder and the corresponding files for handling CRUD operations for the model. For a better understanding of data models, please refer to the [RhoMobile Data Handling Guide](local_database#what-is-a-model). + +## Adding a Windows Phone 8 UI +Since RhoMobile apps employ HTML, CSS and JavaScript to define the user interface and application behavior, a Windows Phone 8 app can be designed with a WP-native UI (a.k.a. 'Metro' by using one of these Metro-like frameworks: + +* [Bootmetro](http://aozora.github.io/bootmetro/) +* [Metro UI CSS](http://metroui.org.ua/) +* [Metro CSS](http://code52.org/metro.css/) +* [Metro-Bootstrap](http://talkslab.github.com/metro-bootstrap/) +* [jqMetro](http://jqmetro.codeplex.com/) + +Follow the instructions that accompany the framework you've chosen to replace the default. + +## Launching your new app + +NOTE: Building RhoMobile apps requires an account on Rhomobile.com and that the user be logged in. This must be done via RhoMobile.com or RhoStudio before your build is attempted; no dialog or log-in prompt will appear within Visual Studio. + +Now that you're now ready to build and launch your app, you must select from following build configuration options: + +* **RhoSimulator** builds and launches the app in RhoSimulator, a Webkit-enabled window that displays your app along with a Web Inspector tool to help facilitate debugging + +* **Device** deploys the app to your Windows Phone 8 device connected to the development machine for on-device debugging using Visual Studio or web inspector tools + +* **Emulator** launches the app in the Windows Phone 8 emulator provided by Microsoft + +NOTE: RhoSimulator is recommended while initially building your app's UI and establishing its basic behavior; it is the fastest method for testing and debugging web apps. + +##Starting RhoSimulator... +###...from within Visual Studio +To launch your new application in the RhoSimulator: + +1. From the Visual Studio toolbar, **select RhoSimulator in the dropdown** +2. **Click Start** + +###...from the command line: +To run your the app in RhoSimulator from the command line, execute the following command: + + :::term + $ rake run:wp8 + +###Keyboard for Windows Phone 8 Emulator +The host computer's keyboard can be used with the Windows Phone 8 emulator, but is disabled by default. To enable it, press the **PgUp** key or the **PAUSE/BREAK** key. While the host keyboard is enabled, device rotation simulation is disabled. To rotate the device in the emulator, you must first disable the keyboard by pressing the **PgDown** key. MSDN has more information about [host keyboard use with the WP8 emulator](http://msdn.microsoft.com/en-us/library/ff754352). + +### Run application device using command line: + + $rake run:wp8:device + +* See log in application folder : rholog.txt + +NOTE: When running on device you may need to disconnect USB cable from device to see log + +## Plug-in feature roadmap +The following features are on the Visual Studio Plug-in roadmap: + +* JavaScript debugging +* Building for Windows Mobile/CE +* Intellisense for RhoMobile APIs +* RhoConnect Projects +* Ruby Debugging +* Building for Android +* Remote build integration with RhoHub + +Related Resources + +* [Windows Phone 8 Dev Center](http://dev.windowsphone.com/en-us) +* [Metro User Interface Implementation and Resources](http://www.queness.com/post/13493/metro-user-interface-implementation-and-resources) diff --git a/docs/en/5.5/guide/web_services.md b/docs/en/5.5/guide/web_services.md new file mode 100644 index 00000000..0a6c9ba9 --- /dev/null +++ b/docs/en/5.5/guide/web_services.md @@ -0,0 +1,280 @@ +# Accessing Web services from RhoMobile + +## Overview + +RhoMobile applications typically use a RhoConnect server to synchronize data with backend systems but they can also retrieve and upload data from other services. In a warehouse application, for example, while you may use RhoConnect to manage products, you can integrate a different service to retrieve pre-processed data in order to build a dashboard interface, or see orders related to a particular customer. + +## Synchronous vs Asynchronous +A network call being synchronous or asynchronous refers to whether your code continues executing immediately after the call is made or it waits for the result before continuing. + +Synchronous calls block execution until a result is received (or the operation times out). Asynchronous calls, on the other hand, return control to your code immediately. When the response is received (or an error occurs), a callback is invoked with the result. + +Synchronous calls are conceptually very easy to work with but they have a very important drawback: your application will appear to hang until the request completes. + +## Network API + +RhoMobile includes its own [Network API](../api/Network) with facilities for making GET and POST requests. + +Ruby: + :::ruby + # synchronous request + response = Rho::Network.get({ + :url => "http://www.example.com" + }) + + # the following line will only be reached after a response is received + # or the request ends with an error + if response["status"] == "ok" + puts "Request complete, the server returned status code #{response["http_error"]} and body #{response["body"]}"" + else + puts "An error occurred" + end + +JavaScript: + :::javascript + // synchronous request + var response = Rho.Network.get({ + url : "http://www.example.com" + }); + + # the following line will only be reached after a response is received + # or the request ends with an error + if (response.status) === "ok" + alert("Request complete, the server returned status code "+params.http_error+" and body "+params.body); + else + alert("An error occurred"); + end + + +Ruby: + :::ruby + # asynchronous request + def get_request + response = Rho::Network.get({ + :url => "http://www.example.com" + }, url_for(:action => :network_request_callback)) + + puts "The above code will not wait for the request to complete. This line will be executed immediately" + end + + def network_request_callback + if @params["status"] == "ok" + puts "Request complete, the server returned status code #{response["http_error"]} and body #{response["body"]}"" + else + puts "An error occurred" + end + end + +JavaScript: + :::javascript + // asynchronous request + function get_request() { + var response = Rho.Network.get({ + url : "http://www.example.com", + }, network_request_callback); + } + + function network_request_callback(params) { + if (params.status==="ok") { + alert("Request complete, the server returned status code "+params.http_error+" and body "+params.body); + } else { + alert("An error occurred"); + } + } + +Your request will be synchronous or asynchronous depending on whether you pass the `callback` parameter +In general, asynchronous requests are preferable. Many times, however, you need the data before the user can continue working; in this case, the following pattern can be used: + +* make an asynchronous request +* render a "waiting" screen to inform the user that the application received their command and is doing something +* when the callback is received, process the data and navigate to a new screen + + +## jQuery + +jQuery also includes convenient APIs for making AJAX requests from JavaScript: `jQuery.ajax` and `jQuery.getJSON` + + :::javascript + function perform_ajax_request() { + $.ajax({ + url: "/app/MyController/get_data" + }).done(function(data) { + parsed = ...; // parse the received string + alert("Customer of the day: "+parsed.customer_of_the_day+" with "+parsed.total_orders+" orders"); + }).fail(function(request, textStatus, errorThrown) { + alert("An error occurred: "+errorThrown); + }).always(function() { + alert("Request completed"); + }); + } + +This snippet will: +* invoke the `get_data` action in `MyController` +* if the request is successful, parse the received data and show it +* if an error occurred, show a message +* notify the user that the request completed (wheter it was successful or not) + +You can return data from your controller in any format, but the easiest way to interchange information between JavaScript and Ruby is to use JSON; see the following example: + + :::ruby + def get_data + result = ::JSON.generate({ + :customer_of_the_day => "John Doe", + :total_orders => 42 }) + + # this is necessary because by default, controllers render their view together with a layout + # in an AJAX request, we only want to return our data formatted as JSON but not the layout + render :string => result, :use_layout_on_ajax => true + end + + :::javascript + function perform_json_request() { + $.getJSON("/app/MyController/get_data") + .done(function(data) { + // the response is parsed as JSON and provided as the data parameter + alert("Customer of the day: "+data.customer_of_the_day+" with "+data.total_orders+" orders"); + }); + } + +## The same-origin policy and cross-domain requests + +One drawback of using `jQuery.ajax` instead of the [RhoMobile Network API](../api/Network) is that, for security reasons, JavaScript code runs inside a sandbox. One of the rules of this sandbox, called the "same-origin policy", mandates that code loaded from one origin (i.e., www.example.com) cannot communicate with code loaded from a different origin (www.example.net). This has the practical consequence that you can only make AJAX calls to the same server that the current page was loaded from, which in a native RhoMobile application case is the mobile device itself (`localhost`). If for some reason you cannot or prefer not to use the RhoMobile Network API, there are several ways to work around this limitation: JSONP, CORS and using Ruby code as a local proxy. + + +### Ruby code as a local proxy + +**NOTE: If you need to make cross-domain requests but do not want to [use the RhoMobile Network API in JavaScript](#network-api), using Ruby code as a local proxy is usually the easiest approach in a native RhoMobile application** + +Although by default you can only make AJAX requests to the embedded server in a RhoMobile application, because your controllers can execute any code you need, you can easily create a custom controller that receives AJAX requests from the JavaScript in your page, connects to a remote server using the Network API as seen above and returns the results back to JavaScript. This is the only scenario where you should prefer to use synchronous requests. + +Example: + +Ruby controller: + :::ruby + def get_data + request = Rho::Network.get({ + :url => "http://www.example.com/get_data" + }) + + # supposing our server returns valid JSON, we can just relay it to our JavaScript + # otherwise we would parse the response, build our own result value and + if request["status"]=="ok" + result = request["body"] + else + result = {:status => "error"} + end + + + # this is necessary because by default, controllers render their view together with a layout + # in an AJAX request, we only want to return our data formatted as JSON but not the layout + render :string => result.to_json, :use_layout_on_ajax => true + end + +JavaScript: + :::javascript + function perform_json_request() { + $.getJSON("/app/MyController/get_data") + .done(function(data) { + // the response is parsed as JSON and provided as the data parameter + alert("Customer of the day: "+data.customer_of_the_day+" with "+data.total_orders+" orders"); + }); + } + +#### When to use Ruby code as a local proxy + +* In general, if you cannot use the JavaScript Network API, using Ruby code is the preferred option due to its simplicity and the fact that the server does not need to be adapted at all. Any service you can call via HTTP will be accessible to your application. + +### JSONP + +Although the sandbox does not allow AJAX requests to a different origin, it is possible to include ` + +While the page itself can reside on any domain, the script will be loaded from `code.jquery.com` and executed. + +Taking advantage of this fact, we can dynamically create a `"); + } + +When the `"); + } + + function process_values(data) { + // the name of this function matches the callback name specified above + } + +Ruby controller: + :::ruby + def get_data + json = ::JSON.generate({ "key" : "value"}) + jsonp = "#{@params["callback"]}(#{json});" + render :string => jsonp, :use_layout_on_ajax => true + end + +#### When to use JSONP + +The ideal use cases for deciding to implement JSONP are: + +* Invoking services that are already implemented as JSONP: integrating an existing JSONP backend in your RhoMobile app is almost trivial +* When other web applications will also access the same services. JSONP can be implemented once on the server side and then reused across different clients + +**NOTE: Using JSONP comes with some security implications: nothing guarantees that a server actually returns the data you expect instead of malicious code. You should only include scripts (and therefore, JSONP links) from servers that are under your control or that you completely trust. If the backend is compromised, it could return arbitrary JavaScript code to your application, potentially compromising it, too.** + + +### CORS + +Due to limitations with JSONP, a new standard is emerging: Cross Origin Resource Sharing (CORS). CORS has the advantage of having been designed explicitly for the task of making requests across different origins. When the browser notes that the destination is not the same as the origin of the current page and sends an OPTIONS request with an additional `Origin` header: + + + :::code + Origin: http://www.example.com + + +This `Origin` header tells the destination server which domain the request comes from. If the server wants to allow the request, its response will include an `Access-Control-Allow-Origin` header: + + :::code + Access-Control-Allow-Origin: * + +or + + :::code + Access-Control-Allow-Origin: http://www.example.org + +CORS has the advantage that it supports POST as well as other HTTP methods, unlike JSONP which can only make GET requests. + +#### When to use CORS + +* You need to use HTTP methods other than GET +* All your desktop end users have modern browsers. Internet Explorer versions earlier than 10.0 have limitations in their CORS implementation. + +**NOTE: When implementing CORS on your server, receiving an `Origin` header is not, by itself, sufficient guarantee that the request actually came from a user on that site: remember that an attacker can create custom requests outside of a web browser. Do not send any sensitive information without further authentication.** + +## Related reading + +* [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) +* [jQuery.getJSON](http://api.jquery.com/jQuery.getJSON/) +* [Network API](../api/Network) +* [Same-origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) +* [JSONP](http://en.wikipedia.org/wiki/JSONP) +* [CORS W3C Candidate Recommendation](http://www.w3.org/TR/cors/) \ No newline at end of file diff --git a/docs/en/5.5/guide/webapps.md b/docs/en/5.5/guide/webapps.md new file mode 100644 index 00000000..557a49cd --- /dev/null +++ b/docs/en/5.5/guide/webapps.md @@ -0,0 +1,42 @@ +# Adding RhoMobile Capabilities To Your Web Application + +You may wish to add RhoMobile API capabilties to your web application if your client devices are running a RhoMobile Application. + +## Client Choices + +### Standard Browsers +Standard browsers will not provide the added benefit of native application packaging, deployment and management. It will also not allow you to take advantage of the RhoMobile APIs that provide device, system and framework access to your web application + +### RhoMobile Application +Although RhoMobile applications typically involve packaging up all resources and application logic locally with the RhoMobile application, you can build a [RhoMobile Application](creating_a_project) to start running from your web server start page. Although you have to [install](rhomobile-install) and [setup](nativesdksetup) the development environment and build the application for each mobile operating system, you can truly make this application appear like a native application by changing the [application icon, splash screen](app_icon_splash) as well as customize other [build](build_config) and [runtime options](runtime_config). [Follow the typical steps](creating_a_project) for building a RhoMobile Application and then be sure to [change the start_path](#connecting-with-your-web-application) to point to your web app starting URL. + +## Connecting with your web application +To load application files to the RhoMobile application from an external Web server - set `start_path` in `rhoconfig.txt` to point to http:// or https:// protocol URI. `rhoconfig.txt` is a runtime configuration file [Read More](runtime_config) + :::ruby + start_path='http://heroku.com/myapp/index.html' + +## Using RhoMobile JS APIs +The RhoMobile JavaScript API library `rhoapi-modules.js` is needed in order to access RhoMobile 4 JavaScript APIs. This file is provided as part of the installation of RhoMobile Suite: + +* Windows: located in the `[RhoMobile Suite install path]/rhoapi-modules` +* Mac: In the `rhoapi-modules` folder of the RhoMobile Suite DMG package. + +Copy this file to your web server and make sure it is referenced in all pages that wish to use the RhoMobile JavaScript APIs. + +NOTE: This file is universal for all platforms and includes all of the Rhodes and RhoElements extensions and APIs by default. If you wish to customize the contents of include any additional extensions, then you will need to generate the `rhoapi-modules.js` file by creating a RhoMobile application project. + +### Generating rhoapi-modules.js +To generate a universal 'rhoapi-modules.js' you can run a rake command. In order to do this, you will need to have RhoStudio installed. Create a RhoMobile project and then in a command prompt from the project folder, execute the following command: + :::ruby + #platform may be: win32, wm, android, iphone, wp8 + rake update_rho_modules_js[all] + +The `rhoapi-modules.js` file will be located in the projects `\public\api` folder. Copy this file to your webserver application and reference it appropriately. + +NOTE: The `rhoapi-modules.js` file is customized to the `extensions` and `capabilities` section of your `build.yml`. If you do not included the proper settings, the rhoapi-modules.js library may not contain all of the capabilities you are looking for. + +### JS ORM +If you are going to be using the JS ORM API, you'll also need to include this line in any files that will be using it: + + :::html + \ No newline at end of file diff --git a/docs/en/5.5/guide/webcontainer.md b/docs/en/5.5/guide/webcontainer.md new file mode 100644 index 00000000..3383a2fc --- /dev/null +++ b/docs/en/5.5/guide/webcontainer.md @@ -0,0 +1,121 @@ +# Building a RhoMobile Web App Container + +If you have an existing web application and wish to enable hardware features or other RhoMobile APIs, then you will need to create a RhoMobile application and point it to your website. This will allow you to deliver a true native application client experience for your web app as well as enable hardware features that you can't get with standard browsers running on the device. + +Here are the steps that you need to follow + +## 1) Install RhoMobile Suite +In order to create your own RhoMobile web app container, you must first install RhoMobile Suite. This will give you the abiltity to create the application and complete the rest of the steps. + +[Follow the Rhomobile Suite Installation Instruction](rhomobile-install) and then return to this section to continue to the next step. + +## 2) Install the Target Platform's SDK +RhoMobile applications rely on having the target platform SDKs installed on your laptop so that the native runtime container can be built. For example, if you want to build a Android web app container, you will need to have the Android development environment installed and linked to RhoMobile Suite. + +[Follow the instructions for setting up target platforms SDKs](nativesdksetup) and then return to this section to continue to the next step. + +## 3) Create a RhoMobile Application +[Follow the instructions for creating a project](creating_a_project#creating-a-project-with-rhostudio) to create a simple skeleton for a RhoMobile project. You can optionally remove the `public` folder as this contains default JavaScript and CSS files that you will not be using since all of your application files will be running from your web server. + +## 4) Setting the Starting Page +By default this application is configured to start with loclly availble files. You need to change the application so that it starts from your web application instead. Edit the `rhoconfig.txt` file and change the `start_path` parameter to point to the url for your web server. + +For example, if my web application was at http://www.mydomain.com/mywebapp then my `start_path` parameter in `rhoconfig.txt` would look like: + + :::yaml + # startup page for your application + start_path = 'http://www.mydomain.com/mywebapp' + +When this application is launched on the device, it will attempt to connect to this URL. + +## 5) Enabling RhoMobile APIs +By default not all RhoMobile APIs are available to your application. APIs and capabilities are included by defining `extensions` in the `build.yml` file. + +### Default APIs +By default the following APIs are included when building any application: +[Application](../api/Application), [Database](../api/Database), [RhoFile](../api/File), [Log](../api/Log), [NativeMenubar](../api/NativeMenubar), [NativeTabbar](../api/NativeTabbar), [NativeToolbar](../api/NativeToolbar), [Navbar](..api/Navbar), [Network](../api/Network), [Notification](../api/Notification), [Orm](../api/Orm), [OrmModel](..api/OrmModel), [System](../api/system), [Webview](../api/webview) + +These APIs are noted on their individual API reference pages under the extension: `coreapi`. You do not need to specify including this as it will automatically be included + +### Licensed APIs +A group of APIs that are available under the `RhoElements` package require a license. [Read More](licensing) about licensing. + +By including the following extension in the `build.yml` file you will enable the associated set(s) of APIs: + +* `extensions: ["barcode"]' - [Barcode](../api/barcode) +* `extensions: ["cardreader"]' - [CardReader](../api/cardreader) +* `extensions: ["hardwarekeys"]' - [KeyCapture](../api/keycapture) +* `extensions: ["indicators"]' - [Battery](../api/battery), [KeyState](../api/keystate), [SignalIndicators](../api/signalindicators) + +Alternatively, they can all be included by adding the following to your `build.yml` file: + + :::yaml + app_type: "rhoelements" + +Or you can include specific groups by specifying a set of them: + :::yaml + extensions: ["barcode","indicators"] + +### Other APIs not requiring a license +The following APIs are not included by default and can be included by specifying the proper `extension` in the `build.yml`: + +* [MediaPlayer](../api/mediaplayer): `extensions: ["mediaplayer"]` +* [ScreenOrientation](../api/screenorientation): `extensions: ["screenorientation"]` +* [Sensor](../api/sensor): `extensions: ["sensor"]` + +### RhoConnect Capabilities +If you would like your application to include [RhoConnect](../rhoconnect/introduction) capabilities then you will need to include the proper settings in the `build.yml` file: + +* [RhoConnectClient](../api/RhoConnectClient): `extensions: ["rhoconnect-client"]` +* [Push](../api/Push): `extensions: ["rhoconnect-push", "rhoconnect-client"]` as well as `capabilities: ["push"]` needs to be added as a seperate line in the `build.yml` file + + +## 6) Setting Application Name and Branding +If you would like to give you application the true native experience, you should change the default behavior for the application name, icons used, and splash screen + +[Follow the steps in this guide](app_icon_splash) and then return here to continue to the next step. + +## 7) Building the Application +Now that you have configured your application behavior, it is time to build the RhoMobile web app container. Depending on the target platform being used will determine the specific steps that you need to follow. Overall, the goal is to produce an installation package that can run on the target native platform (i.e. .cab for Windows Mobile, .apk for Android, etc) + +Follow the steps for the target platform and return here to contuinue + +* [Build for iOS](build_ios) +* [Build for Android](build_android) +* [Build for Windows Mobile](build_wm) +* [Build for Windows Phone 8](build_wp8) +* [Build for Windows](build_win) + +## 8) Enabling JavaScript on your Web App +Now that you have a RhoMobile Web App container pointed to your web server, you need to configure your web application on your server to enable the RhoMobile JavaScript APIs. In order to do this, you must: + +a) **Generate the `rhoapi-modules.js` file** + +In a command prompt from the RhoMobile project folder [you created](#3-create-a-rhomobile-application), execute the following command: + :::ruby + # optionally change 'all' below to an individual platform + # if your devices are all running on the same platform + # may be: win32, wm, android, iphone, wp8 + rake update_rho_modules_js[all] + + +b) **Copy this file onto your server** + +Typically this will be in the same location you have other JavaScript files. + + +c) **Link to the file** + +From your web application HTML files link to the `rhoapi-modules.js` file you copied to your web server + +For example if you placed `rhoapi-modules.js` in `[webserver app root]\js\` then in your html files you would link to the `rhoapi-modules.js` using: + + :::javascript + + +d) **JS ORM** + +If you are going to be using the JS ORM API, you'll also need to include this line in any files that will be using it: + + :::html + \ No newline at end of file diff --git a/docs/en/5.5/guide/welcome.md b/docs/en/5.5/guide/welcome.md new file mode 100644 index 00000000..e39b1d07 --- /dev/null +++ b/docs/en/5.5/guide/welcome.md @@ -0,0 +1,25 @@ +# Welcome To RhoMobile Suite + +With the right effort, you can create great applications with any tool. But with the right tools, you can do it faster and more often. + +Supported by a thriving, open source community and built around modern coding languages like JavaScript, HTML5 and CSS3, RhoMobile Suite leverages existing web development skills to build feature-rich, native enterprise applications. Styling libraries of advanced widgets and effects are easy to integrate, making it simple to create better-looking, better-working apps. True write-once, run-anywhere capability frees developers from having to tweak code to support additional operating systems. And seamless, out of the box data sync simplifies back-end integration and connects users to business-critical intelligence, whether they're online or off. + +Designed to stay current no matter how quickly technology evolves, RhoMobile Suite keeps your IT team far ahead of the development curve, and puts them closer than ever to creating your next essential app. + +RhoMobile Suite; developer-centered, enterprise-focused, future-ready. With countless ways forward, it’s always what’s next. + + +## RhoStudio +A powerful Eclipse plug-in that allows you to develop, test and debug your RhoMobile applications. Runs on both a Windows PC or Mac and includes RhoSimulator, a device and platform simulator customized for your RhoMobile application development. + +## RhoMobile +RhoMobile is the mobile application container that runs as a true native application but allows you to easily write cross platform code by using common web skills. In addition to supporting standard web languages like JavaScript, HTML, CSS and Ruby, RhoMobile provides device, system and framework access through it's Rhodes and RhoElements API libraries. RhoMobile applications come with a RhoConnect client for easy integration with a RhoConnect application to provide data synchronization. + +### Rhodes +Rhodes is a API library set that is accessible to all RhoMobile applications. It provides access via both JavaScript and Ruby interfaces and allows developers to access device level capabilities like Camera or geolocation. Rhodes is free to use, open-source and developers can contribute to the project. + +### RhoElements +RhoElements is an additional API library set that is accessible to RhoMobile applications and is optimized and customized to run on Zebra Technologies devices. It provides access via both JavaScript and Ruby programming languages and allows developers access to an extended set of device capabilities like Bar Code Scanning and hardware capabilities that are only provided on enterprise level mobile devices. RhoElements also provides a modern Webkit to Windows Mobile/CE platforms. + +## RhoConnect +RhoConnect is a server application that either can be hosted on our system or yours and acts as a seamless bridge for your enterprise data to exist both on your back-end and your mobile device. With RhoConnect, you can simultaneously connect your application to many data sources just as easily as you can connect to one data source — including enterprise back-end customer relationship management (CRM) and enterprise resource planning (ERP) systems, web services, databases and much more. diff --git a/docs/en/5.5/rhoconnect/adapters-crm.md b/docs/en/5.5/rhoconnect/adapters-crm.md new file mode 100644 index 00000000..64c62793 --- /dev/null +++ b/docs/en/5.5/rhoconnect/adapters-crm.md @@ -0,0 +1,231 @@ +CRM adapters +=== + +With rhoconnect-adapters, you can utilize the pre-built set of [RhoConnect](http://rhomobile.com/products/rhoconnect/) applications +for popular CRM backends (SalesForce, Oracle CRM On Demand, Sugar CRM, etc.). Also, this library includes support for writing your own [RhoConnect](http://rhomobile.com/products/rhoconnect/) +CRM applications to extend or customize the default functionality. + +### Generating Standard CRM Application + +To create a standard out-of-the-box rhoconnect CRM application use the following command: + + $ rhoconnect-adapters crmapp + +Here, the \ parameter specifies the CRM backend that your application will use. +Currently, the following CRM backends are supported: + + - MsDynamics (for [Microsoft Dynamics CRM](http://www.microsoft.com/en-us/dynamics/default.aspx)) + - Salesforce (for [Salesforce CRM](http://www.salesforce.com/)) + +Also, you can generate the application for the following backends but they are not officially supported +(initial test and development has been done, but currently there is no on-going test support): + + - OracleOnDemand (for [Oracle CRM On Demand](http://crmondemand.oracle.com)) + - Sugar (for [Sugar CRM](http://www.sugarcrm.com/crm/)) + + +The generated Rhoconnect CRM application structure will include typical [RhoConnect](http://rhomobile.com/products/rhoconnect/) +files (for example, application.rb and settings.yml). It will also create a special vendor directory `vendor/\` +containing all support files specific for the corresponding CRM backend. + +By default, the Rhoconnect CRM application will be generated with four standard source adapters corresponding +to the following CRM objects: + + - Account + - Contact + - Lead + - Opportunity + + +### Generating CRM Application without pre-built source adapters + +In some cases, it is necessary to generate an application without any standard sources. +For this purpose, use the `--bare` option to generate just the application's skeleton. + + rhoconnect-adapters crmapp --bare + + +### Generating CRM source adapters for the Rhoconnect CRM application + +Once you create your Rhoconnect CRM application, you can generate the desired source adapters +based on the CRM objects by typing the following command in your application's directory: + + rhoconnect-adapters crmsource + +Here, \ must exactly correspond to the name of the CRM object you're trying to +build the source adapter for. + +## Preparing the Rhoconnect CRM Application + +### OracleOnDemand settings +All OracleOnDemand-specific settings are located in the `vendor/oracle_on_demand/settings` directory. +In the file `settings.yml` you'll find the entries that you must customize before running the app. +These are: + +- **:oraclecrm_service_url:** - substitute the default URL with your OracleOnDemand account URL. + +For every source adapter based on CRM object there is a corresponding *'vendor/oracle_on_demand/settings/\.yml'* +file containing the descriptions for the OracleOnDemand CRM object. +Every CRM object file has the following entries: + + Query_Fields: hash of the objects's fields + (each field's element has the value + in a form of the hash with the field's options , + containing the following data): + Label => - display name of the field + Type => - type of the field data + (textinput, textarea, Picklist, id, etc.) + + NonQuery_MappingWS_Fields: object's fields that can not be used + in OracleCRM Queries + (however, Oracle returns them in GetMapping API) + + StaticPickList: Normally, all picklist fields are queried + for the allowed values using GetPicklistValues API + However, for certain fields OracleCRM API + returns the error 'not a valid picklist' + This entry is a workaround for this error - + fields's picklist values are statically hard-coded here. + + ObjectFields: this one specifies a hash of fields + that are actually references to other objects. + For example, AccountName field for Contact object + is really a reference to the corresponding Account object.' + + TitleFields: this setting specifies an array of fields + used in constructing the object's title in the 'Show' page + using the Metadata method. Typically, you will want to put + `name` fields in here. + +For the default generated CRM object adapters, this file is pre-filled with information. However, you can customize it by including or excluding +options. For custom adapters, you need to fill this file with relevant information. List of object's fields, for example, can be obtained +from the Oracle CRM On Demand documentation and then later used to fill the Query_Fields setting. Alternatively, user can customize the adapter and obtain +the list of fields using the GetMapping API. + + +### MsDynamics settings +All MsDynamics-specific settings are located in the **'vendor/ms_dynamics/settings'** directory. +In the file *'settings.yml'* you'll find the entries that are necessary to customize before running the app. +These are: + +- **:msdynamics_ticket_url:** - substitute the default URL with your MsDynamics account URL. + +For every source adapter based on CRM object there is a corresponding *'vendor/msdynamics/settings/\.yml'* +file containing the descriptions for the Sugar CRM object. +Every CRM object file has the following entries: + + Query_Fields: hash of the objects's fields + (each field's element has the value + in a form of the hash with the field's options , + containing the following data): + Label => - display name of the field + Type => - type of the field data + (textinput, textarea, Picklist, id, etc.) + + AttributeTypePicklists: this is a hash of picklist arrays + for artificially constructed fields + that are really represent some other field's type + for example, `customerid` field can be either + `account` or `contact`. In this case + field `customertype_attrtype` will represent `customerid` field's type + and will take values from the `AttributeTypePicklists` + array for the field `customerid_attrtype` + + ObjectFields: this one specifies a hash of fields + that are actually references to other objects. + For example, `account_name` field for Contact object + is really a reference to the corresponding Account object. + + TitleFields: this setting specifies an array of fields + used in constructing the object's title in the 'Show' page + using the Metadata method. Typically, you will want to put + `name` fields in here. + +For the default generated CRM object adapters, this file is pre-filled with information. However, you can customize it by including or excluding +options. For custom adapters, you need to fill this file with relevant information. List of object's fields, for example, can be obtained +from the MsDynamics documentation and then later used to fill the Query_Fields setting. Alternatively, user can customize the adapter and obtain +the desired list of object's fields using the MsDynamics SOAP API. + +### Sugar settings +All Sugar-specific settings are located in the **'vendor/sugar/settings'** directory. +In the file *'settings.yml'* you'll find the entries that are necessary to customize before running the app. +These are: + +- **:sugarcrm_uri:** - substitute the default URL with your OracleOnDemand account URL. +- **:debug_enabled:** - enable debug output of the backend HTTP transactions. + +For every source adapter based on CRM object there is a corresponding *'vendor/sugar/settings/\.yml'* +file containing the descriptions for the Sugar CRM object. +Every CRM object file has the following entries: + + Query_Fields: hash of the objects's fields + (each field's element has the value + in a form of the hash with the field's options , + containing the following data): + Label => - display name of the field + Type => - type of the field data + (textinput, textarea, Picklist, id, etc.) + + ObjectFields: this one specifies a hash of fields + that are actually references to other objects. + For example, `account_name` field for Contact object + is really a reference to the corresponding Account object. + + TitleFields: this setting specifies an array of fields + used in constructing the object's title in the 'Show' page + using the Metadata method. Typically, you will want to put + `name` fields in here. + +For the default generated CRM object adapters, this file is pre-filled with information. However, you can customize it by including or excluding +options. For custom adapters, you need to fill this file with relevant information. List of object's fields, for example, can be obtained +from the SugarCRM documentation and then later used to fill the Query_Fields setting. Alternatively, user can customize the adapter and obtain +the desired list of object's fields using the SugarCRM REST API. + +### Salesforce settings +All Salesforce-specific settings are located in the `vendor/salesforce/settings` directory. +In the file `settings.yml` you'll find the entries that you must customize before running the app. +These are: + +- **:salesforce_login_url:** - Currently, this parameter is pre-defined to +`https://login.salesforce.com/services/Soap/c/22.0` for simple SOAP web service authentication. +Rhoconnect-adapters is not using `OAuth2` scheme at this point. + +For every source adapter based on CRM object there is a corresponding *'vendor/salesforce/settings/\.yml'* +file containing the descriptions for the SalesForce CRM object. +Every CRM object file has the following entries: + + Query_Fields: hash of the objects's fields + (each field's element has the value + in a form of the hash with the field's options , + containing the following data): + Label => - display name of the field + Type => - type of the field data + (textinput, textarea, Picklist, datetime, id, etc.) + + ObjectFields: this one specifies a hash of fields + that are actually references to other objects. + For example, AccountId field for Contact object + is really a reference to the corresponding Account object.' + + TitleFields: this setting specifies an array of fields + used in constructing the object's title in the 'Show' page + using the Metadata method. Typically, you will want to put + `name` fields in here. + +For the default generated CRM object adapters, this file is pre-filled with sample information. However, you can customize it by including or excluding +different fields. For custom adapters, you need to fill this file with relevant information. List of object's fields, for example, can be obtained +from the Salesforce documentation and then later used to fill the Query_Fields setting. Alternatively, user can customize the adapter and obtain +the list of fields using the `/sobjects//describe/` API. + + +## Running the CRM Application +Once your Rhoconnect application is customized and ready to run, you can start it like any other Rhoconnect app. +Type the following command in the CRM application's root directory: + + rake rhoconnect:start + + +## Meta +Created and maintained by Rhomobile Inc. + +Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/adapters-intro.md b/docs/en/5.5/rhoconnect/adapters-intro.md new file mode 100644 index 00000000..86c79cb3 --- /dev/null +++ b/docs/en/5.5/rhoconnect/adapters-intro.md @@ -0,0 +1,18 @@ +RhoConnect Adapters Introduction +=== + +rhoconnect-adapters is a ruby library containing a collection of the out-of-box [RhoConnect](http://rhomobile.com/products/rhoconnect) applications +for various needs. + +## Setup +Install the 'rhoconnect-adapters' gem by using the following command: + + $ [sudo] gem install rhoconnect-adapters + + +## Usage +The 'rhoconnect-adapters' command creates pre-built [RhoConnect](http://rhomobile.com/products/rhoconnect/) applications. +Visit the [RhoConnect](http://rhomobile.com/products/rhoconnect/) website for more information. + + +image diff --git a/docs/en/5.5/rhoconnect/async-jobs.md b/docs/en/5.5/rhoconnect/async-jobs.md new file mode 100644 index 00000000..5b46f509 --- /dev/null +++ b/docs/en/5.5/rhoconnect/async-jobs.md @@ -0,0 +1,69 @@ +Adapter Jobs with Resque +=== + +RhoConnect uses the [resque](http://github.com/defunkt/resque) library for managing and executing asynchronous jobs. Using async jobs are especially useful when your application requires processing large amounts of data, pinging devices using the built-in push support, or you just want to perform some task that will take a long period of time. + +## Async Job Types +RhoConnect supports three job types: BulkDataJob, PingJob, SourceJob + +### BulkDataJob +[Bulk Data](bulk-sync) jobs are used by RhoConnect to prepare the [bulk sync data files](bulk-sync#data-files). These jobs are automatically queued by the RhoConnect application, so it is not necessary to queue them manually. + +### PingJob +Ping jobs are used to execute a [device ping](push). A PingJob can be queued from anywhere in your RhoConnect application (i.e. at the end of another job or adapter query method). + +Example: + + :::ruby + Resque.enqueue( + PingJob, + { + "user_id" => current_user.login, + "message" => "New products available!", + "badge" => 1, + "sources" => ['Product'] + } + ) + +### SourceJob +Source jobs are used to execute source adapter queues asynchronously. + +To make your source adapters always run asynchronously, define a queue in `settings/settings.yml`: + + :::yaml + Product: + :queue: product + +Then run a resque worker so the job will execute. + +Example that queues a new source adapter job manually: + + :::ruby + Resque.enqueue( + SourceJob, + :query, + APP_NAME, + 'Joe', + 'some-client-id + ) + +## Running Async Jobs +Running RhoConnect jobs requires one or more [resque](http://github.com/defunkt/resque) workers running. For example, to start one resque worker listening for all job queues: + + :::term + $ cd + $ QUEUE=* rake resque:work + +To start multiple workers(in this case 5): + + :::term + $ cd + $ QUEUE=* COUNT=5 rake resque:workers + +For more information on the options available when running resque workers, please refer to the [resque readme](https://github.com/defunkt/resque#readme). + +If you want to run resque workers in daemon mode, we recommend using [nohup](http://en.wikipedia.org/wiki/Nohup), [god](http://github.com/defunkt/resque/tree/master/examples/god/), or [monit](http://github.com/defunkt/resque/tree/master/examples/monit): + + :::term + $ mkdir log/; touch log/resque_worker_QUEUE.log # if it doesn't exist + $ nohup QUEUE=* rake resque:work & &> log/resque_worker_QUEUE.log \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/authentication.md b/docs/en/5.5/rhoconnect/authentication.md new file mode 100644 index 00000000..e56e6f03 --- /dev/null +++ b/docs/en/5.5/rhoconnect/authentication.md @@ -0,0 +1,145 @@ +# Device Authentication in RhoConnect +The generated RhoConnect application code includes a file called "application_controller.rb" which contains an implementation for the "login" route. This route is called when a device first connects to the RhoConnect application and provides username/password credentials. + +## Authentication Workflow +The following diagram shows how this authenticate method is called: + + + +## Example +If your back-end service requires authentication, simply add code to the login route and return true if authentication was successful or false to deny access to the application from this device. For example: + + :::ruby + post "/login", :rc_handler => :authenticate do + username = params[:login] + password = params[:password] + success = false + # ... connect to backend using API and authenticate ... + result = do_custom_authentication(username,password) + if result.code == 200 + # save the data for later use in the source adapter + Store.put_value("username:#{username}:token",result.body) + success = true + end + return success + end + +## Changing Login +If your actual user name is different than the username that is input into the client, you can change the username by returning a string instead of true if authentication was successful. + + :::ruby + post "/login", :rc_handler => :authenticate do + username = params[:login] + password = params[:password] + success = false + # ... connect to backend using API and authenticate ... + result = do_custom_authentication(username,password) + if result.code == 200 + new_user = custom_user_mapping(username) + # save the data for later use in the source adapter + Store.put_value("username:#{new_user}:token",result.body) + success = new_user + end + return success + end + +## LDAP Example +The code sample above demonstrates authentication by calling a method you would implement called 'do_custom_authentication' that returns an HTTP response object, however the actual implementation is left as an exercise. If your application needs to connect to LDAP, you can use the following sample code to perform simple authentication: + + :::ruby + require 'net/ldap' + + post "/login", :rc_handler => :authenticate do + username = params[:login] + password = params[:password] + success = false + ldap = Net::LDAP.new + ldap.host = "localhost" + ldap.port = 389 + ldap.auth "cn=#{username},dc=example,dc=com", password + + # we only need to bind to verify successful login + success = true if ldap.bind + + return success + end + +Where the domain component "dc=example,dc=com" is replaced by your domain. For example, the `ldap.auth` code above using "rhomobile.com" would be: + + :::ruby + ldap.auth "cn=#{username},dc=rhomobile,dc=com", password + +This example uses the [net-ldap](https://github.com/RoryO/ruby-net-ldap) gem. To install this gem, run the following: + + :::term + $ [sudo] gem install net-ldap + +For more details about LDAP, please visit [http://www.openldap.org/](http://www.openldap.org/). + +## X509 Example +The code sample below demonstrates using an X509 certificate for authentication. See X509 certificate generation for more information about generating a cert. You can also view a sample project of the code below. + +Inside of your RhoConnect app you can replace the password parameter with a pem file parameter. This parameter is expecting a string formatted for .pem with your certificate followed by your private key. + + :::ruby + + require 'socket' + require 'openssl' + + post "/login", :rc_handler => :authenticate do + username = params[:login] + pem = params[:password] + #assuming pem file has certificate and then private key below in pem format + pem_arr = pem.split("-----END CERTIFICATE-----") + pem_arr[0] << "-----END CERTIFICATE-----" + + socket = TCPSocket.new('my.secureserver.com', 4567) + + ssl_context = OpenSSL::SSL::SSLContext.new + + ssl_context.cert = OpenSSL::X509::Certificate.new(pem_arr[0].strip) + ssl_context.key = OpenSSL::PKey::RSA.new(pem_arr[1].strip) + + ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context) + ssl_socket.sync_close = true + + ca_cert = OpenSSL::X509::Certificate.new(File.open("CA.crt")) + + if ssl_socket.connect + puts "socket connected correctly" + return true + else + puts "socket failed to connect" + return false + end + + end + +A simple Sinatra app listening on port 4567 for connections might look something like this. + + :::ruby + require 'rubygems' + require 'socket' + require 'openssl' + + socket = TCPServer.new('my.secureserver.com', 4567) + + ssl_context = OpenSSL::SSL::SSLContext.new() + ssl_context.cert = OpenSSL::X509::Certificate.new(File.open("server.crt")) + ssl_context.key = OpenSSL::PKey::RSA.new(File.open("server.key")) + + ca_cert = OpenSSL::X509::Certificate.new(File.open("CA.crt")) + + ssl_socket = OpenSSL::SSL::SSLServer.new(socket, ssl_context) + + + loop do + connection = ssl_socket.accept + Thread.new { + begin + #do something + rescue + $stderr.puts $! + end + } + end \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/benchmarks-running.md b/docs/en/5.5/rhoconnect/benchmarks-running.md new file mode 100644 index 00000000..e41f8547 --- /dev/null +++ b/docs/en/5.5/rhoconnect/benchmarks-running.md @@ -0,0 +1,147 @@ +Running RhoConnect Benchmarks +=== + +## Introduction + +You can execute benchmark tests against your deployment and verify the performance of your Rhoconnect application using the provided `rhoconnect-benchmark` command. +During the test the Rhoconnect benchmark framework will dynamically create a special ephemeral source adapter inside of +your application and perform the 5-step query use-case mimicking the typical device-to-server communication. + +Currently, the Rhoconnect Benchmark measures two primary system-wide metrics: Average Time and Throughput. + +- Average time (milliseconds per request) is calculated as sum_of_executed_http_request_times/number of http requests. +- Throughput is an integral metric (number of requests per second) calculated as: cumulative_number_of_http_requests_processed/(finish_time_for_last_test - start_time_of_first_test). + +NOTE: Both metrics implicitly include the network latency and therefore represent the performance of the whole system `device-network-server`. + +## Rhoconnect Benchmark Command + +To execute the Rhoconnect Benchmark test, use the `rhoconnect-benchmark` command. This command has the following options: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                              -u--url URLUse URL to specify the targeted Rhoconnect server for benchmarking. If this option is not specified, http://localhost:9292 will be used as a default.
                                                                              -p--payload NUMBERThis options specifies the amount of data to be simulated in the query request (in number of records). Default: 100, which roughly translates into 20 kilobytes.
                                                                              -C--nclients NUMBERSpecifies how many concurrent clients to emulate during the test. If this option is omitted, then the number of simulated clients will be determined based on the number of available seats in your Rhoconnect application's license.
                                                                              -R--niterations NUMBERSpecifies how many times each emulated client will perform the test. Default: 10. The more iterations you specify, the more time your test will take, but it will lessen the test result's statistical fluctuations.
                                                                              -S--save PATHThis option saves the test results in the PATH sub-directory and run the post-processing on the saved files (for example, generate the EXCEL spreadsheet). All the results will be saved under the PATH root directory.
                                                                              -x--maxpayloadloops NUMBERThis option runs several tests in a loop varying the payload between 1 and NUMBER. The specified interval will be split by 10. For example: -m 500 will produce 10 test executions , first for payload of 1 record, then - for 56, 112, 167, 223, 278, 334, 389, 445, and 500
                                                                              -m--maxclientloops NUMBERThis option runs several tests in a loop varying number of concurrent clients between 1 and NUMBER. The specified interval will be split by 5. For example: -m 10 will produce 5 test executions , first for 1 client, then - for 3, 6, 8, and 10
                                                                              -S--simtime NUMBERThis option allows to enforce NUMBER of seconds delay in the source adapter, thus simulating the backend communication round-trip.
                                                                              -A--advancedThis convenience option combines -m 10, -x 500, and -S - thus running a matrix of tests varying in payload and number of concurrent clients. Also, it saves the results into the `bench_results` subdirectory and runs the available post-processing.
                                                                              -D--distributed AWSFILEThis option executes the advanced benchmark test using the remote AWS EC2 clients. Currently, this option is only available for the Linux/MacOS machines. See Distributed Benchmark section below for details.
                                                                              + +## Result post-processing +By default, all results are displayed in the console during the test. However, it is possible to save all the results into the file and, additionally, generate the EXCEL files and/or PNG images using the `--save PATH` option. The results are saved for two benchmark metrics: Average Time and Throughput. + +### Generate EXCEL spreadsheet +To enable the automatic generation of the EXCEL spreadsheets from the test results, please install the `spreadsheet` gem by using: + + :::term + $ [sudo] gem install spreadsheet + +You can read more about the `spreadsheet` gem [here](http://rubygems.org/gems/spreadsheet). + +### Generate PNG images +To enable the automatic generation of the PNG images from the test results, install the `gruff` gem. +Installation of the GRUFF gem requires an additional installation of several components. +Use [this](http://nubyonrails.com/pages/gruff) guide to install the GRUFF on your machine. + +## Distributed Benchmark test +To fully simulate the distributed nature of the device-to-server system, the Rhoconnect Benchmark command allows to you to create distributed clients through the [AWS Cloud Formation](http://aws.amazon.com/cloudformation/). + +NOTE: Distributed Rhoconnect Benchmark test will be executed via the AWS Cloud Formation and EC2 services using your account and therefore you will be billed for its usage by Amazon. + +In order to run the distributed Benchmark test, you need to have an AWS account and specify its settings in a YAML file, which should have the following structure: + + :::ruby + :default: + :region: desired_aws_region + :aws_access_key_id: your_aws_account_key_id + :aws_secret_access_key: your_aws_account_secret_access_key + :aws_key_pair_name: your_aws_ec2_security_key_pair + :aws_ssh_pem_file: location_of_your_aws_ssh_pem_file + +Here is the description of each entry in the AWS settings file: + + + + + + + + + + + + + + + + + + + + + + +
                                                                              :regionSpecify the desired AWS region for your EC2 clients. Default is 'us-west-1'. Typically, you need to specify the same region as the location of your Rhoconnect server to minimize the network impact (since communications between different regions will take more time).
                                                                              :aws_access_key_idYour AWS access key ID.
                                                                              :aws_secret_access_keyYour AWS secret access key.
                                                                              :aws_key_pair_nameIn order to create EC2 clients, you will need to create EC2 KeyPair in the desired region. After that KeyPair is created, you will have its name, which should be specified here.
                                                                              :aws_ssh_pem_fileFor the above KeyPair, you will have the corresponding keypair .PEM file. Download this file to your machine and reference its location here.
                                                                              + +Once the AWS settings file is created, you need to make sure that the following gems are installed on your machine: + +- fog +- net-ssh-multi + +You can install those gems using the `[sudo] gem install ` command. + +Once all the pre-requisites are met, you can run the distributed Rhoconnect Benchmark test with the following command: + + :::term + $ rhoconnect-benchmark -u `server_url` -D `path_to_aws_settings_file` + + +NOTE: In order to run the distributed Benchmark test, you must provide public server's URL accessible from the outside clients. + + + + diff --git a/docs/en/5.5/rhoconnect/benchmarks.md b/docs/en/5.5/rhoconnect/benchmarks.md new file mode 100644 index 00000000..bab4e0f2 --- /dev/null +++ b/docs/en/5.5/rhoconnect/benchmarks.md @@ -0,0 +1,272 @@ +RhoConnect Benchmarks +=== + +Note, these numbers reflect synchronization performance using the rhoconnect bench utilities (see the rhoconnect/bench folder for more information). +We will be adding more results as we test across different server environments. + +## Single-core Amazon EC2 server environment + +### Configuration + +Servers configuration (Amazon EC2 'm1.small' instances) : + +* CPU Units - 1 ECU + +* CPU Cores - 1 Core + +* Memory - 1.7GB + +* Platform - Ubuntu (2.6.38-8-virtual) + +Environment (instance #1): + +* Nginx 1.0.0 + +* Ruby 1.8.7 (2011-02-18 patchlevel 334) [i686-linux], Ruby Enterprise Edition 2011.03 + +* Passenger 3.0.7 (mod_rails) + +* Redis 2.2.11 + +* Rhoconnect 3.0.0 + +Nginx configuration file: + +
                                                                              +user  www-data;
                                                                              +worker_processes  4;
                                                                              +
                                                                              +pid /var/run/nginx.pid;
                                                                              +
                                                                              +events {
                                                                              +    worker_connections  1024;
                                                                              +}
                                                                              +
                                                                              +http {
                                                                              +    passenger_root /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.7;
                                                                              +    passenger_ruby /usr/local/bin/ruby;
                                                                              +    passenger_max_pool_size 20;
                                                                              +    include       mime.types;
                                                                              +    default_type  application/octet-stream;
                                                                              +
                                                                              +    sendfile    on;
                                                                              +    tcp_nopush  on;
                                                                              +    tcp_nodelay on;
                                                                              +
                                                                              +    keepalive_timeout  65;
                                                                              +
                                                                              +    gzip  on;
                                                                              +
                                                                              +    server {
                                                                              +        listen 80;
                                                                              +        server_name  ec2-50-18-72-186.us-west-1.compute.amazonaws.com;
                                                                              +        root  /var/www/benchapp/public;   # Bench application #1
                                                                              +        # root  /var/www/blobapp/public;   # Bench application #2
                                                                              +        passenger_enabled on;
                                                                              +        passenger_min_instances 6;
                                                                              +    }
                                                                              +}
                                                                              +
                                                                              + + +Environment (instance #2): + +* Ruby 1.8.7 (2011-02-18 patchlevel 334) [i686-linux], Ruby Enterprise Edition 2011.03 + +* Rhoconnect 3.0.0 code with bench scripts + + +Server instance #1 is running rhoconnect bench applications, +the 2nd one executes rhoconnect bench scripts. + +### Bench application #1 (benchapp) +* Simulates creating multiple objects + +* 100 concurrent users + +* 1 device per user + +* 20 object dataset + +* each object has 7 attributes + +* 904 total HTTP requests + +
                                                                              +Request clientcreate   : min: 0.0069, max: 1.6010, avg: 0.3404
                                                                              +Request ack-cud        : min: 0.0339, max: 3.2250, avg: 0.5910
                                                                              +Request clientlogin    : min: 0.0063, max: 0.8138, avg: 0.1216
                                                                              +Request get-cud        : min: 0.0315, max: 3.0044, avg: 0.3988
                                                                              +Request create-object  : min: 0.0791, max: 4.4959, avg: 1.3521
                                                                              +Throughput(req/s)      : 7.13629650622702
                                                                              +Throughput(req/min)    : 428.177790373621
                                                                              +
                                                                              + +### Bench application #2 (blobapp) +* Simulates creating multiple objects + +* 100 concurrent users + +* 1 device per user + +* 10 object dataset + +* each object has variable number of attributes (from 10 to 60) + image + +* 904 total HTTP requests + +
                                                                              +Request clientcreate   : min: 0.0067, max: 2.9286, avg: 0.6870
                                                                              +Request ack-cud        : min: 0.0473, max: 5.5015, avg: 1.6219
                                                                              +Request clientlogin    : min: 0.0061, max: 3.2326, avg: 0.4687
                                                                              +Request get-cud        : min: 0.0382, max: 7.2202, avg: 1.0975
                                                                              +Request create-object  : min: 0.3765, max: 11.1387, avg: 5.1424
                                                                              +Throughput(req/s)  : 7.22833609137099
                                                                              +Throughput(req/min): 433.700165482259
                                                                              +
                                                                              + +### Prepare bench applications for running on server #1 + +Go to rhoconnect/bench directory and configure benchapp application: + +
                                                                              +sudo cp -R benchapp /var/www/
                                                                              +cd /var/www/
                                                                              +sudo mkdir benchapp/public
                                                                              +sudo chown -R www-data:www-data benchapp/
                                                                              +
                                                                              + +Do the same for blobapp bench: +
                                                                              +sudo cp -R blobapp /var/www/
                                                                              +cd /var/www/
                                                                              +sudo mkdir blobapp/public
                                                                              +sudo chown -R www-data:www-data blobapp/
                                                                              +
                                                                              + +Edit Nginx configuration file, set server_name and root properties to public DNS server name +and bench application public folder respectively. After restarting server make sure that bench application is +running by visiting its web console, i.e. : +
                                                                              +http://server_dns_public_name/console/ 
                                                                              +
                                                                              + +### How to execute bench scripts on server #2 +Before running bench scripts you need configure bench application settings properly. + +Edit rhoconnect/bench/benchapp/settings/settings.yml and set redis and syncserver properties: +
                                                                              +:development:
                                                                              +  :licensefile: settings/license.key
                                                                              +  :redis: server_ip_address:6379
                                                                              +  :syncserver: http://server_dns_public_name:80/api/application/
                                                                              +
                                                                              + +Do the same for blobapp settings.yml file. + +Then from rhoconnect/bench directory execute run_cud_script.sh and run_blob_script.sh scripts respectively. + +## Multi-core Amazon EC2 server environments + +### Configuration + +Server configurations: + +* Large (m1.large, 2 cores, 7.5GB memory) + +* Extra Large (m1.xlarge, 4 cores, 15GB memory) + +* High-CPU Extra Large (c1.xlarge, 8 cores, 7GB memory) + +* Platform - Basic 64-bit Amazon Linux AMI 2011.09 (Red Hat based) + +Software environment: + +* Nginx 1.0.6 + +* Ruby 1.8.7 (2011-02-18 patchlevel 334) [i686-linux], Ruby Enterprise Edition 2011.03 + +* Passenger 3.0.9 + +* Redis 2.2.14 + +* Rhoconnect 3.0.0 + +All above software are installed on servers by executing the following commands: +
                                                                              +sudo yum install make patch gcc-c++ zlib-devel curl-devel pcre-devel readline-devel openssl-devel
                                                                              +sudo rpm -i rhoconnect-3.0.0.noarch.rpm
                                                                              +
                                                                              + +### Tested bench application (benchapp) + +* Simulates creating multiple objects + +* 100 concurrent users + +* 1 device per user + +* 20 object dataset + +* each object has 7 attributes + +### Prepare bench application for running on servers + +1. Go to rhoconnect/bench directory and configure benchapp application: +
                                                                              +sudo cp -R benchapp /opt/nginx/html
                                                                              +cd /opt/nginx/html/benchapp
                                                                              +sudo /opt/rhoconnect/bin/bundle install --without=test development
                                                                              +sudo mkdir public
                                                                              +sudo chown -R nginx:nginx /opt/nginx/html/benchapp
                                                                              +   
                                                                              + +2. Edit '/opt/nginx/conf/conf.d/rhoconnect.conf' file and point root entry to /opt/nginx/html/benchapp/public directory: +
                                                                              +server {
                                                                              +  listen      80;
                                                                              +  root  /opt/nginx/html/benchapp/public;
                                                                              +  passenger_enabled on;
                                                                              +}
                                                                              +   
                                                                              + +3. Start redis and nginx servers: +
                                                                              +sudo /etc/init.d/redis start
                                                                              +sudo /etc/init.d/nginx start
                                                                              +   
                                                                              + +### Benchmark results for large (2 cores) server +
                                                                              +Request clientcreate   : min: 0.0058, max: 1.0360, avg: 0.1138, err: 0, verification err: 0
                                                                              +Request ack-cud        : min: 0.0258, max: 0.1998, avg: 0.0642, err: 0, verification err: 0
                                                                              +Request clientlogin    : min: 0.0056, max: 0.0958, avg: 0.0128, err: 0, verification err: 0
                                                                              +Request get-cud        : min: 0.0234, max: 0.1777, avg: 0.0476, err: 0, verification err: 0
                                                                              +Request create-object  : min: 0.0526, max: 0.3074, avg: 0.1242, err: 0, verification err: 0
                                                                              +Throughput(req/s)  : 8.40951725551376
                                                                              +Throughput(req/min): 504.571035330826
                                                                              +
                                                                              + +### Benchmark results for extra large (4 cores) server +
                                                                              +Request clientcreate   : min: 0.0080, max: 1.0194, avg: 0.0944, err: 0, verification err: 0
                                                                              +Request ack-cud        : min: 0.0298, max: 0.1381, avg: 0.0573, err: 0, verification err: 0
                                                                              +Request clientlogin    : min: 0.0091, max: 0.0591, avg: 0.0152, err: 0, verification err: 0
                                                                              +Request get-cud        : min: 0.0259, max: 0.1679, avg: 0.0443, err: 0, verification err: 0
                                                                              +Request create-object  : min: 0.0618, max: 0.2778, avg: 0.1112, err: 0, verification err: 0
                                                                              +Throughput(req/s)  : 8.19117682939103
                                                                              +Throughput(req/min): 491.470609763462
                                                                              +
                                                                              + +### Benchmark results for high-cpu extra large (8 cores) server +
                                                                              +Request clientcreate   : min: 0.0083, max: 1.0162, avg: 0.0741, err: 0, verification err: 0
                                                                              +Request ack-cud        : min: 0.0277, max: 0.1803, avg: 0.0525, err: 0, verification err: 0
                                                                              +Request clientlogin    : min: 0.0092, max: 0.0681, avg: 0.0147, err: 0, verification err: 0
                                                                              +Request get-cud        : min: 0.0259, max: 0.1729, avg: 0.0474, err: 0, verification err: 0
                                                                              +Request create-object  : min: 0.0599, max: 0.2850, avg: 0.1102, err: 0, verification err: 0
                                                                              +Throughput(req/s)  : 8.08355941878833
                                                                              +Throughput(req/min): 485.0135651273
                                                                              +
                                                                              + +All above results produced by bench script cud_script hosted by large (2 cores) EC2 server. \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/blob-sync.md b/docs/en/5.5/rhoconnect/blob-sync.md new file mode 100644 index 00000000..6b5dab6f --- /dev/null +++ b/docs/en/5.5/rhoconnect/blob-sync.md @@ -0,0 +1,148 @@ +Binary Objects and Blob Sync +=== +Synchronizing images or binary objects between RhoConnect and the client is declared by having a 'blob attribute' on the [Rhom model](../guide/local_database). This instructs the client to download the blob attribute's value (in this case a url) separately from the rest of the data and save it to the device file system. + +**NOTE: The example below shows how to synchronize an image created by the device's camera, but could be applied to any arbitrary files on the device.** + +## Synchronizing from Device to RhoConnect +Suppose you have a [Rhom model](../guide/local_database) called "Image" and you have a [camera callback function](../guide/camera) defined in the Rhodes Image model's controller: + + :::ruby + def camera_callback + if @params['status'] == 'ok' + #create image record in the DB + image = Image.new({'image_uri'=>@params['image_uri']}) + image.save + SyncEngine.dosync + end + #reply on the callback + render :action => :ok, :layout => false + end + +When this is executed in a Rhodes application: + +* This callback triggers a sync after saving saving an image. + +* Then Rhodes will push the image file to the RhoConnect application by HTTP POST. + +* `image.rb#store_blob` is called for pre-processing of the file. +NOTE: You must implement this method inside of your Source Adapter Model and do not use the tempfile provided by Rack, because RhoConnect processing is asynchronous and there is no guarantee that the temporary file will exist at the actual time when `create` is called. + +The following example stores the file permanently and keeps its `:filename` argument as another object attribute. + + :::ruby + def store_blob(obj,field_name,blob) + # ... custom code to store the blob file ... + my_stored_filename = do_custom_store[blob[:filename]] + obj['filename'] = my_stored_filename + end + +* The RhoConnect source adapter model tied to this Rhom model processes the blob in the `create` method. + +The following example takes the blob and stores it in S3: + + :::ruby + def create(create_hash) + # this would be a blob attribute, points to a tempfile + # containing the raw post data + name = create_hash["image_uri"] + # filename we saved in application.rb#store_blob method + basename = create_hash["filename"] + S3Object.store( + basename, + open(name), + @bucket, + :access => :public_read + ) + basename #=> object id here is the filename + end + +In this example, we store the image blob to s3 so we can query it later. See the "image" source adapter that comes with [the rhodes-samples-server](https://github.com/rhomobile/rhodes-samples-server/blob/master/sources/image.rb). + +## Query for Blobs in the Source Adapter Model + +In your query call, you should store the URL to images in the blob attribute so that the device can fetch the image when it synchronizes. + + :::ruby + def query(params=nil) + @result={} + Bucket.find(@bucket).objects.each do |entry| + new_item = { + 'image_uri-rhoblob' => @baseurl+@bucket+'/'+File.basename(entry.key) + } + @result[entry.key] = new_item + end + @result + end + +Here we save the image URL to an attribute `image_uri-rhoblob`. This will correspond to the `image_uri` attribute in our Rhom model above. + +**NOTE: In order for Rhodes to automatically recognize a blob attribute, the attribute name must end with "-rhoblob". In the above example, `image_uri` was our Rhom attribute, so our source adapter model assigned `image_uri-rhoblob` with the blob URL.** + +### Blob file name and extension on client +File name is generated on client when downloading. File extension is determine by: + +* To specify blob file extension add extension parameter to the blob URL. For example: '&extension=jpg' +* If no extension parameter the blob URL then extension is extracted from blob URL itself(looking for '.' from the end of the URL) +* If still no file extension found, then '.bin' is used + +A complete image source adapter model that stores files in S3 might look like: + + :::ruby + require 'aws/s3' + class Image < Rhoconnect::Model::Base + include AWS::S3 + + + def initialize(source,credential) + AWS::S3::Base.establish_connection!( + :access_key_id => ENV['AMAZON_ACCESS_KEY_ID'], + :secret_access_key => ENV['AMAZON_SECRET_ACCESS_KEY'] + ) + @baseurl = 'http://s3.amazonaws.com/' + @bucket = 'rhodes-samples-images' + super(source,credential) + end + + def query(params=nil) + @result={} + Bucket.find(@bucket).objects.each do |entry| + new_item = { + 'image_uri-rhoblob' => @baseurl+@bucket+'/'+File.basename(entry.key) + } + @result[entry.key] = new_item + end + @result + end + + def create(create_hash) + puts "Creating: #{create_hash.inspect}" + name = create_hash["image_uri"] + basename = create_hash["filename"] + S3Object.store( + basename, + open(name), + @bucket, + :access => :public_read + ) + basename + end + + def delete(delete_hash) + puts "Removing: #{delete_hash.inspect}" + S3Object.delete delete_hash['id'], @bucket + end + + def store_blob(obj,field_name,blob) + # ... custom code to store the blob file ... + my_stored_filename = do_custom_store(blob) + obj['filename'] = my_stored_filename + end + + def do_custom_store(blob) + S3Object.store(blob[:filename], blob[:tempfile], @bucket) + end + end + +## Rhodes Sample Code +See controller and view in the [app/Blob directory](https://github.com/rhomobile/rhodes-system-api-samples/tree/master/app/Blob) of the [System API Samples application](http://github.com/rhomobile/rhodes-system-api-samples/tree/master) for a complete Rhodes code sample. \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/bulk-sync.md b/docs/en/5.5/rhoconnect/bulk-sync.md new file mode 100644 index 00000000..94df1cf2 --- /dev/null +++ b/docs/en/5.5/rhoconnect/bulk-sync.md @@ -0,0 +1,136 @@ +Bulk Sync +=== +During the initial sync process in your application, you may need to deliver a large number of objects. This may result in many megabytes of data being sent to the device. In this case, incremental synchronization may take a while to complete since it uses JSON as the wire format. To significantly speed up this process you may use RhoConnect's "bulk sync" feature. + +## Bulk Sync Process + +If and when the Rhodes application issues a request to get bulk data, the RhoConnect application will do following: + +* Queue a [resque background job](http://github.com/defunkt/resque) which will run the bulk sync process. + +* Execute the ['login,'query','logoff' methods](source-adapters#source-adapter-api) of all source adapter models matching the [requested data partition](source-adapters#data-partitioning) to get latest set of objects from the backend service + +* Generate appropriate database files for the device. RhoConnect will generate sqlite files for iOS, Android, and Windows Mobile clients (if enabled). + +* The Rhodes application will poll RhoConnect for the bulk sync job to finish. Once the job is finished, the files are generated and Rhodes will download and install them to the device. + +* After bulk database is installed, Rhodes application will analyze sources for references to remote blob objects. Each remote blob object will be downloaded to device, and if download is successful, remote references will be updated to local ones. + +**NOTE: Be cautious using this in your application - any previous set of objects on the device will be replaced with the latest set from the backend service.** + +Once the bulk data sync process is complete for a source, you may continue to synchronize sources using the default incremental sync process. However, the default sync process may be disabled for a source by setting its `sync_type` to 'bulk_sync_only'. This will save space in your redis database if you don't plan on using incremental sync for this source. + +For example, your settings/settings.yml might have: + + :::yaml + :sources: + Product: + poll_interval: 300 + Customer: + poll_interval: 300 + sync_type: bulk_sync_only + +## Setup + +### Setup DB Library +Bulk sync prepares database files inside of a job, therefore it needs access to sqlite3's ruby library. To enable this library, uncomment or add the following line to your RhoConnect app's Gemfile: + + :::ruby + gem 'sqlite3', ">= 1.3.3", :platforms => [:ruby, :mswin, :mingw] + +Then install the gem: + + :::term + $ bundle install + +### Enabling Bulk Sync in Rhodes +In the device rhodes application, setting `bulksync_state` to 0 in rhoconfig.txt will trigger bulk sync next time sync is performed: + + bulksync_state = 0 + +After application executed bulk sync it will set `bulksync_state` to 1 and next time sync will happen, it will not execute bulk sync anymore. You may force bulk sync on the next sync cycle by setting `bulksync_state` to 0 again using ruby in your application: + + :::ruby + Rho::RhoConfig.bulksync_state = '0' + +## Data Files + +By default, bulk sync data files will be stored in the application's root folder, under a 'data' directory. When bulk data is requested by the Rhodes application, RhoConnect will return a link to the file if the `bulk_sync_poll_interval` has not expired. If the file is expired, RhoConnect will return a wait command to Rhodes and enqueue another [resque job](http://github.com/defunkt/resque) to generate new bulk data files. By default, the `bulk_sync_poll_interval` is set to 1 hour (3600) seconds and is configurable in `settings.yml`: + + :::yaml + :development: + :redis: localhost:6379 + :licensefile: settings/license.key + :syncserver: http://localhost:9292/application/ + :bulk_sync_poll_interval: 3600 + +## Bulk Sync Associations + +Sometimes your bulk data is not simply a collection of separate sources, but they are linked together through associations. For these purposes +RhoConnect uses the notation of `belongs_to` association. The `belongs_to` association is a natural way to express hasOne and hasMany associations. In the case of bulk sync, data `belongs_to` relationship includes a list of all dependent objects for model(s) and helps resolve dependency issues during bulk sync process. + +Associations are defined in your RhoConnect application's `settings/settings.yml` file. + +For example, you can have a list of customers who have purchased a product, and thus you can have them belong to that product: + + :::yaml + :sources: + :Product: + :poll_interval: 600 + :partition_type: app + :sync_type: bulk_sync_only + :Customer: + :poll_interval: 300 + # ... + belongs_to: + - :product_id: 'Product' + +`belongs_to` format is an array of attribute/source_name pairs. It can be polymorphic and define associations across multiple sources: + + :::yaml + belongs_to: + - :parent_id, 'Product' + - :parent_id, 'Cases' + +Bulk Sync Associations are similar to [Rhom Sync Associations](../guide/rhom_ruby#associations) and both should be considered together +if you are planning to use bulk sync data. + +## Using Bulk Sync with Fixed Schema Models + +If your Rhom model is a [fixed schema model](../guide/local_database#fixed-schema-model) and you use bulk sync, you can control the bulk sync schema at runtime in your source adapter by implementing the 'schema' method. + +**NOTE: This method must return a JSON string. This JSON string is sent to the Rhodes application and used to dynamically build the database schema.** + +An example schema method is as follows: + + :::ruby + def schema + { + 'version' => '1.0', + 'property' => { + 'name' => 'string', + 'brand' => 'string', + 'price' => 'string', + 'image_url_cropped' => 'blob,overwrite', + 'image_url' => 'blob' + }, + 'index' => { + 'by_name_brand' => 'name,brand' + }, + 'unique_index' => { + 'by_price' => 'price' + } + }.to_json + end + +**NOTE: Key `version` is mandatory and should be always defined in schema method. You need update `version` value only in the case of schema changes.** + +## Select which models to bulk sync. + +Bulk sync process will only sync sources which sync type is not ‘none’. You may exclude model data from bulk sync with following code in your Rhodes application: + + :::ruby + Rho::RHO.get_user_db().update_into_table('sources',{'sync_type'=>'none'}, {'name'=> "MySourceName" }) + +Set sync type to 'incremental' or 'bulk' when you want to get model data with bulk sync. + diff --git a/docs/en/5.5/rhoconnect/client-java.md b/docs/en/5.5/rhoconnect/client-java.md new file mode 100644 index 00000000..a5400d21 --- /dev/null +++ b/docs/en/5.5/rhoconnect/client-java.md @@ -0,0 +1,236 @@ +# Android Java Client + +## Getting started + +* The RhoConnect Client is part of the Rhoconnect-client repository. You can get it [on github](https://github.com/rhomobile/rhodes/downloads) (select the latest 'rhoconnect-client' package). + +* The RhoConnect Client for Android contains two files: + +** rhoimpl.jar - Java part of RhoConnect Client library + +** librhoconnectclient.so - native part of RhoConnect Client library + +These can be build from /rhoconnect-client directory with next command + + :::shell + $>rake android:default + +* Create new Android project or open existing one in Eclipse. Add rhoimple.jar to your project build path and copy librhoconnectclient.so to /libs/armeabi, so both Java and native parts of RhoConnect Client library will link with your project. + +* Copy all files and subfolders from /rhoconnect-client/Java/RhoConnect/assets to assets folder of your Android project. + +## RhoConnectClient initialization + +* Load native library before any RhoConnect client usage. Example of appropriate place to do so is Android application's onCreate method + + :::java + + import android.app.Application; + public class SampleApplication extends Application + { + public void onCreate() { + System.loadLibrary("rhoconnectclient"); + } + } + +* Configure and initialize RhoConnect library. Example of appropriate place to do so is main Activity onCreate method + +* Login to RhoConnect server + + :::cplusplus + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + ApplicationInfo appInfo = getApplicationInfo(); + + try { + RhoFileApi.initRootPath(appInfo.dataDir, appInfo.sourceDir); + RhoFileApi.init(this.getApplicationContext()); + + RhoLogConf.setMinSeverity(0); + RhoLogConf.setEnabledCategories("*"); + + RhoConnectClient.nativeInit(); + } catch (Exception e) { + Logger.E(TAG, e.getMessage()); + } + mSyncClient = new RhoConnectClient(); + mModels = new RhomModel[]{ + new RhomModel("Customer", RhomModel.SYNC_TYPE_INCREMENTAL), + new RhomModel("Product", RhomModel.SYNC_TYPE_INCREMENTAL) + }; + mSyncClient.initialize(mModels); + mSyncClient.setPollInterval(0); + mSyncClient.setSyncServer("http://rhodes-store-server.heroku.com/application"); + mSyncClient.setBulkSyncState(1); + mSyncClient.loginWithUserAsync("", "", new RhoConnectNotify.IDelegate() { + public void call(RhoConnectNotify notify) { onLogin(notify); } }); + } + public void onLogin(RhoConnectNotify notify) { + // Handle login event + } + +Note: RhoConnect callbacks (like passed to RhoConnectClient.loginWithUserAsync method in example above) may and most possibly will be called from another thread. It is up to application developer to care about synchronizing or forwarding call to an appropriate thread like GUI thread or Service thread. + +## Object Model + +### Intro + +RhoConnect Client Android Java API resides at com.rhomobile.rhoconnect package. It contains two main classes: RhoConnectClient and RhomModel. The package also contains two classes which represent results of call to the API. These are RhoConnectNotify and RhoConnectObjectNotify. +Also several utility classes from com.rhomobile.rhodes package can be used. These are RhoConf, RhoLogConf, Logger. + +### RhoConnectClient + + :::cplusplus + package com.rhomobile.rhoconnect; + public class RhoConnectClient{ + /// Call this method before create and use the client. It sets up directory structure and makes necessary native library initialization. + public static native void nativeInit(); + /// Creates instance of RhoConnectClient singlethon (yes, it's only one instance of RhoConnectClient allowed). + public RhoConnectClient(); + /// Call this method to close network connections and release any resources gracefully + public synchronized void close(); + /// Makes db models initialization. This call must be made just after RhoConnectClient construction and before any other calls to RhoConnectClient object. + public native void initialize(RhomModel models[]); + /// Sets up server URL to sync (RhoConnect server) + public native void setSyncServer(String url); + /// Forces synchronous or asynchronous RhoConnectClient mode + /// true - asynchronous mode (default) + /// false - synchronous mode + public native void setThreadedMode(boolean mode); + /// Sets/gets auto sync interval. 0 - disable auto sync + public native void setPollInterval(int interval); + public native int getPollInterval(); + /// + public native void setBulkSyncState(int state); + public native int getBulkSyncState(); + /// Set get various configuration parameters. + public native void setConfigString(String name, String param); + public native String getConfigString(String name); + /// Reset all data for all models in local database, also perform logout + public native void databaseFullResetAndLogout(); + /// Checks does login session exists in the database + public native boolean isLoggedIn(); + /// Logins to RhoConnect server and keep login session in database + public native RhoConnectNotify loginWithUserSync(String user, String pass); + /// Logins to RhoConnect server and keep login session in database. + /// callback will be called when operation has finished. + public native void loginWithUserAsync(String user, String pass, RhoConnectNotify.IDelegate callback); + /// Runs sync of all models + public native RhoConnectNotify syncAll(); + } + +### RhomModel + + :::cplusplus + package com.rhomobile.rhoconnect; + public class RhomModel { + /// Possible model types + public final static int MODEL_TYPE_PROPERTY_BAG = 0; + public final static int MODEL_TYPE_FIXED_SCHEMA = 1; + /// Possible sync types + public final static int SYNC_TYPE_NONE = 0; + public final static int SYNC_TYPE_INCREMENTAL = 1; + public final static int SYNC_TYPE_BULK_ONLY = 2; + /// Constructor + public RhomModel(String name, int syncType); + /// Returns the model name + public String getName() { return mName; } + /// Returns the model type + public int getModelType() { return mModelType; } + /// Sets the model type + public void setModelType(int type) { mModelType = type; } + // Returns the model sync type + public int getSyncType() { return mSyncType; } + /// Sets the model sync type + public void setSyncType(int type) { mSyncType = type; } + /// Returns the model sync priority + public int getSyncPriority() { return mSyncPriority; } + /// Sets the model sync priority + public void setSyncPriority(int prio) { mSyncPriority = prio; } + /// Returns the model partition + public String getPartition() { return mPartition; } + /// Sets the model partition + public void setPartition(String part) { mPartition = part; } + /// Runs sync of the model + public RhoConnectNotify sync(); + /// Creates model object with properties and save to database, object id will be generated automatically if not set + public void create(Map props); + /// Finds object by object id + public Map find(String objectId) + /// Saves changes to existing object + public void save(Map item); + /// Destroys existing object + public void destroy(Map item) { + + // Returns first object which matches the condition + public Map findFirst(Map condition); + // Returns all objects which matched the condition + public Collection > findAll(Map condition); + + public void startBulkUpdate(); + public void stopBulkUpdate(); + } + +#### RhoConnectNotify + + :::cplusplus + package com.rhomobile.rhoconnect; + public class RhoConnectNotify { + public int getTotalCount() { return mTotalCount; } + public int getProcessedCount() { return mProcessedCount; } + public int getCumulativeCount() { return mCumulativeCount; } + public int getSourceId() { return mSourceId; } + public int getErrorCode() { return mErrorCode; } + public String getSourceName() { return mSourceName; } + public String getStatus() { return mStatus; } + public String getSyncType() { return mSyncType; } + public String getErrorMessage() + public String getCallbackParams() { return mParams; } + /// Developer need to implement and pass reference to this interface + /// in order to get call back when asynchronous operation has completed + public static interface IDelegate { + public void call(RhoConnectNotify notify); + } + } + +#### RhoConnectObjectNotyfy + + :::cplusplus + package com.rhomobile.rhoconnect; + public interface RhoConnectObjectNotify { + public String[] getDeletedObjects(); + public String[] getUpdatedObjects(); + public String[] getCreatedObjects(); + + public int[] getDeletedSourceIds(); + public int[] getUpdatedSourceIds(); + public int[] getCreatedSourceIds(); + + /// Developer need to implement and pass reference to this interface + /// in order to get call back when objects are created, updated or destroyed at sync server + public static interface IDelegate { + public void call(RhoConnectObjectNotify notify); + } + } + +### Samples + +* See android_store sample [rhoconnect-client\Samples\Java\android_store](http://github.com/rhomobile/rhodes/tree/master/rhoconnect-client/Samples/Java/android_store/) as an example. +* See android test Eclipse project [rhoconnect-client\Java\Android\test](http://github.com/rhomobile/rhodes/tree/master/rhoconnect-client/Java/Android/test/) as another example. + +## Packaging RhoConnect Client +To package the RhoConnect Client archive for distribution, go to the top of the rhodes repository and run: + + :::term + $ rake build:rhoconnect_client + +This will produce a zipfile in the folder called `rhoconnect-client-.zip` where `` is the version of the client. + +## Release procedure +1. Unzip package to some folder + +2. Open project `rhoconnect-client\ObjectiveC\Tests\RhoConnectClientTest` in xcode and run. See log - SUCCESS should be at the end of log + +3. Open project `rhoconnect-client\Samples\ObjectiveC\store` in xcode and run. Press Login, you should see several items, click on item, you should see details diff --git a/docs/en/5.5/rhoconnect/client-objc.md b/docs/en/5.5/rhoconnect/client-objc.md new file mode 100644 index 00000000..b3f78014 --- /dev/null +++ b/docs/en/5.5/rhoconnect/client-objc.md @@ -0,0 +1,1077 @@ +Using RhoConnect without Rhodes: Objective C Client API +=== + +The RhoConnect Client is a library that adds sync data capability to your non-Rhodes applications, such as applications created in XCode or Android Java. Using this library, you can enable synchronized data between your Objective C iOS device application and a RhoConnect server. + +Source Code +----------- +The source code for the RhoConnect client store example is located here. + + * [rhoconnect-client\Samples\ObjectiveC\store](http://github.com/rhomobile/rhoconnect-client/tree/master/rhoconnect-client/Samples/ObjectiveC/store/) + +Pre-requisite Reading +--------------------- + * [iOS development](http://developer.apple.com/devcenter/ios/index.action) + +## Features supported + + + + + + + + + + + + + +
                                                                              Feature Ruby ObjectiveC
                                                                              Property bag modelyesyes
                                                                              Fixed schema modeyesyes
                                                                              Model associationsyesyes
                                                                              BLOB attributesyesyes
                                                                              Bulk syncyesyes
                                                                              Syncyesyes
                                                                              Notificationsyesyes
                                                                              Database resetyesyes
                                                                              Authenticationyesyes
                                                                              DB partitioningyesnot yet
                                                                              + +## Setup + +The RhoConnect Client is part of the Rhoconnect-client repository; it contains files that you will need to add to your Xcode project. You can get the client [on github](https://github.com/rhomobile/rhodes/downloads). (Select the latest 'rhoconnect-client' package). + +Create a new Xcode project or open an existing one in Xcode. + +### Adding RhoConnectClient to your Xcode Project + +Do the following steps to add `/objectivec/RhoConnectClient.xcodeproj` as a dependency so that the RhoConnectClient library will link with your project. + +1. Drag and drop `/ObjectiveC/RhoConnectClient.xcodeproj` from the Finder into Groups & Files for your Xcode project. RhoConnectClient.xcodeproj should now appear in Groups & Files. + +RhoConnectClient in Groups & Files + +2. Under Groups and Files, open the Targets icon. +3. Right-click on your project-named target. +4. Choose Get Info, then click on the General tab. +5. In Direct Dependencies, click the + button. +6. Choose the dependency from RhoConnectClient.xcodeproj. + +RhoConnectClient Direct Dependency + +### Adding Xcode Libraries + +Do the following steps to add libraries: + +1. Under Groups & Files, right-click on your project (the name at the top of the list). +2. Select Add->Existing Frameworks from the popup menu. +3. Add the following to your project: `libstdc++6.dylib, libsqlite3.dylib, libz.dylib, CFNetwork.framework`. + +Add Frameworks + +### Adding Schema Files + +Do the following steps to add schema files to your Copy Bundle Resources build phase: +1. Copy the folder `/platform/shared/db/res/db` into your Xcode project folder. +2. Drag the copied db folder into your Xcode project, onto the project-named icon under Groups & Files. The db folder should now appear in the Groups & Files list. +3. Under Groups and Files, open the Targets icon, then open the project-named icon under Targets, then open the Copy Bundle Resources folder. You should see sync.schema listed there. +4. Open and edit the sync.schema file. Add a create table statement for every model you will use in your project. For example, for a model named product: + + :::term + CREATE TABLE product ( + "client_id" VARCHAR(255) default NULL); + +** NOTE: Do not use NOT NULL statement in column definitions. RhoConnect client delete object attributes by setting value to null, when all object attributes become nulls, object deleted. So objects with NOT NULL columns will not be deleted. ** + +## Coding a RhoConnect Client + +This section discusses the general steps you perform to code a RhoConnect client in Objective C, using the store example. It is not a tutorial for coding a complete Xcode application, but instead discusses the RhoConnect code that you need to create. + +### Initialize the Database + +Call the RhoConnectClient method initDatabase to initialize the local database for the models. You must do this before you initialize and use a RhoConnectClient object. + + :::cplusplus + [RhoConnectClient initDatabase]; + +### Initialize the Client + +Call the RhomModel init method for each model. In the Store example, initialize a customer model and a product model. + + :::cplusplus + customer = [[RhomModel alloc] init]; + customer.name = @"Customer"; + product = [[RhomModel alloc] init]; + product.name = @"Product"; + +Call init for RhoConnectClient to initialize your client. + + :::cplusplus + sclient = [[RhoConnectClient alloc] init]; + +Set up an NSMutableArray containing the models for your client. + + :::cplusplus + NSMutableArray* models = [NSMutableArray arrayWithObjects:customer, product, nil]; + +Call the RhoConnectClient method addModels to add those models to your client. + + :::cplusplus + [sclient addModels:models]; + +Set the RhoConnectClient property sync\_server to the URL of the RhoConnect server for your client. + + :::cplusplus + sclient.sync_server = @"http://rhodes-store-server.heroku.com/application"; + +Here is the Store code for the initialization process, contained in RhoConnectEngine.m. + + :::cplusplus + - (id)init + { + if ( sharedInst != nil ) { + [NSException raise:NSInternalInconsistencyException + format:@"[%@ %@] cannot be called; use +[%@ %@] instead", + NSStringFromClass([self class]), NSStringFromSelector(_cmd), + NSStringFromClass([self class]), + NSStringFromSelector(@selector(sharedInstance))]; + + } else if ( self = [super init] ) { + sharedInst = self; + + [RhoConnectClient initDatabase]; + + customer = [[RhomModel alloc] init]; + customer.name = @"Customer"; + + product = [[RhomModel alloc] init]; + product.name = @"Product"; + + sclient = [[RhoConnectClient alloc] init]; + NSArray* models = [NSArray arrayWithObjects:customer, product, nil]; + + [sclient addModels:models]; + + sclient.sync_server = @"http://rhodes-store-server.heroku.com/application"; + sclient.threaded_mode = TRUE; + sclient.log_severity = 1; + + loginState = [sclient is_logged_in] ? logged_in : logged_out; + } + return sharedInst; + } + +### Log Into the RhoConnect Server + +Call the RhoConnectClient loginWithUser method to log into the RhoConnect server. + + :::cplusplus + [ [RhoConnectEngine sharedInstance].syncClient loginWithUser:txtLogin.text pwd:txtPassword.text callback:@selector(loginComplete:) target:self]; + +Here is the Store code for the login process, contained in LoginViewController.m. It contains both a login method that calls loginWithUser, and a callback method called by loginWithUser, that checks to see if the login is active. + + :::cplusplus + - (void)loginComplete:(RhoConnectNotify*) notify + { + if ( notify.error_code != RHO_ERR_NONE || ![[RhoConnectEngine sharedInstance].syncClient is_logged_in]) + [RhoConnectEngine sharedInstance].loginState = failed; + else + [RhoConnectEngine sharedInstance].loginState = logged_in; + + [waitPage loginComplete: [notify error_message] ]; + + [notify release]; + } + + - (IBAction)doLogin:(id)sender + { + [RhoConnectEngine sharedInstance].loginState = in_progress; + [[self navigationController] pushViewController:waitPage animated:YES]; + + [ [RhoConnectEngine sharedInstance].syncClient loginWithUser:txtLogin.text pwd:txtPassword.text callback:@selector(loginComplete:) target:self]; + } + + +### Synchronize Data + +Call the RhoConnectClient setNotification method to call a callback method that notifies about the state of the synchronization. + + :::cplusplus + [ [RhoConnectEngine sharedInstance].syncClient setNotification: @selector(syncAllComplete:) target:self]; + +To perform a bulk sync *bulksync_state* configuration flag should be reset to zero. If you don't need bulk sync then just skip it. + + :::cplusplus + // set configuration for bulk sync, it means "next sync should be performed as bulk" + [RhoConnectEngine sharedInstance].syncClient.bulksync_state = 0; + // after sync performed the it should contain value 1. + +Call a sync method, such as the RhoConnectClient syncAll method or the RhomModel sync method, to sync your client model data with the RhoConnect server. + + :::cplusplus + [ [RhoConnectEngine sharedInstance].syncClient syncAll]; + +Call clearNotification upon completion of the sync. + + :::cplusplus + [ [RhoConnectEngine sharedInstance].syncClient clearNotification]; + +Here is the Store code for the sync process, contained in WaitLoginController.m. It contains both a loginComplete method (called from the loginWithUser callback method) that calls setNotification and syncAll, and the setNotification callback method that calls clearNotification when the sync is complete. + + :::cplusplus + - (void)syncAllComplete:(RhoConnectNotify*) notify + { + if ( [notify.status compare:@"in_progress"] == 0) + { + }else if ([notify.status compare:@"complete"] == 0) + { + [[self navigationController] pushViewController:homePage animated:YES]; + [ [RhoConnectEngine sharedInstance].syncClient clearNotification]; + }else if ([notify.status compare:@"error"] == 0) + { + if([notify.error_message caseInsensitiveCompare:@"unknown client"] == 0) { + [[RhoConnectEngine sharedInstance].syncClient database_client_reset]; + [[RhoConnectEngine sharedInstance].syncClient setNotification: @selector(syncAllCalback:) target:self]; + [[RhoConnectEngine sharedInstance].syncClient syncAll]; + } else if( err_code == RHO_ERR_CLIENTISNOTLOGGEDIN + || err_code == RHO_ERR_UNATHORIZED) { + + NSLog(@"GO TO LOGIN PAGE!"); + // real code to trigger view transition goes here.. + }else + { + //This is mandatory: + if([notify hasCreateErrors]) { + [[RhoConnectEngine sharedInstance].syncClient onCreateError: notify @"delete"]; + } + //These are optional: + /* + if([notify hasUpdateErrors]) { + [[RhoConnectEngine sharedInstance].syncClient onUpdateError: notify @"rollback"]; + } + if([notify hasDeleteErrors]) { + [[RhoConnectEngine sharedInstance].syncClient onDeleteError: notify @"retry"]; + } + */ + } + } + } + + - (void)loginComplete:(NSString*) errorMessage + { + NSLog(@"Login error message: \"%@\"", errorMessage); + [indicator stopAnimating]; + if ([RhoConnectEngine sharedInstance].loginState == logged_in) + { + [ [RhoConnectEngine sharedInstance].syncClient setNotification: @selector(syncAllComplete:) target:self]; + [ [RhoConnectEngine sharedInstance].syncClient syncAll]; + } else { + lblMessage.text = errorMessage; + self.navigationItem.hidesBackButton = false; + } + } + +### Processing unknown-client error +Unknown client error return by server after resetting server database, removing particular client id from database or any other cases when server cannot find client id(sync server unique id of device). +Note that login session may still exist on server, so in this case client does not have to login again, just create new client id. +Processing of this error contain 2 steps: + +* When unknown client error is come from server, client should call database_client_reset and start new sync, to register new client id. + +* If login session also deleted or expired on the server, then customer has to login again. + +Example: + :::cplusplus + + - (void)syncAllComplete:(RhoConnectNotify*) notify + { + NSString* status = notify.status; + NSString* error = notify.error_message; + int err_code = notify.error_code; + + NSLog(@"syncAll DONE, status: '%s' , error_msg: '%s' , error_code: %d", + [status cStringUsingEncoding: NSUTF8StringEncoding], + [error cStringUsingEncoding: NSUTF8StringEncoding], + err_code + ); + + if ( [notify.status compare:@"in_progress"] == 0) { + + } else if ([notify.status compare:@"complete"] == 0) { + + [[RhoConnectEngine sharedInstance].syncClient clearNotification]; + + } else if ([notify.status compare:@"error"] == 0) { + + if([notify.error_message caseInsensitiveCompare:@"unknown client"] == 0) { + [[RhoConnectEngine sharedInstance].syncClient database_client_reset]; + [[RhoConnectEngine sharedInstance].syncClient setNotification: @selector(syncAllCalback:) target:self]; + [[RhoConnectEngine sharedInstance].syncClient syncAll]; + } else if( err_code == RHO_ERR_CLIENTISNOTLOGGEDIN + || err_code == RHO_ERR_UNATHORIZED) { + + NSLog(@"GO TO LOGIN PAGE!"); + // real code to trigger view transition goes here.. + } + } + } + +### Processing server errors +* create-error: +has to be handled in sync callback. Otherwise sync will stop on this model. To fix create errors you should call Model.on_sync_create_error or SyncEngine.on_sync_create_error: + +* update-error: +If not handled, local modifications, which were failing on server, will never sync to server again. +So sync will work fine, but nobody will know about these changes. + +* delete-error: +If not handled, local modifications, which were failing on server, will never sync to server again. +So sync will work fine, but nobody will know about these changes. + +Example: + :::cplusplus + + - (void)syncAllCalback:(RhoConnectNotify*) notify + { + NSString* status = notify.status; + NSString* error = notify.error_message; + int err_code = notify.error_code; + + NSLog(@"syncAll DONE, status: '%s' , error_msg: '%s' , error_code: %d", + [status cStringUsingEncoding: NSUTF8StringEncoding], + [error cStringUsingEncoding: NSUTF8StringEncoding], + err_code + ); + + if ( [notify.status compare:@"in_progress"] == 0) { + + } else if ([notify.status compare:@"complete"] == 0) { + + [[RhoConnectEngine sharedInstance].syncClient clearNotification]; + + } else if ([notify.status compare:@"error"] == 0) { + + if([notify isUnknownClientError]) { + [[RhoConnectEngine sharedInstance].syncClient database_client_reset]; + [[RhoConnectEngine sharedInstance].syncClient setNotification: @selector(syncAllCalback:) target:self]; + [[RhoConnectEngine sharedInstance].syncClient syncAll]; + } else if( err_code == RHO_ERR_CLIENTISNOTLOGGEDIN + || err_code == RHO_ERR_UNATHORIZED) { + + NSLog(@"GO TO LOGIN PAGE!"); + // real code to trigger view transition goes here.. + }else + { + //This is mandatory: + if([notify hasCreateErrors]) { + [[RhoConnectEngine sharedInstance].syncClient onCreateError: notify action:@"delete"]; + } + //These are optional: + /* + if([notify hasUpdateErrors]) { + [[RhoConnectEngine sharedInstance].syncClient onUpdateError: notify action:@"rollback"]; + } + if([notify hasDeleteErrors]) { + [[RhoConnectEngine sharedInstance].syncClient onDeleteError: notify action:@"retry"]; + } + */ + } + } + } + +### Search the Client Database for Models + +Call a RhomModel find method (find, find\_first, find\_all) to find model objects in the client database. This code sample for the find\_all method fetches all the models in the database; you can also search for models containing certain attribute data. + + :::cplusplus + NSMutableArray* arItems = [[RhoConnectEngine sharedInstance].product find_all:nil]; + NSDictionary* item = [arItems objectAtIndex: 0 ]; + textBrand = [item valueForKey:@"brand"]; + +Here is the Store code for the find process, contained in RootViewController.m. It contains a call to the find\_all method, and returns the total count of the models in the database. + + :::cplusplus + // Customize the number of rows in the table view. + - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section + { + if (!arItems) + arItems = [[RhoConnectEngine sharedInstance].product find_all:nil]; + + //warning here because this may be dictionary or an array when called. + return (NSUInteger)[arItems count]; + } + +## RhoConnectClient Class API + +The RhoConnectClient class contains the following properties and methods to build an Objective C RhoConnect client and connect it with a RhoConnect server. + + * threaded_mode property + * poll_interval property + * log_severity property + * sync_server property + * initDatabase + * addModels + * database\_full\_reset\_and\_logout + * database\_client\_reset + * initDatabase + * loginWithUser + * loginWithUser (with callback) + * setNotification + * clearNotification + * is\_logged\_in + * syncAll + * is_syncing + * stop_sync + * search + * setObjectNotification + * clearObjectNotification + * addObjectNotify + * onCreateError + * onUpdateError + * onDeleteError + +### threaded\_mode property + +BOOL. Set to false to get the result of operations as a return value. (Set to true to get notifications - not supported yet.) Default = false. + + :::cplusplus + @property(setter=setThreadedMode) BOOL threaded_mode; + +### poll\_interval property + +int. Not yet supported. Default = 0. + + :::cplusplus + @property(setter=setPollInterval) int poll_interval; + +### log\_severity property + +int. Set minimal severity level for messages to log output. Default = 0. + + :::cplusplus + @property(setter=setLogSeverity) int log_severity; + +### sync\_server property + +NSString. Sets the RhoConnect server url, for example: "`http://:/application`" + + :::cplusplus + @property(assign, setter=setSyncServer) NSString* sync_server; + +### initDatabase + +Initializes your client database. Call this method before you create and use a client. + + ::::cplusplus + + (void) initDatabase; + +### addModels + +Adds your model objects to your client database, allowing them to sync with the RhoConnect server. + + :::cplusplus + - (void) addModels:(NSArray*)models; + + + + + + +
                                                                              modelsNSArray containing the model objects.
                                                                              + +### database\_full\_reset\_and\_logout + +Resets all data for all models in your local database, and then performs logout. + + :::cplusplus + - (void) database_full_reset_and_logout; + +### database\_client\_reset + +Resets all data for all models in your local database and delete client ID. Use this method for 'unknown client' error + + :::cplusplus + - (void) database_client_reset; + +### loginWithUser + +Returns a RhoConnectNotify object containing login data after logging your client database into the RhoConnect server. + + :::cplusplus + - (RhoConnectNotify*) loginWithUser: (NSString*) user pwd:(NSString*) pwd; + + + + + + + + + + +
                                                                              usrNSString containing the user name.
                                                                              pwdNSString containing the password.
                                                                              + +###
                                                                              loginWithUser (with callback) + +Logs your client database into the RhoConnect server and calls a selector callback target method when the login process is finished. + + :::cplusplus + - (void) loginWithUser: (NSString*) user pwd:(NSString*) pwd callback:(SEL) callback target:(id)target; + + + + + + + + + + + + + + +
                                                                              usrNSString containing the user name.
                                                                              pwdNSString containing the password.
                                                                              callback:(SEL) callback target:(id)targetThe reference to the callback method. An example could be callback:@selector(loginComplete:) target:self. You would write the callback method loginComplete to perform actions when the login process completes.
                                                                              + +###
                                                                              setNotification + +Set the sync notification callback method. + + :::cplusplus + - (void) setNotification: (SEL) callback target:(id)target; + + + + + + +
                                                                              callback:(SEL) target:(id)targetThe reference to the callback method that performs actions upon a sync notification.
                                                                              + +###
                                                                              clearNotification + +Instance method. Clear the sync notification callback. + + :::cplusplus + - (void) clearNotification; + +### is\_logged\_in + +Instance method. Returns true if your RhoConnect session is logged in (if the login session exists in the database), false otherwise. + + :::cplusplus + - (BOOL) is_logged_in; + +### syncAll + +Instance method. Returns a RhoConnectNotify object after running a sync on all the models for your RhoConnect client. + + :::cplusplus + - (RhoConnectNotify*) syncAll; + +### is_syncing + +Instance method. Returns TRUE if synchronization is in progress + + :::cplusplus + - (BOOL) is_syncing; + +### stop_sync + +Instance method. Stop current sync if running + + :::cplusplus + - (void) stop_sync; + +### search + +Instance method. Returns a RhoConnectNotify object after sending a search request to the RhoConnect server. + + :::cplusplus + - (RhoConnectNotify*) search: (NSArray*)models from: (NSString*) from params: (NSString*)params sync_changes: (BOOL) + sync_changes progress_step: (int) progress_step; + + + + + + + + + + + + + + + + + + + + + + +
                                                                              modelsNSArray containing the names of the model names to search in.
                                                                              from(Optional) NSString. Sets the RhoConnect path that the records are fetched with. Default = "search".
                                                                              paramsNSString. A string containing the name/value search items, in the form "param1=val1¶m2=val2¶m3=val3". The values must be url-encoded.
                                                                              sync_changesBOOL. TRUE if data with local changes is pushed to the server before the search is performed, FALSE otherwise.
                                                                              progress_step(Optional) int. Define how often the search callback will be executed when the RhoConnectNotify status is "in_progress".
                                                                              + +###
                                                                              setObjectNotification + +Instance method. Sets the callback method for object notification. The callback receives a RhoConnectObjectNotify object as a parameter. This RhoConnectObjectNotify object contains three arrays of hashes for the objects and their source ids that have been updated, created, and deleted, allowing you to display which records were changed. + + - (void) setObjectNotification: (SEL) callback target:(id)target; + + + + + + +
                                                                              (SEL) callback target:(id)targetThe name of your callback method.
                                                                              + +###
                                                                              clearObjectNotification + + - (void) clearObjectNotification; + +Instance method. Clears the callback method for object notification. + +### addObjectNotify + +Instance method. Add an object to track changes: create, update, delete. + + :::cplusplus + - (void) addObjectNotify: (int) nSrcID szObject:(NSString*) szObject; + + + + + + + + + + +
                                                                              nSrcIDint. The object ID of the source on the server with which this RHoConnectClient syncs. You can provide this with the "source\_id" property value.
                                                                              szObjectNSString. The object ID of the item created to track the changes to this RhoConnectClient.
                                                                              + +Sample call: + + :::cplusplus + RhoConnectClient* sclient; + ... + [sclient addObjectNotify: [[item objectForKey:@"source_id"] intValue] szObject:[item valueForKey:@"object"] ]; + +### onCreateError + +Instance method. To process 'create-error' errors from server. + + :::cplusplus + - (void) onCreateError: (RhoConnectNotify*)notify action: (NSString*)action; + + + + + + + + + + +
                                                                              notifyRhoConnectNotify. Notification object passed to notification callback.
                                                                              actionNSString. May be "delete" or "recreate": "delete" just remove object from client, "recreate" will push this object to server again at next sync.
                                                                              + +Sample call: + + :::cplusplus + RhoConnectClient* sclient; + ... + if ([notify hasCreateErrors]) + [sclient onCreateError: notify action:@"delete" ]; + + +### onUpdateError + +Instance method. To process 'update-error' errors from server. + + :::cplusplus + - (void) onUpdateError: (RhoConnectNotify*)notify action: (NSString*)action; + + + + + + + + + + +
                                                                              notifyRhoConnectNotify. Notification object passed to notification callback.
                                                                              actionNSString. May be "retry" or "rollback": "retry" will push update object operation to server again at next sync, "rollback" will write rollback objects(comes from server) to client database.
                                                                              + +Sample call: + + :::cplusplus + RhoConnectClient* sclient; + ... + if ([notify hasUpdateErrors]) + [sclient onUpdateError: notify action:@"retry" ]; + +### onUpdateError + +Instance method. To process 'delete-error' errors from server. + + :::cplusplus + - (void) onDeleteError: (RhoConnectNotify*)notify action: (NSString*)action; + + + + + + + + + + +
                                                                              notifyRhoConnectNotify. Notification object passed to notification callback.
                                                                              actionNSString. May be "retry" - will push delete object operation to server again at next sync.
                                                                              + +Sample call: + + :::cplusplus + RhoConnectClient* sclient; + ... + if ([notify hasDeleteErrors]) + [sclient onDeleteError: notify action:@"retry" ]; + +## RhomModel Class API + +The RhomModel class contains the following properties and methods for setting and using RhomModel objects; RhomModel objects are RhoConnect models and their attributes. + + * name property + * sync_type property + * model_type property + * associations property + * init + * sync + * sync (with callback) + * setNotification + * clearNotification + * create + * find + * find_first + * find_all + * save + * destroy + * startBulkUpdate + * stopBulkUpdate + * is_changed + +### name property + +NSString. Sets the model name. + + :::cplusplus + @property(assign) NSString* name; + +### sync\_type property + +int. Sets the synchronization type: RST\_INCREMENTAL or RST\_BULK\_ONLY. + + :::cplusplus + @property(assign) int sync_type; + +### model\_type property + +int. Sets the model type: RMT\_PROPERTY\_BAG (default) or RMT\_PROPERTY\_FIXEDSCHEMA. + + :::cplusplus + @property(assign) int model_type; + +### associations property + +The associations dictionary is a property of the model that controls its synchronization process. When one model (model A) has an association with another model (model B), this forces the other model (model B) synchronized along with the model (model A). + + :::cplusplus + // Associations dictionary: the key is the model attribute name, + // the value is the associated model name. + // While using associations, use the object_id attribute as object reference + + @property(assign) NSDictionary* associations; + +Example of associating two models, customer and product: + + :::cplusplus + RhomModel* order = [[RhomModel alloc] init]; + order.name = @"Order"; + order.associations = [NSDictionary dictionaryWithObjectsAndKeys: @"Customer", @"customer", @"Product", @"product", nil]; + +### init + +Initializes a model object. + + :::cplusplus + - (id) init; + +### sync + +Returns a RhoConnectNotify object containing sync information, after running a sync on this model. + + :::cplusplus + - (RhoConnectNotify*) sync; + +### sync (with callback) + +Runs a sync on this model, and calls a callback, passing the callback the RhoConnectNotify status parameter for the synchronization: "in\_progress", "ok", "error", "complete". + + :::cplusplus + - (void) sync: (SEL) callback target:(id)target; + +Example: + + :::cplusplus + int shouldSyncProductByName() + { + RhoConnectNotify* res = [[product sync] retain]; + int nErr = res.error_code; + [res release]; + if ( nErr!= RHO_ERR_NONE ) { + return 0; + } + + return 1; + } + +### setNotification + +Set the sync notification callback method for the Model. + + :::cplusplus + - (void) setNotification: (SEL) callback target:(id)target; + + + + + + +
                                                                              callback:(SEL) target:(id)targetThe reference to the callback method that performs actions upon a sync notification.
                                                                              + +###
                                                                              clearNotification + +Instance method. Clear the sync notification callback for the Model. + + :::cplusplus + - (void) clearNotification; + + +### create + +Create a model object with attributes and save it to the database, the object id will be generated automatically if not set. + + :::cplusplus + - (void) create: (NSMutableDictionary *) data; + + + + + + +
                                                                              dataNSMutableDictionary. The object containing the attribute data for this model.
                                                                              + +###
                                                                              find + +Returns an NSMutableDictionary object containing a model with the given object id. + + :::cplusplus + - (NSMutableDictionary *) find: (NSString*)object_id; + + + + + + +
                                                                              object_idNSString. The object id.
                                                                              + +###
                                                                              find\_first + +Returns an NSMutableDictionary object containing the first model object found with the given set of model attributes. + + :::cplusplus + - (NSMutableDictionary *) find_first: (NSDictionary *)cond; + + + + + + +
                                                                              condA NSDictionary object containing the model attributes to find.
                                                                              + +Example call: + + :::cplusplus + NSMutableDictionary* cond = [[NSMutableDictionary alloc] init]; + [cond setValue: @"SomeRealName" forKey:@"name"]; + prod = [[product find_first: cond] retain]; + [cond release]; + if ( !prod ) { + // not found + } + +###
                                                                              find\_all + +Returns a NSMutableArray containing all the model objects that match the given set of attributes. + + :::cplusplus + - (NSMutableArray *) find_all: (NSDictionary *)cond; + + + + + + +
                                                                              condA NSDictionary object containing the model attributes to find.
                                                                              + +###
                                                                              save + +Saves a model object with the given data to the database. + + :::cplusplus + - (void) save: (NSDictionary *)data; + + + + + + +
                                                                              dataA NSDictionary object containing the attribute data for the model object that is saved.
                                                                              + +###
                                                                              destroy + +Delete model objects from the database that contain the given data. + + :::cplusplus + - (void) destroy: (NSDictionary *)data; + + + + + + +
                                                                              dataA NSDictionary object containing the attribute data for the model objects that are to be deleted.
                                                                              + +###
                                                                              startBulkUpdate + +Run this method when you start to create or update a bunch of models; it will optimize database access. Equal to start transaction. + + :::cplusplus + - (void) startBulkUpdate; + +### stopBulkUpdate + +Run this method when you start to create or update a bunch of models; it will optimize database access. Equal to commit transaction. + + :::cplusplus + - (void) stopBulkUpdate; + +### is_changed + +Check does model contain non-synced local changes + + :::cplusplus + - (BOOL) is_changed; + +## RhoConnectNotify Class API + +Several RhoConnectClient methods return a RhoConnectNotify object. The properties for the RhoConnectNotify class provide access to sync notification objects as described [here](../guide/using_rhoconnect#setting-up-notifications). (Developers do not set RhoConnectNotify properties, but only read them after a call to a RhoConnectClient method that returns a RhoConnectNotify object.) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                              total_count@property int. Total number of records that exist for this RhoConnect source.
                                                                              processed_count@property int. Number of records included in this sync page for an in\_progress (status = incremental) sync.
                                                                              cumulative_count@property int. Number of records the SyncEngine has processed so far for this source.
                                                                              source_id@property int. The id of the current model that is synchronizing.
                                                                              error_code@property int. The HTTP response code of the RhoConnect server error: 401, 500, 404, etc.
                                                                              source_name@property(assign) NSString*. Name of the model (i.e. "Product").
                                                                              status@property(assign) NSString*. Status of the current sync process: "in\_progress", "error", "ok", "complete", "schema-changed".
                                                                              sync_type@property(assign) NSString*. Type of sync used for this model: "incremental" or "bulk".
                                                                              error_message@property(assign) NSString*. Response body of error message (if any).
                                                                              callback_params@property(assign) NSString*. Callback parameters.
                                                                              hasCreateErrors(Boolean). Return true if server return create-errors.
                                                                              hasUpdateErrors(Boolean). Return true if server return update-errors.
                                                                              hasDeleteErrors(Boolean). Return true if server return delete-errors.
                                                                              isUnknownClientError(Boolean). Return true if server return unknown client error.
                                                                              + +## RhoConnectObjectNotify Class API + +This class provides access to the sync object notification as described [here](../guide/using_rhoconnect#setting-up-notifications). + +The RhoConnectObjectNotify object contains three arrays of hashes for the objects and their source ids that have been updated, created, and deleted. Each hash contains values for the keys “object” and “source\_id” so you can display which records were changed. + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                              deleted_objects@property(readonly) NSMutableArray*. An array containing the deleted objects.
                                                                              updated_objects@property(readonly) NSMutableArray*. An array containing the updated objects.
                                                                              created_objects@property(readonly) NSMutableArray*. An array containing the created objects.
                                                                              deleted_source_ids@property(readonly) NSMutableArray*. An array containing the deleted source ids.
                                                                              updated_source_ids@property(readonly) NSMutableArray*. An array containing the updated source ids.
                                                                              created_source_ids@property(readonly) NSMutableArray*. An array containing the created source ids.
                                                                              + +## Packaging RhoConnect Client +To package the RhoConnect Client archive for distribution, go to the top of the rhodes repository and run: + + :::term + $ rake build:rhoconnect_client + +This will produce a zipfile in the folder called `rhoconnect-client-.zip` where `` is the version of the client. + +## Release procedure +1. Unzip package to some folder + +2. Open project `rhoconnect-client\ObjectiveC\Tests\RhoConnectClientTest` in xcode and run. See log - SUCCESS should be at the end of log. + +3. Open project `rhoconnect-client\Samples\ObjectiveC\store` in xcode and run. Press Login, you should see several items, click on item, you should see details. diff --git a/docs/en/5.5/rhoconnect/client.md b/docs/en/5.5/rhoconnect/client.md new file mode 100644 index 00000000..5a634f05 --- /dev/null +++ b/docs/en/5.5/rhoconnect/client.md @@ -0,0 +1,628 @@ +Using RhoConnect with the RhoConnect Client +=== + +Rhoconnect Client is a library to add sync data capability to your applications. Application code can be ObjectiveC, JavaScript or any other supported language. Using this library you can easily enable synchronized data between your smartphone application and a RhoConnect server. + +## Objective-C Client + +### Getting started +* The RhoConnect Client is part of the Rhoconnect-client repository. You can get it [on github](https://github.com/rhomobile/rhodes/downloads) (select the latest 'rhoconnect-client' package). + +* Create new project or open existing one in XCode. Add `/objectivec/RhoConnectClient.xcodeproj` as dependency to your project, so the RhoConnectClient library will link with your project. + +* Add a 'Copy bundle resources' build phase to project target, than add `/shared/db/res/db` folder to it. + +* Add these libraries to your project: `libstdc++6.dylib, libsqlite3.dylib, libz.dylib, CFNetwork.framework`. + +### Features supported + + + + + + + + + + + + + +
                                                                              Feature Ruby ObjectiveC
                                                                              Property bag modelyesyes
                                                                              Fixed schema modeyesyes
                                                                              Model associationsyesyes
                                                                              BLOB attributesyesyes
                                                                              Bulk syncyesyes
                                                                              Syncyesyes
                                                                              Notificationsyesyes
                                                                              Database resetyesyes
                                                                              Authenticationyesyes
                                                                              DB partitioningyesnot yet
                                                                              + +### Object Model + +#### RhoConnectClient + + :::cplusplus + //default is false + //Set to false to get result of operations as return value. + //Set to true to get notifications - not supported yet + @property(setter=setThreadedMode) BOOL threaded_mode; + + //default is 0. Not supported yet + @property(setter=setPollInterval) int poll_interval; + + //default is 0. Set minimal severity level for messages to log output + @property(setter=setLogSeverity) int log_severity; + + //set rhoconnect server url, for example: "http://:/application" + @property(assign, setter=setSyncServer) NSString* sync_server; + + //call this method before create and use client + //it will initialize local database + + (void) initDatabase; + + //Add sync models to database, so they will sync + - (void) addModels:(NSArray*)models; + + //reset all data for all models in local database, also perform logout + - (void) database_full_reset_and_logout; + + //login to rhoconnect server and keep login session in database + - (RhoConnectNotify*) loginWithUser: (NSString*) user pwd:(NSString*) pwd; + + //login to rhoconnect server and keep login session in database and call selector when finish + // target is object where to call selector, selector calls in thread which make login call + - (void) loginWithUser: (NSString*) user pwd:(NSString*) pwd callback:(SEL) callback target:(id)target; + + //set sync notification callback + - (void) setNotification: (SEL) callback target:(id)target; + //clear sync notification callback + - (void) clearNotification; + + //check does login session exists in database + - (BOOL) is_logged_in; + + // run sync of all models + - (RhoConnectNotify*) syncAll; + + // check is sync is in progress + - (BOOL) is_syncing; + + //stop current sync if running + - (void) stop_sync; + + //send search request to rhoconnect + - (RhoConnectNotify*) search: (NSArray*)models from: (NSString*) from params: (NSString*)params sync_changes: (BOOL) + sync_changes progress_step: (int) progress_step; + + //set callback method for object notification. callback receive RhoConnectObjectNotify object as a parameter + - (void) setObjectNotification: (SEL) callback target:(id)target; + - (void) clearObjectNotification; + //add object to track changes: create, update, delete + - (void) addObjectNotify: (int) nSrcID szObject:(NSString*) szObject; + + //To process 'create-error' errors from server: + //Action may be "delete" or "recreate" + //"delete" just remove object from client, "recreate" will push this object to server again at next sync. + - (void) onCreateError: (RhoConnectNotify*)notify action: (NSString*)action; + + //To process 'update-error' errors from server: + //Action may be "retry" or "rollback". + //"retry" will push update object operation to server again at next sync, "rollback" will write rollback objects(comes from server) to client database. + - (void) onUpdateError: (RhoConnectNotify*)notify action: (NSString*)action; + + //To process 'delete-error' errors from server: + //Action may be "retry" - will push delete object operation to server again at next sync. + - (void) onDeleteError: (RhoConnectNotify*)notify action: (NSString*)action; + +#### RhomModel + + :::cplusplus + //model name + @property(assign) NSString* name; + + //possible values: RST_INCREMENTAL, RST_BULK_ONLY + @property(assign) int sync_type; + + //possible values: RMT_PROPERTY_BAG (default), RMT_PROPERTY_FIXEDSCHEMA + @property(assign) int model_type; + + //associations dictionary: the key is attribute name, the value is associated model name + //while using associations use object_id attribute as object reference + @property(assign) NSDictionary* associations; + + // model constructor + - (id) init; + + //run sync of this model + - (RhoConnectNotify*) sync; + + //run sync of this model and call callback with status(in_progress, ok, error, complete) + - (void) sync: (SEL) callback target:(id)target; + + //create model object with properties and save to database, object id will be generated automatically if not set + - (void) create: (NSMutableDictionary *) data; + + //find object by object id + - (NSMutableDictionary *) find: (NSString*)object_id; + + //find first object by set of properties + - (NSMutableDictionary *) find_first: (NSDictionary *)cond; + + //find all objects by set of properties + - (NSMutableArray *) find_all: (NSDictionary *)cond; + + //run sql query - result is array of hashes (string) + - (NSMutableArray *) find_bysql: (NSString*)sql args: (NSArray*) sql_args; + + //save object represents by data to database + - (void) save: (NSDictionary *)data; + + //delete object represents by data from database + - (void) destroy: (NSDictionary *)data; + + //if you are going to create/update bunch of items - use these methods to optimize database access + //these are equivalent to start/commit transaction + - (void) startBulkUpdate; + - (void) stopBulkUpdate; + + //check does model was modified and not yet synced + - (BOOL) is_changed; + +#### RhoConnectNotify + +This class provides access to sync notification objects as described [here](../guide/using_rhoconnect#setting-up-notifications): + + :::cplusplus + @property int total_count; + @property int processed_count; + @property int cumulative_count; + @property int source_id; + @property int error_code; + @property(assign) NSString* source_name; + @property(assign) NSString* status; + @property(assign) NSString* sync_type; + @property(assign) NSString* error_message; + @property(assign) NSString* callback_params; + + - (Boolean) hasCreateErrors; + - (Boolean) hasUpdateErrors; + - (Boolean) hasDeleteErrors; + - (Boolean) isUnknownClientError; + +#### RhoConnectObjectNotify + +This class provides access to sync object notification as described [here](../guide/using_rhoconnect#setting-up-notifications): + + :::cplusplus + @property(readonly) NSMutableArray* deleted_objects; + @property(readonly) NSMutableArray* updated_objects; + @property(readonly) NSMutableArray* created_objects; + + @property(readonly) NSMutableArray* deleted_source_ids; + @property(readonly) NSMutableArray* updated_source_ids; + @property(readonly) NSMutableArray* created_source_ids; + +### Samples + +See [rhoconnect-client\Samples\ObjectiveC\store](http://github.com/rhomobile/rhodes/tree/master/rhoconnect-client/Samples/ObjectiveC/store/) as an example. + +#### Initialization + + :::cplusplus + [RhoConnectClient initDatabase]; + + RhomModel* customer = [[RhomModel alloc] init]; + customer.name = @"Customer"; + + RhomModel* product = [[RhomModel alloc] init]; + product.name = @"Product"; + + RhomModel* order = [[RhomModel alloc] init]; + order.name = @"Order"; + order.associations = [NSDictionary dictionaryWithObjectsAndKeys: @"Customer", @"customer", @"Product", @"product", nil]; + + RhoConnectClient* sclient = [[RhoConnectClient alloc] init]; + NSArray* models = [NSArray arrayWithObjects:customer, product, order, nil]; + + [sclient addModels:models]; + + sclient.sync_server = @"http://rhodes-store-server.heroku.com/application"; + +#### Initialization of Schema model + + :::cplusplus + RhomModel* product = [[RhomModel alloc] init]; + product.name = @"Product_s"; + product.model_type = RMT_PROPERTY_FIXEDSCHEMA; + +To create schema model tables edit database schema file: + +* Copy file /shared/db/res/db/syncdb.schema to your project folder + +* Edit file syncdb.schema : add create table statement for each schema model. Note that mandatory object column should be in each table: + + "object" varchar(255) PRIMARY KEY + +** NOTE: Do not use NOT NULL statement in column definitions. RhoConnect client delete object attributes by setting value to null, when all object attributes become nulls, object deleted. So objects with NOT NULL columns will not be deleted. ** + +* Open 'Copy bundle resources' build phase in project target and point it to local project db folder + + +#### Login + + :::cplusplus + RhoConnectNotify* res = [ [RhoConnectEngine sharedInstance].syncClient loginWithUser:txtUser pwd:txtPwd]; + if ( res.error_code != RHO_ERR_NONE || ![[RhoConnectEngine sharedInstance].syncClient is_logged_in]) + ;//show error page + else + ;//show success page + +#### Sync Data + + :::cplusplus + RhoConnectNotify* res = [[RhoConnectEngine sharedInstance].syncClient syncAll]; + +#### Fetch data + + :::cplusplus + NSMutableArray* arItems = [[RhoConnectEngine sharedInstance].product find_all:nil]; + NSDictionary* item = [arItems objectAtIndex: 0 ]; + textBrand = [item valueForKey:@"brand"]; + +#### Object Notifications + :::cplusplus + - (void)objectNotifyCallback:(RhoConnectObjectNotify*) notify + { + } + + NSMutableDictionary* item = [[NSMutableDictionary alloc] init]; + [item setValue:@"Test" forKey:@"name"]; + [product create:item]; + + [sclient setObjectNotification:@selector(objectNotifyCallback:) target:self]; + + [sclient addObjectNotify: [[item objectForKey:@"source_id"] intValue] szObject:[item valueForKey:@"object"] ]; + +#### Processing unknown-client error +Unknown client error return by server after resetting server database, removing particular client id from database or any other cases when server cannot find client id(sync server unique id of device). +Note that login session may still exist on server, so in this case client does not have to login again, just create new client id. +Processing of this error contain 2 steps: + +* When unknown client error is come from server, client should call database_client_reset and start new sync, to register new client id. + +* If login session also deleted or expired on the server, then customer has to login again. + +Example: + :::cplusplus + + - (void)syncAllCalback:(RhoConnectNotify*) notify + { + NSString* status = notify.status; + NSString* error = notify.error_message; + int err_code = notify.error_code; + + NSLog(@"syncAll DONE, status: '%s' , error_msg: '%s' , error_code: %d", + [status cStringUsingEncoding: NSUTF8StringEncoding], + [error cStringUsingEncoding: NSUTF8StringEncoding], + err_code + ); + + if ( [notify.status compare:@"in_progress"] == 0) { + + } else if ([notify.status compare:@"complete"] == 0) { + + [[RhoConnectEngine sharedInstance].syncClient clearNotification]; + + } else if ([notify.status compare:@"error"] == 0) { + + if([notify isUnknownClientError]) { + [[RhoConnectEngine sharedInstance].syncClient database_client_reset]; + [[RhoConnectEngine sharedInstance].syncClient setNotification: @selector(syncAllCalback:) target:self]; + [[RhoConnectEngine sharedInstance].syncClient syncAll]; + } else if( err_code == RHO_ERR_CLIENTISNOTLOGGEDIN + || err_code == RHO_ERR_UNATHORIZED) { + + NSLog(@"GO TO LOGIN PAGE!"); + // real code to trigger view transition goes here.. + } + } + } + +#### Processing server errors +* create-error: +has to be handled in sync callback. Otherwise sync will stop on this model. To fix create errors you should call Model.on_sync_create_error or SyncEngine.on_sync_create_error: + +* update-error: +If not handled, local modifications, which were failing on server, will never sync to server again. +So sync will work fine, but nobody will know about these changes. + +* delete-error: +If not handled, local modifications, which were failing on server, will never sync to server again. +So sync will work fine, but nobody will know about these changes. + +Example: + :::cplusplus + + - (void)syncAllCalback:(RhoConnectNotify*) notify + { + NSString* status = notify.status; + NSString* error = notify.error_message; + int err_code = notify.error_code; + + NSLog(@"syncAll DONE, status: '%s' , error_msg: '%s' , error_code: %d", + [status cStringUsingEncoding: NSUTF8StringEncoding], + [error cStringUsingEncoding: NSUTF8StringEncoding], + err_code + ); + + if ( [notify.status compare:@"in_progress"] == 0) { + + } else if ([notify.status compare:@"complete"] == 0) { + + [[RhoConnectEngine sharedInstance].syncClient clearNotification]; + + } else if ([notify.status compare:@"error"] == 0) { + + if([notify isUnknownClientError]) { + [[RhoConnectEngine sharedInstance].syncClient database_client_reset]; + [[RhoConnectEngine sharedInstance].syncClient setNotification: @selector(syncAllCalback:) target:self]; + [[RhoConnectEngine sharedInstance].syncClient syncAll]; + } else if( err_code == RHO_ERR_CLIENTISNOTLOGGEDIN + || err_code == RHO_ERR_UNATHORIZED) { + + NSLog(@"GO TO LOGIN PAGE!"); + // real code to trigger view transition goes here.. + }else + { + //This is mandatory: + if([notify hasCreateErrors]) { + [[RhoConnectEngine sharedInstance].syncClient onCreateError: notify action:@"delete"]; + } + //These are optional: + /* + if([notify hasUpdateErrors]) { + [[RhoConnectEngine sharedInstance].syncClient onUpdateError: notify action:@"rollback"]; + } + if([notify hasDeleteErrors]) { + [[RhoConnectEngine sharedInstance].syncClient onDeleteError: notify action:@"retry"]; + } + */ + } + } + } + +#### Run SQL query on Schema model + + :::cplusplus + NSArray* params = [NSArray arrayWithObjects: @"Apple", nil]; + NSMutableArray* items2 = [product find_bysql:@"SELECT * FROM Product_s WHERE name=?" args: params]; + //items2 is an Array of NSDictionary* (NSString* to NSString*) + +## Android Java Client + +### Getting started +* The RhoConnect Client is part of the Rhodes repository. You can get it [on github](https://github.com/rhomobile/rhodes/downloads) (select the latest 'rhoconnect-client' package). + +* The RhoConnect Client for Android contains two files: + + * rhoimpl.jar - Java part of RhoConnect Client library + + * librhoconnectclient.so - native part of RhoConnect Client library + +These can be build from /rhoconnect-client directory with next command + + :::shell + $>rake android:default + +* Create new Android project or open existing one in Eclipse. Add rhoimple.jar to your project build path and copy librhoconnectclient.so to /libs/armeabi, so both Java and native parts of RhoConnect Client library will link with your project. + +* Copy all files and subfolders from /rhoconnect-client/Java/RhoConnect/assets to assets folder of your Android project. + +### RhoConnectClient initialization + +* Load native library before any RhoConnect client usage. Example of appropriate place to do so is Android application's onCreate method + + :::java + + import android.app.Application; + public class SampleApplication extends Application + { + public void onCreate() { + System.loadLibrary("rhoconnectclient"); + } + } + +* Configure and initialize RhoConnect library. Example of appropriate place to do so is main Activity onCreate method + +* Login to RhoConnect server + + :::cplusplus + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + ApplicationInfo appInfo = getApplicationInfo(); + + try { + RhoFileApi.initRootPath(appInfo.dataDir, appInfo.sourceDir); + RhoFileApi.init(this.getApplicationContext()); + + RhoLogConf.setMinSeverity(0); + RhoLogConf.setEnabledCategories("*"); + + RhoConnectClient.nativeInit(); + } catch (Exception e) { + Logger.E(TAG, e.getMessage()); + } + mSyncClient = new RhoConnectClient(); + mModels = new RhomModel[]{ + new RhomModel("Customer", RhomModel.SYNC_TYPE_INCREMENTAL), + new RhomModel("Product", RhomModel.SYNC_TYPE_INCREMENTAL) + }; + mSyncClient.initialize(mModels); + mSyncClient.setPollInterval(0); + mSyncClient.setSyncServer("http://rhodes-store-server.heroku.com/application"); + mSyncClient.setBulkSyncState(1); + mSyncClient.loginWithUserAsync("", "", new RhoConnectNotify.IDelegate() { + public void call(RhoConnectNotify notify) { onLogin(notify); } }); + } + public void onLogin(RhoConnectNotify notify) { + // Handle login event + } + +Note: RhoConnect callbacks (like passed to RhoConnectClient.loginWithUserAsync method in example above) may and most possibly will be called from another thread. It is up to application developer to care about synchronizing or forwarding call to an appropriate thread like GUI thread or Service thread. + +### Object Model + +#### Intro + +RhoConnect Client Android Java API resides at com.rhomobile.rhoconnect package. It contains two main classes: RhoConnectClient and RhomModel. The package also contains two classes which represent results of call to the API. These are RhoConnectNotify and RhoConnectObjectNotify. +Also several utility classes from com.rhomobile.rhodes package can be used. These are RhoConf, RhoLogConf, Logger. + +#### RhoConnectClient + + :::cplusplus + package com.rhomobile.rhoconnect; + public class RhoConnectClient{ + /// Call this method before create and use the client. It sets up directory structure and makes necessary native library initialization. + public static native void nativeInit(); + /// Creates instance of RhoConnectClient singlethon (yes, it's only one instance of RhoConnectClient allowed). + public RhoConnectClient(); + /// Call this method to close network connections and release any resources gracefully + public synchronized void close(); + /// Makes db models initialization. This call must be made just after RhoConnectClient construction and before any other calls to RhoConnectClient object. + public native void initialize(RhomModel models[]); + /// Sets up server URL to sync (RhoConnect server) + public native void setSyncServer(String url); + /// Forces synchronous or asynchronous RhoConnectClient mode + /// true - asynchronous mode (default) + /// false - synchronous mode + public native void setThreadedMode(boolean mode); + /// Sets/gets auto sync interval. 0 - disable auto sync + public native void setPollInterval(int interval); + public native int getPollInterval(); + /// + public native void setBulkSyncState(int state); + public native int getBulkSyncState(); + /// Set get various configuration parameters. + public native void setConfigString(String name, String param); + public native String getConfigString(String name); + /// Reset all data for all models in local database, also perform logout + public native void databaseFullResetAndLogout(); + /// Checks does login session exists in the database + public native boolean isLoggedIn(); + /// Logins to RhoConnect server and keep login session in database + public native RhoConnectNotify loginWithUserSync(String user, String pass); + /// Logins to RhoConnect server and keep login session in database. + /// callback will be called when operation has finished. + public native void loginWithUserAsync(String user, String pass, RhoConnectNotify.IDelegate callback); + /// Runs sync of all models + public native RhoConnectNotify syncAll(); + } + +#### RhomModel + + :::cplusplus + package com.rhomobile.rhoconnect; + public class RhomModel { + /// Possible model types + public final static int MODEL_TYPE_PROPERTY_BAG = 0; + public final static int MODEL_TYPE_FIXED_SCHEMA = 1; + /// Possible sync types + public final static int SYNC_TYPE_NONE = 0; + public final static int SYNC_TYPE_INCREMENTAL = 1; + public final static int SYNC_TYPE_BULK_ONLY = 2; + /// Constructor + public RhomModel(String name, int syncType); + /// Returns the model name + public String getName() { return mName; } + /// Returns the model type + public int getModelType() { return mModelType; } + /// Sets the model type + public void setModelType(int type) { mModelType = type; } + // Returns the model sync type + public int getSyncType() { return mSyncType; } + /// Sets the model sync type + public void setSyncType(int type) { mSyncType = type; } + /// Returns the model sync priority + public int getSyncPriority() { return mSyncPriority; } + /// Sets the model sync priority + public void setSyncPriority(int prio) { mSyncPriority = prio; } + /// Returns the model partition + public String getPartition() { return mPartition; } + /// Sets the model partition + public void setPartition(String part) { mPartition = part; } + /// Runs sync of the model + public RhoConnectNotify sync(); + /// Creates model object with properties and save to database, object id will be generated automatically if not set + public void create(Map props); + /// Finds object by object id + public Map find(String objectId) + /// Saves changes to existing object + public void save(Map item); + /// Destroys existing object + public void destroy(Map item) { + + // Returns first object which matches the condition + public Map findFirst(Map condition); + // Returns all objects which matched the condition + public Collection > findAll(Map condition); + + public void startBulkUpdate(); + public void stopBulkUpdate(); + } + +#### RhoConnectNotify + + :::cplusplus + package com.rhomobile.rhoconnect; + public class RhoConnectNotify { + public int getTotalCount() { return mTotalCount; } + public int getProcessedCount() { return mProcessedCount; } + public int getCumulativeCount() { return mCumulativeCount; } + public int getSourceId() { return mSourceId; } + public int getErrorCode() { return mErrorCode; } + public String getSourceName() { return mSourceName; } + public String getStatus() { return mStatus; } + public String getSyncType() { return mSyncType; } + public String getErrorMessage() + public String getCallbackParams() { return mParams; } + /// Developer need to implement and pass reference to this interface + /// in order to get call back when asynchronous operation has completed + public static interface IDelegate { + public void call(RhoConnectNotify notify); + } + } + +#### RhoConnectObjectNotyfy + + :::cplusplus + package com.rhomobile.rhoconnect; + public interface RhoConnectObjectNotify { + public String[] getDeletedObjects(); + public String[] getUpdatedObjects(); + public String[] getCreatedObjects(); + + public int[] getDeletedSourceIds(); + public int[] getUpdatedSourceIds(); + public int[] getCreatedSourceIds(); + + /// Developer need to implement and pass reference to this interface + /// in order to get call back when objects are created, updated or destroyed at sync server + public static interface IDelegate { + public void call(RhoConnectObjectNotify notify); + } + } + +### Samples + +* See android_store sample [rhoconnect-client\Samples\Java\android_store](http://github.com/rhomobile/rhoconnect-client/tree/master/rhoconnect-client/Samples/Java/android_store/) as an example. +* See android test Eclipse project [rhoconnect-client\Java\Android\test](http://github.com/rhomobile/rhoconnect-client/tree/master/rhoconnect-client/Java/Android/test/) as another example. + +## Packaging RhoConnect Client +To package the RhoConnect Client archive for distribution, go to the top of the rhodes repository and run: + + :::term + $ rake build:rhoconnect_client + +This will produce a zipfile in the folder called `rhoconnect-client-.zip` where `` is the version of the client. + +## Release procedure +1. Unzip package to some folder + +2. Open project `rhoconnect-client\ObjectiveC\Tests\RhoConnectClientTest` in xcode and run. See log - SUCCESS should be at the end of log + +3. Open project `rhoconnect-client\Samples\ObjectiveC\store` in xcode and run. Press Login, you should see several items, click on item, you should see details diff --git a/docs/en/5.5/rhoconnect/command-line.md b/docs/en/5.5/rhoconnect/command-line.md new file mode 100644 index 00000000..be85ed1e --- /dev/null +++ b/docs/en/5.5/rhoconnect/command-line.md @@ -0,0 +1,223 @@ +Generating a RhoConnect Application +=== + +You can generate a RhoConnect app with RhoStudio or with the `rhoconnect` utility command line tool. + +## Generating a RhoConnect App with RhoStudio + +In RhoStudio, select File->New->Project... + +The New Project window opens. Select the RhoConnect application wizard and click the Next button. + + + +Enter the name for your RhoConnect application in Project name. You may specify a specific folder for your destination where your project is stored, by default, the destination is your RhoStudio workspace folder. Then press the Finish button. + + + +## Generating a RhoConnect App from the Command Line + +The `rhoconnect` utility is a command line tool for generating RhoConnect applications and source adapters. + +The app name is passed as a parameter. The `rhoconnect` utility will generate a directory for your application with all the necessary files to get started. We will start with running `rhoconnect help app` to see the usage: + + :::term + Usage: + rhoconnect app NAME + + Generates a new rhoconnect application. + +For example: + + :::term + $ rhoconnect app storeserver + Generating with app generator: + [32m [ADDED] [0m storeserver/config.ru + [32m [ADDED] [0m storeserver/Gemfile + [32m [ADDED] [0m storeserver/.gitignore + [32m [ADDED] [0m storeserver/settings/settings.yml + [32m [ADDED] [0m storeserver/settings/license.key + [32m [ADDED] [0m storeserver/Rakefile + [32m [ADDED] [0m storeserver/.rcgemfile + [32m [ADDED] [0m storeserver/public + [32m [ADDED] [0m storeserver/controllers/ruby/application_controller.rb + [32m [ADDED] [0m storeserver/spec/controllers/ruby/application_controller_spec.rb + [32m [ADDED] [0m storeserver/spec/spec_helper.rb + +The generator will then run `bundle install` for you. + + :::term + Executing 'bundle install' for the first time in your freshly baked application! + bundle install --gemfile=/Users//guides/storeserver/Gemfile + +Here's a basic rundown of each of the files that were just generated: + + +* **config.ru** - This is a rackup file which will load your application. RhoConnect uses the excellent [sinatra](http://www.sinatrarb.com/) web framework to run the application. +* **settings/settings.yml** - This contains settings such as your redis connection, which source adapters exist and their parameters. You can also put custom settings here. +* **settings/license.key** - The RhoConnect [license](licensing) associated with your application. The default license allows up to 10 devices to synchronize with the application. +* **application_controller.rb** - The RhoConnect application class where you can implement authentication. You can also add other custom methods here to use in your application. +* **Rakefile** - This contains tasks that can be run from the terminal. +* **Gemfile** - This file specifies application's dependencies using [bundler](http://gembundler.com/). +* **spec/spec_helper.rb** - A helper file which loads the environment for running [specs](testing). + +## Rhoconnect Command Line Interface + +In rhoconnect versions 3.2 and higher, a ruby utility called [thor](https://github.com/wycats/thor) routes all rake-like tasks through a custom command-line interface. All tasks are used via the rhoconnect gem's command line interface. + +To issue commands this way, type `rhoconnect` followed by the task you wish to perform. To see a list of all the tasks you can issue with +rhoconnect, type `rhoconnect` or `rhoconnect help`. + + :::term + $ rhoconnect help + Commands: + rhoconnect app NAME [options] # Generate a new rhoconnect application + rhoconnect attach # Attach to rhoconnect console + rhoconnect console [environment] # Run rhoconnect console + rhoconnect dtach-about # About dtach + rhoconnect dtach-install # Install dtach program from sources + rhoconnect flushdb # Flush data store - WARNING: THIS REMOVES ALL DATA IN RHOCONNECT + rhoconnect get-token # Fetch current api token from rhoconnect + rhoconnect help [COMMAND] # Describe available commands or one specific command + rhoconnect redis-about # About redis + rhoconnect redis-attach # Attach to redis dtach socket + rhoconnect redis-download # Download redis release 2.6.11 + rhoconnect redis-install # Install the latest verison of Redis from Github (requires git, duh) + rhoconnect redis-restart # Restart redis on localhost + rhoconnect redis-start # Start redis on localhost + rhoconnect redis-status # Show status of redis servers + rhoconnect redis-stop # Stop redis running on localhost + rhoconnect restart [options] # Alias for `rhoconnect stop; rhoconnect start` + rhoconnect routes # Prints out routes defined in the application + rhoconnect secret # Generate a cryptographically secure secret session key + rhoconnect set-admin-password # Set the admin password + rhoconnect source NAME [options] # Generate a new source adapter + rhoconnect start [options] # Start rhoconnect server + rhoconnect stop # Stop rhoconnect server + rhoconnect update # Update an existing application to the latest rhoconnect release + rhoconnect version # Display rhoconnect version + rhoconnect web # Launch the web console in a browser + +**NOTE: The `rhoconnect war` command is available only if you switch to jruby, such as using the command `rvm use jruby`.** + +`rhoconnect start` and `rhoconnect restart` have the following options. + + -p, [--port=N] # Use port (default: 9292) + -r, [--redis=REDIS] # Redis server settings: (default: localhost:6379) + -P, [--push-server=PUSH_SERVER] # Push server settings (default: http://someappname@localhost:8675/) + -t, [--api-token=API_TOKEN] # API token (default: my-rhoconnect-token) + -f, [--config=CONFIG] # /path/to/rhoconnect/settings.yml file + -l, [--licenseflie=LICENSEFLIE] # /path/to/license.key file + +### Start the Application + +**NOTE: If you have not already done so, make sure you install Redis and Dtach (Mac OS/Linux only) in the [Installing Rhoconnect doc](install#installing-redis) before continuing.** + +In your command console or terminal on Mac OSX, change directories to your RhoConnect app's directory and start redis. + + :::term + $ cd storeserver + $ rhoconnect redis-start + +Open a new console window (since the redis server is running in the previous console window) or dtach the current running redis instance with Ctrl+\\. Then start your rhoconnect application. + + :::term + $ rhoconnect start + +#### Starting RhoConnect without a Source Adapter Application + +You can also start RhoConnect in a directory that does not contain a RhoConnect source adapter application. This is useful for RhoConnect plugin developers, who do not write a RhoConnect source adapter application: they can start a RhoConnect server from an empty directory. + + :::term + $ cd (an empty directory) + $ rhoconnect start + +When you start RhoConnect in a directory that does not contain a rhoconnect source adapter application, a hidden settings file, .rhoconnect.yml, is created in your user home directory. Here is a partial sample listing. + + :development: &70196107903780 + :syncserver: http://localhost:9393 + :redis: localhost:6379 + :push_server: http://someappname@localhost:8675/ + :api_token: my-rhoconnect-token + :secret: !binary |- + ... + :test: *70196107903780 + :production: *70196107903780 + +Once .rhoconnect.yml has been created in your user home directory, you can manually modify it for the next time you start RhoConnect. For example, you could change the port upon which the syncserver runs. + +Running RhoConnect this way uses the default license key in the RhoConnect gem. You can use other license keys by using the `-l` option in the `rhoconnect start` command. + +#### Opening the Web Console + +If everything went well when you started RhoConnect, you should see the following in your console: + + [03:52:15 PM 2013-03-12] Rhoconnect Server v4.0.0 started... + +To open the web console, navigate to [http://localhost:9292/](http://localhost:9292) in your browser or run: + + :::term + $ rhoconnect web + +### Creating executable WAR containers (JRuby environment only) + +It is possible to create Java WAR containers for your Rhoconnect application that can be deployed into the +Java App Servers (for example, Tomcat, JBoss). To create the executable WAR container, execute the following command in your app's root directory: + + :::term + $ cd storeserver + $ rhoconnect war + +This will build the WAR file named `storeserver.war` that can be deployed into the Java App Server. Also warbler package includes + an application launcher script, so you can run it standalone on port 8080 in java environment: + + :::term + $ java -jar storeserver.war + +To open the web console, navigate to [http://localhost:8080/](http://localhost:8080) in your browser. + +### Common Tasks + +RhoConnect applications come with many useful rhoconnect tasks for administrative and development workflows. Some common ones are: + +* `rhoconnect dtach-install` - (Mac OS / Linux only) This will install [dtach](http://dtach.sourceforge.net/) to /usr/local/bin. + +* `rhoconnect redis-install` - This will install to the system. On Mac OS / Linux, it will attempt to install in '/usr/local/bin' (on windows, C:\redis-), unless you have specified a REDIS_HOME to use instead. +If you cannot install redis on Linux due to insufficient user permissions, then follows these [instructions](install). + +* `rhoconnect set-admin-password` - Set the RhoConnect administrator password. The default password is blank ''. + +* `rhoconnect get-token` - Get a RhoConnect API token to use for calling the RhoConnect REST API. + +**NOTE: On Mac OS / Linux, you need to install dtach (i.e. by running `rhoconnect dtach-install`) to run the following tasks: ** + +* `rhoconnect redis-start` - Start redis on localhost. + +* `rhoconnect redis-stop` - Stop redis running on localhost. + +* `rhoconnect redis-status` - Show status of redis servers. + +* `rhoconnect redis-attach` - (Mac OS / Linux only) Attach to a currently-running redis server. + +* `rhoconnect start` - Start the RhoConnect application in a new console. This requires a running redis server. + +* `rhoconnect stop` - Stop the currently-running RhoConnect application. + +* `rhoconnect attach` - (Mac OS / Linux only) Attach to a currently-running RhoConnect application. + +Some other useful development tasks: + +* `rhoconnect spec` - Run all source adapter specs in spec/sources/. + +* `rhoconnect web` - Open the RhoConnect web console in a browser. + +## Generate Source + +Connecting to a backend service with RhoConnect requires that you write a small amount of code for the query, create, update and delete operations of your particular enterprise backend. The collection of the code for these operations is called a source. You can create source for your RhoConnect application two ways: + + * [RhoConnect source adapter](source-adapters): generate a Ruby code source adapter from RhoStudio or from the command line, similar to how you generate a RhoConnect app. This source adapter contains code for the query, create, update and delete operations. + + * [RhoConnect plugin](plugin-intro): write the source code (the query, create, update and delete operations) into your backend application, and plug a RhoConnect plugin in the application. The plugin is written in the language that matchs your backend application, such as Java or .NET. + +## Rake Tasks (Removed) +As of version 4.0, the rhoconnect rake tasks have been removed. You can use `rhoconnect --help` to see the list of available rhoconnect commands. \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/cud-conflicts.md b/docs/en/5.5/rhoconnect/cud-conflicts.md new file mode 100644 index 00000000..a7180321 --- /dev/null +++ b/docs/en/5.5/rhoconnect/cud-conflicts.md @@ -0,0 +1,68 @@ +Resolving Conflicts +=== + +Create,Update,Delete Queue and Potential Conflicts +--- + +By design, your RhoConnect application supports parallel dispatching of the multiple client's requests via the asynchronous Resque jobs. This scenario can lead to a situation where two or more clients will try to perform create,update, and delete operations at the same time, potentially creating the race condition. For example, this can happen when two users will try to insert or delete the same record simultaneously. +To handle this situation, RhoConnect uses the create,update,delete (or CUD) queue, which is being dispatched continuously. You can inspect this queue before the CUD operation is called and mark the conflicting records for special processing. To do this, you need to override the Source Adapter `validate` method that is called before the CUD queue is dispatched. This method has the following parameters: + + + + + + + + + + + + + + + + + +
                                                                              StringoperationCUD operation marker, one of three: create, update, or delete
                                                                              Array Of Record Hashescud_queueCUD queue consisting of CUD request hashes, ordered from oldest to newest. Each entry in the queue contains a hash of CUD records to process. (Each CUD client request can contain more than one record)
                                                                              Array Of Client Idsclient_queueThis array is used to map the CUD request in the above queue to a corresponding client ID. i.e. cud_queue[n] request was issued by client_queue[n] client. Please note that there may be several entries from the same client - if they came separately in time
                                                                              + +Below you can see the example of the `validate` method parameters indicating two create requests containing the conflicting records: + + :::ruby + client_1 = 'cid_1' + cud_request_1 = { 'temp_cid1_1' => {'name' => 'iPhone'}, 'temp_cid1_2' => {'name' => 'Android'}} + client_2 = 'cid_2' + cud_request_2 = { 'temp_cid2_1' => {'name' => 'iPhone'}} # this record seems to be the duplicate of the record 'temp_cid1_1' + + operation = 'create' + cud_queue = [ cud_request_1, cud_request_2 ] + client_ids = [ client_1, client_2 ] + +Detecting the Conflict and Forcing an Error +--- + +Using the above `validate` method you can iterate through the queue and detect CUD conflicts based on the desired application logic. Once the conflicting record is found (for example, duplicate create request), you need to mark it by inserting the conflicting record parameters into the special hash structure that is returned by the `validate` method: + + :::ruby + def validate(operation, cud_queue, client_ids) + resulting_meta_hash = {} + + # iterating through the queue + cud_queue.each_with_index do |cud_request, index| + cud_request_client = client_ids[index] + + # iterating through the request records + cud_request.each do |record_id, record_hash| + # ... detecting the conflict here .... + + # !!! found a conflict - force an error + error_record_id = record_id + record_meta_data = { error_record_id => { :error => 'my_error_string: conflict is detected!!!' }} + resulting_meta_hash[index] ||= {} + resulting_meta_hash[index].merge!(record_meta_data) + end + end + resulting_meta_hash + end + +Once the `validate` method returns a non-empty validation metadata hash structure, it will be used in processing the CUD queue. All marked records will not be processed, but instead an error will be sent back to the originating client with the user-provided error message. + \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/data-partitioning.md b/docs/en/5.5/rhoconnect/data-partitioning.md new file mode 100644 index 00000000..96d91df0 --- /dev/null +++ b/docs/en/5.5/rhoconnect/data-partitioning.md @@ -0,0 +1,55 @@ +Data Partitioning & Pass-Through +=== + +## Data Partitioning + +Data is stored in RhoConnect using [redis sets](http://redis.io/commands#set). The `@result` hash from the `query` method is stored in redis and referred to as the Master Document or MD. + +The MD is referenced in RhoConnect by a corresponding partition. Source adapters can partition data in two ways: user and app. As you might have guessed, user partitioning stores a copy of the source adapter MD for each user (one copy shared across all devices for a given user). + +Likewise, app partitioning stores one copy of the source adapter MD for the entire application (all users and devices share the same data). App partitioning can be particularly useful if you have source adapter models which retrieve large amounts of data that is fixed from user to user, for example a global product catalog. Using app partitioning wherever possible ***greatly reduces*** the amount of data in redis. + +### App Partition +Enable app partitioning the same way: + + :::yaml + :sources: + Product: + :poll_interval: 300 + :partition_type: app + +Now you have a single copy of the `Product` source adapter dataset for all users. + +### User Partition +User partitioning is the default mode for source adapters, however you can explicitly define it in `settings/settings.yml` with: + + :::yaml + :sources: + Product: + :poll_interval: 300 + :partition_type: user + +### Custom User partitioning +Sometimes, different groups of users share the common source data. To leverage this, you can implement the following method in your Source Adapter Model to provide custom partition names for the users with shared data. In this case, RhoConnect will store the data for MD of the grouped users under your custom name, which will reduce the memory footprint in Redis. From this standpoint, `app` partition is the edge-case of the custom user partitioning where all users share the same data for the particular source. + +To use the custom user partitioning, implement the following class method in your Source Adapter's model: + + :::ruby + class Product < Rhoconnect::Model::Base + # group users by the first letter + def self.partition_name(user_id) + return user_id[0] + end + end + +## Pass Through +RhoConnect provides a simple way to keep data out of redis. If you have sensitive data that you do not want saved in redis, add the `pass_through` option in settings/settings.yml for each source: + +**NOTE: When enabling pass_through for a model in your RhoConnect app, it is necessary to also enable pass_through for your client-side app. See the [Rhom Ruby Doc](../guide/rhom_ruby#using-models) section on using models for more information.** + + :::yaml + :sources: + Product: + :pass_through: true + +**NOTE: When running query or search the entire data set will be returned from your backend service. ** diff --git a/docs/en/5.5/rhoconnect/deploying.md b/docs/en/5.5/rhoconnect/deploying.md new file mode 100644 index 00000000..3b38cef7 --- /dev/null +++ b/docs/en/5.5/rhoconnect/deploying.md @@ -0,0 +1,579 @@ +# Deploying a RhoConnect Application + +## Deploying On-Premise +The [sinatra book](http://sinatra-book.gittr.com/) has some great [deployment documentation](http://sinatra-book.gittr.com/#deployment) that you should review before running your RhoConnect application in production. + +## Deploying packaged RhoConnect software on Linux servers + +You can create RhoConnect production environment on Linux servers by installing software packages +for Ubuntu and CentOS respectively. At this moment supported formats are Debian (deb) and Red Hat (rpm) packages. + +Every package provides the following components: + +* Ruby, version 1.9.3 + +* Node.js, version v0.10.x + +* Nginx HTTP server, release 1.3.x + +* Thin application server, release 1.5.x + +* Redis data store, release 2.6.x + +* Latest RhoConnect gem with all required dependencies + +In addition, RPM package provides latest sqlite3 headers and binaries, because standard Cent OS (5.x) libraries for sqlite3 outdated. + +### Getting the Packages + +To download the RhoConnect debian package, you first must add our repo to your list of sources. + +#### Steps for Debian-Based Linux Users +Add the following line to the end of your /etc/apt/sources.list: + + :::text + deb http://rhoconnect.s3.amazonaws.com/packages/deb rhoconnect main + +**NOTE: If you want to get the package with cool new features from the Beta repository, then define repo url as `http://rhoconnect.s3.amazonaws.com/beta-packages/deb`** + +Once the repo is added apt-get needs to be updated: + + :::term + $ sudo apt-get update + +Once that is done, it is time to install RhoConnect: + + :::term + $ sudo apt-get install rhoconnect + +#### Steps for RedHat-Based Linux Users +Prerequisites: target Linux server should include CentOS Development tools. +To install them, use the this command + + :::term + $ yum groupinstall 'Development Tools' + +It will install for you such tools as GNU GCC C/C++ compiler, make and others. + +Vanilla CentOS distribution does not include some packages required by RhoConnect installer. To resolve dependencies you +might wanted to use [Extra Packages for Enterprise Linux (EPEL) ](http://fedoraproject.org/wiki/EPEL) +repository and install Python26 out of it. + +For example, to enable EPEL repository for CentOS 5.x release execute these commands: + + :::term + $ wget http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm + $ rpm -i epel-release-5*.rpm + $ yum update + $ yum install python26 + +For CentOS 6.x release: + + :::term + $ wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm + $ rpm -i epel-release-6*.rpm + $ yum update + +Now you can create a file named rhoconnect.repo in the /etc/yum.repos.d/ directory: + + :::term + $ sudo vim /etc/yum.repos.d/rhoconnect.repo + +Copy and paste these contents into the file. + + :::text + [rhoconnect] + name=Rhoconnect + baseurl=http://rhoconnect.s3.amazonaws.com/packages/rpm + enabled=1 + gpgcheck=0 + +**NOTE: If you want to get the package with cool new features from the Beta repository, then define baseurl as `baseurl=http://rhoconnect.s3.amazonaws.com/beta-packages/rpm`** + +Once that is done, it is time to install RhoConnect: + + :::term + $ sudo yum install rhoconnect + +### Final Steps (After the installer is finished) +Installer also created and configured RhoConnect rhoapp application in /opt/nginx/html directory. +To test it you need to as a root user start redis, thin, and nginx servers: + + :::term + $ sudo /etc/init.d/redis start + $ sudo /etc/init.d/thin start + $ sudo /etc/init.d/nginx start + +And verify that it's up and running by visiting application web console in your browser: + + http://servername + +### Configuration of web and application servers +Installer compiled and configured Nginx as reverse proxy web server (/opt/nginx) with the following settings: + +* Nginx start-up script (`/etc/init.d/nginx`) + +* Nginx logrotate settings (`/etc/logrotate.d/nginx`) + +* Nginx configuration file (`/opt/nginx/conf/nginx.conf`) + +* virtual host template for rhoconnect application (`/opt/nginx/conf/conf.d/rhoconnect.conf`) + +Installer also configured Thin app server with the following configuration files: + +* Thin start-up script (`/etc/init.d/thin`) + +* Thin configuration file (`/etc/thin/rhoapp.yml`) + +Default setup of Nginx server is to deal with back-end servers (called "upstreams") that are running on UNIX domain sockets: + + :::text + # /opt/nginx/conf/conf.d/rhoconnect.conf file + + upstream thin_cluster { + least_conn; + server unix:/tmp/thin.0.sock; + server unix:/tmp/thin.1.sock; + # Add additional copies if need more Thin servers + #server unix:/tmp/thin.2.sock; + #server unix:/tmp/thin.3.sock; + } + + server { + listen 80; + # Be sure to point to 'public' folder of your application! + root /opt/nginx/html/rhoapp/public; + # ... + + } + +Thin application server runs as a cluster with /etc/thin/rhoapp.yml configuration file: + + :::yaml + --- + chdir: /opt/nginx/html/rhoapp + environment: production + timeout: 30 + log: /var/log/thin/thin.log + pid: /var/run/thin/thin.pid + max_conns: 1024 + max_persistent_conns: 512 + require: [] + wait: 30 + socket: /tmp/thin.sock + servers: 2 + daemonize: true + +Configuration file is generated by this command: + + :::term + $ thin config -C /etc/thin/rhoapp.yml -c /opt/nginx/html/rhoapp/ --socket /tmp/thin.sock --servers 2 --log /var/log/thin/thin.log --pid /var/run/thin/thin.pid -e production + +### Development and deployment of RhoConnect applications + +Packaged software does not setup automatically path to installed ruby bins and gems, so you need do it manually. Add necessary bins to the path(s) of the users who will be using this software. You may also wish to add these items +to your bash scripts (i.e. `~/.profile` on Ubuntu; `~/.bash_profile` on CentOS) to automatically add them upon login. + + :::text + export PATH=/opt/rhoconnect/bin:$PATH + +#### Deploying a rhoconnect app + +To deploy and develop your rhoconnect app on nginx and thin servers + +a) Copy your rhoconnect project (lets name it as `your_rhoconnect_app`) to default location to `/opt/nginx/html` directory + +b) Set up for it `nginx` owner + + :::term + $ cd /opt/nginx/html + $ sudo chown -R nginx:nginx your_rhoconnect_app/ + +c) Make sure that your app is bundled properly + + :::term + $ cd your_rhoconnect_app + $ sudo /opt/rhoconnect/bin/bundle install + +d) Configure Nginx virtual host for your rhoconnect application. For that edit the file +`/opt/nginx/conf/conf.d/rhoconnect.conf`, so that it reflects your specifications (root directive) + + :::text + # ... + server { + listen 80; + # Be sure your app have 'public' folder and root directive + # point to it! + root /opt/nginx/html/your_rhoconnect_app/public; + # ... + } + +e) Edit Thin `/etc/thin/rhoapp.yml` configuration file directly + + :::yaml + --- + chdir: /opt/nginx/html/your_rhoconnect_app + # ... + + or as root user generate a new one + + :::term + $ env PATH=/opt/rhoconnect/bin:$PATH thin config -C /etc/thin/your_rhoconnect_app.yml \ + -c /opt/nginx/html/your_rhoconnect_app/ \ + --socket /tmp/thin.sock --servers 2 --log /var/log/thin/thin.log \ + --user nginx --group nginx \ + --pid /var/run/thin/thin.pid -e production + +f) As root user restart Thin, and Nginx servers + + :::term + /etc/init.d/thin restart + /etc/init.d/nginx restart + + +#### Deploying multiple rhoconnect apps + +**NOTE: Deploying multiple rhoconnect apps on nginx has not yet been tested. Perform these steps only if you are experienced with nginx.** + +To deploy and develop two rhoconnect applications on nginx and thin servers, +refer to the nginx documentation on [nginx server blocks](http://wiki.nginx.org/ServerBlockExample) to see how to configure an nginx sever for multiple host names. + +For each rhoconnect app, you need to set up its own redis instance. Refer to [the redis quick start documentation](http://redis.io/topics/quickstart). + +If you have questions on setting this up, contact your system administrator. + +#### Monitoring and Logging + +For monitoring and troubleshooting purposes visit web console of your app and look at log files in `/opt/nginx/logs`. + +Also you can use RhoConnect `/opt/nginx/html/rhoapp` application as a template and modify it as you wanted. + +**NOTE: You should pay attentions to situations, if you have already Ruby installed on system level. Avoid usage of system gems in your application. It might lead to unpredictable results, if ruby versions are different. Either set up path to rhoconnect binaries for root user, or install required gems as `sudo /opt/rhoconnect/bin/gem install gem_name`** + +## Nginx configuration for SSL with self-signed certificate + +### About Self-Signed Certificates +A SSL certificate is a way to encrypt a site's information and create a more secure connection. +This chapter will take you through generating a self-signed certificate to use with Nginx. + +### Create a Directory for the Certificate +The SSL certificate has 2 main parts: the certificate itself and the public key. To make all of the relevant files easy to access, you should create a directory to store them in: + + :::term + $ sudo mkdir /opt/nginx/ssl + +We will perform the next few steps within the directory: + + :::term + $ cd /opt/nginx/ssl + + +### Create the Server Key and Certificate Signing Request +Start by creating the private server key. During this process, you will be asked to enter a specific passphrase. Be sure to note this phrase carefully, if you forget it or lose it, you will not be able to access the certificate. + + :::term + $ openssl genrsa -des3 -out server.key 1024 + Generating RSA private key, 1024 bit long modulus + ..........++++++ + ..................++++++ + e is 65537 (0x10001) + Enter pass phrase for server.key: + Verifying - Enter pass phrase for server.key: + +Follow up by creating a certificate signing request: + + :::term + $ openssl req -new -key server.key -out server.csr + +This command will prompt terminal to display a lists of fields that need to be filled in. +The most important line is "Common Name". Enter your official domain name here or, +if you don't have one yet, your site's IP address. Leave the challenge password and optional company name blank. + + :::term + Enter pass phrase for server.key: + You are about to be asked to enter information that will be incorporated + into your certificate request. + What you are about to enter is what is called a Distinguished Name or a DN. + There are quite a few fields but you can leave some blank + For some fields there will be a default value, + If you enter '.', the field will be left blank. + ----- + Country Name (2 letter code) [AU]:YOUR_COUNTRY + State or Province Name (full name) [Some-State]:YOUR_STATE + Locality Name (eg, city) []:YOUR_CITY + Organization Name (eg, company) [Internet Widgits Pty Ltd]:YOUR_COMPANY + Organizational Unit Name (eg, section) []:YOUR_UNIT + Common Name (eg, YOUR name) []:YOUR_DOMAINNAME_HERE + Email Address []:YOUR_EMAIL + + Please enter the following 'extra' attributes + to be sent with your certificate request + A challenge password []: + An optional company name []: + +### Remove the Passphrase +We are almost finished creating the certificate. However, it would serve us to remove the passphrase. Although having the passphrase in place does provide heightened security, the issue starts when one tries to reload nginx. In the event that nginx crashes or needs to reboot, you will always have to re-enter your passphrase to get your entire web server back online. + +Use these commands to remove the password: + :::term + $ cp server.key server.key.org + $ openssl rsa -in server.key.org -out server.key + + +### Sign your SSL Certificate +Your certificate is all but done, and you just have to sign it. + +Keep in mind that you can specify how long the certificate should remain valid by changing the 365 to the number of days you prefer. As it stands this certificate will expire after one year. + + :::term + $ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt + Signature ok + subject= ... + Getting Private key + +### Set Up the Certificate +Now we have all of the required components of the finished certificate. +The next thing to do is to set up the virtual host to serve your domain from HTTS connection. + +Update existing Nginx `/opt/nginx/conf/conf.d/https_rhoconnect.conf` configuration file by including the newly signed certificate and private key: + + :::term + upstream thin_cluster { + # ... + } + + # HTTPS server + server { + listen 443; + server_name YOUR_DOMAINNAME_HERE; + root /opt/nginx/html/#{app_name}/public; + + location / { + # ... + proxy_pass http://thin_cluster; + } + + ssl on; + ssl_certificate /opt/nginx/ssl/server.crt; + ssl_certificate_key /opt/nginx/ssl/server.key; + } + + +### Activate the Virtual Host +Restart nginx: + + :::term + $ /etc/init.d/nginx restart + +Now we're ready to access the above host using: + + :::term + https://YOUR_DOMAINNAME_HERE + + +## Deploying RhoConnect Redis and Push packages on Linux servers + +### RhoConnect Redis + +RhoConnect Redis is a packaged Redis server for RhoConnect development and production environment on Linux servers. +rhoconnect-redis package might be useful if you want to deploy Redis on separate server. + +The package compiles from sources latest stable Redis release (2.4.15) and installs it to `/opt/rhoconnect` directory with the following settings: + +* Redis server configuration file (`/opt/rhoconnect/etc/redis.conf`) + +* log files located in `/var/log/redis` directory + +* start-up scripts in `/etc/init` and `/etc/init.d` directories + +#### Steps for Debian-Based Linux Users +Add the following line to the end of your /etc/apt/sources.list. + + :::term + deb http://rhoconnect-repo.s3.amazonaws.com/packages/deb rhoconnect-repo main + +Then update the repo list and install RhoConnect Redis. + + :::term + $ sudo apt-get update + $ sudo apt-get install rhoconnect-redis + +When Redis server is successfully installed, start it using the following command. + + :::term + $ sudo start rhoconnect-redis + +#### Steps for RedHat-Based Linux Users + +Create a file named rhoconnect-repo.repo in the /etc/yum.repos.d/ directory. + + :::term + $ sudo nano /etc/yum.repos.d/rhoconnect-repo.repo + +Copy and paste these contents into the file. + + :::term + [rhoconnect-redis] + name=Rhoconnect Redis + baseurl=http://rhoconnect-repo.s3.amazonaws.com/packages/rpm + enabled=1 + gpgcheck=0 + +Once that is done, install the RhoConnect Push service. + + :::term + $ sudo yum install rhoconnect-redis + +You can start a redis server using the following command. + + :::term + $ sudo /etc/init.d/redis start + +### RhoConnect Push Service +You can create a RhoConnect Push production environment on Linux servers by installing prepackaged software for +Ubuntu (12.x) and CentOS (5.x/6.x). In a few clicks, you will have installed on your Linux server. + +* Node.js with Npm package manager + +* RhoConnect Push service + +* Upstart script to start, stop, and control Push service (for Ubuntu and CentOS 6.x) + +* `/etc/init.d/rhoconnect-push` init script to start, stop, and restart Push service (CentOS 5.x) + +Prerequisites: + + * Python 2.6 or 2.7 + +#### Steps for Debian-Based Linux Users +Add the following line to the end of your /etc/apt/sources.list. + + :::term + deb http://rhoconnect-repo.s3.amazonaws.com/packages/deb rhoconnect-repo main + +Then update the repo list and install RhoConnect Push. + + :::term + $ sudo apt-get update + $ sudo apt-get install rhoconnect-push + +#### Steps for RedHat-Based Linux Users +Node.js requires python 2.6 which is not available for CentOS 5 stock version. +For this flavor of linux you need to manually install EPEL repo and install python26 RPM out of it: + + :::term + $ wget http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm + $ rpm -i epel-release-5*.rpm + $ yum install python26 + + +Now create a file named rhoconnect-repo.repo in the /etc/yum.repos.d/ directory. + + :::term + $ sudo nano /etc/yum.repos.d/rhoconnect-repo.repo + +Copy and paste the following contents into the file. + + :::term + [rhoconnect-push] + name=Rhoconnect Push Service + baseurl=http://rhoconnect-repo.s3.amazonaws.com/packages/rpm + enabled=1 + gpgcheck=0 + +Once that is done, install the RhoConnect Push service. + + :::term + $ sudo yum install rhoconnect-push + + +## Deploying into J2EE environment +In JRuby environment, there is an option to create the WAR container for the RhoConnect app +and deploy it into the J2EE App Server. +(see the corresponding 'rake' task for creating the WAR containers). +Deploying the WAR container varies per J2EE App Server, for JBoss it is necessary +to place the WAR file into the server's deploy directory. + +#### Deploying warbler package on Apache Tomcat web server +To successfully deploy warbler package on Tomcat you need to make rhoconnect app be the default app. There are a few ways to reach +this goal and we describe only a couple of them. + +##### Method 1 + +1) Stop Tomcat `shutdown.sh` + +2) Delete the `ROOT` directory under `$CATALINA_BASE/webapps` + +3) Name your war file as `ROOT.war` (capitals mandatory) + +4) Drop the `ROOT.war` file directly in the `$CATALINA_BASE/webapps` directory + +5) Start Tomcat `startup.sh` + +##### Method 2 + +1) Stop Tomcat + +2) Copy your war file in `$CATALINA_BASE/webapps`, under its original name + +3) Turn off autoDeploy and deployOnStartup in your Host element in the server.xml file. + +4) Explicitly define your application context in server.xml, specifying both path (must be empty!) and docBase. + + :::xml + + + + + + +5) Start Tomcat + +## Deploying on Heroku + +#### Prerequisites + +* [Heroku account](https://api.heroku.com/login) and [Heroku Toolbelt](https://toolbelt.heroku.com/) + +* Rhoconnect version >= 3.4 + +#### Create Rhoconnect application +Create your Rhoconnect app and make sure that it's up and running in your development environment using thin: + + :::term + $ cd your_rhoconnect_app + $ bundle exec thin start + + +#### Deploy to Heroku +Heroku uses git as its deployment interface. To create and deploy your application on Heroku, use the the following steps: + + :::term + $ git init + $ git add . + $ git commit -m 'initial commit' + $ heroku create --buildpack=https://github.com/rhomobile/heroku-buildpack-ruby.git + $ heroku addons:add redistogo:nano + $ git push heroku master + $ heroku open + +#### Monitoring app on Heroku +Use `heroku ps` to determine the number of processes that are executing. +Use `heroku logs` to view an aggregated list of log messages from all process types. + + :::term + $ heroku ps + $ heroku logs + +#### Get connected with Rhodes client +If you have a rhodes client and want to sync it with your rhoconnect app on Heroku, then set the proper `syncserver` URL in `rhoconfig.txt`: + + :::term + syncserver = 'https://.herokuapp.com' + + + + + + diff --git a/docs/en/5.5/rhoconnect/extending-rhoconnect-server.md b/docs/en/5.5/rhoconnect/extending-rhoconnect-server.md new file mode 100644 index 00000000..33014fd5 --- /dev/null +++ b/docs/en/5.5/rhoconnect/extending-rhoconnect-server.md @@ -0,0 +1,91 @@ +Extending RhoConnect Application with custom routes +=== + +Adding custom routes to a Controller +--- + +You can provide custom routes support in your RhoConnect application and utilize all the powerful features of the typical Sinatra app. To do this, simply define your routes in the corresponding controller class. Endpoint URL for your routes will be relative to the controller's root. + +The following example illustrates how to add a sample `my_custom_route` to the Product Controller: + + :::ruby + class ProductController < Rhoconnect::Controller::Base + get '/my_custom_route', :login_required => true do + send_file 'public/my_file.png' + end + end + +This route will have the following URL : GET '/app/v1/Product/my_custom_route' + +The above custom route implementation will respond to client's GET request, verifies the current_user (which will be extracted from the RhoConnect session cookie and checked for validity by the `:login_required` condition) +and returns a static PNG file (which can be later used in BLOB syncs) + +Routes declaration order +--- + +At run-time all requests are being matched against the declared routes to find the appropriate route handler. Sinatra matches the routes sequentially in the order of their declaration until the first matching route signature is found. This can lead to a possibility where the declared route can hide subsequent routes. For example: + + :::ruby + class ProductController < Rhoconnect::Controller::Base + register Rhoconnect::Handler::Sync + + delete '/my_custom_route_delete', :login_required => true do + # do something here + end + end + +In the above example, user's custom route will never be called, because `register Rhoconnect::Handler::Sync` (which is responsible for [adding pre-defined SYNC routes](../rhoconnectapi/source-adapter-controller-api-ruby#register Rhoconnect::Handler::Sync)) will add `DELETE '/:id'` route. +As a result, ProductController will have the following routes map: + + * 1) DELETE '/:id' + * 2) DELETE '/my_custom_route_delete' + +At run-time, Controller will try to match `DELETE /my_custom_route_delete` with the FIRST appropriate route declaration - and, it will find that `DELETE '/:id'` is a good match. Controller will treat string `my_custom_route_delete` as an instance of an `:id` parameter. So, the user-defined custom route will never be called - it is being hidden by the more-generic route that has been declared first in order. + +In summary, you should always specify more-specific routes first followed by the more-generic routes. In the above example, moving the custom route's declaration above the line 'register Rhoconnect::Handler::Sync' will make the custom route match happening before the parametrized route. Alternatively, you can write your routes using "as unique as possible" signatures, i.e. in the above example, declaring the route as `DELETE '/my/custom_route/delete'` will not match any other route declaration. + +NOTE: You can always see the routes that are available in your application using the `rhoconnect routes` command. + +Using custom routes in BLOB syncs +--- + +After you create the new custom routes you can reference and use them from standard Rhodes applications. +For example, suppose you have a Rhodes app with a Product model. To use a custom route in BLOB syncs, define the following property in the Rhodes Product model (file: `app/Product/product.rb`): + + :::ruby + # The model has already been created by the framework, and extends Rhom::RhomObject + # You can add more methods here + class Product + include Rhom::PropertyBag + + # Uncomment the following line to enable sync with Product. + enable :sync + + #add model specific code here + property :my_custom_blob_field, :blob, :overwrite + end + +To see the static image, modify the `app/Product/show.erb` file for the Product model in your Rhodes application: + + :::html +
                                                                            • +
                                                                              My Static Field Image
                                                                              +
                                                                              +
                                                                            • + +Then, modify your RhoConnect source adapter model (in `rhoconnect_app/models/ruby/product.rb`) to provide BLOB's url for the `my_custom_blob_field`: + + :::ruby + def query(params=nil) + parsed = JSON.parse(RestClient.get("#{@base}.json").body) + + @result={} + parsed.each do |item| + item["product"]["my_custom_field-rhoblob"] = "http://localhost:9292/app/v1/Product/my_custom_route" + @result[item["product"]["id"].to_s] = item["product"] + end if parsed + end + +This way, your `my_custom_field` would be getting the BLOB image data from the custom route defined in your RhoConnect Source Adapter Controller. + +For more information on BLOB syncs, see [this section](blob-sync). \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/heroku-addon.md b/docs/en/5.5/rhoconnect/heroku-addon.md new file mode 100644 index 00000000..4a18901b --- /dev/null +++ b/docs/en/5.5/rhoconnect/heroku-addon.md @@ -0,0 +1,153 @@ +# RhoConnect Heroku Addon + +RhoConnect is a data synchronization server and client library that keeps enterprise app data current and available on users’ mobile devices. + +The information is stored locally on a user’s device, and is available even when disconnected and offline. + +Full documentation on all the capabilities of RhoConnect is in the [RhoConnect Developer Reference](http://docs.rhomobile.com/rhoconnect/introduction). + + +Overview +-------- +Combining Rhodes, RhoConnect, and `rhoconnect-rb` will allow you to create a mobile app that can connect to and manage your backend rails app seamlessly. + +

                                                                              + +Gem +----- +To install the latest stable RhoConnect gem, run: + + :::term + $ [sudo] gem install rhoconnect + +Using from Rails +------------ +`rhoconnect-rb` is a ruby gem that allows your rails app to interact with RhoConnect. To use RhoConnect from a rails application you must first install the `rhoconnect-rb` gem. + + :::term + $ [sudo] gem install rhoconnect-rb + +**NOTE: `rhoconnect-rb` only supports rails 3. You will not be able to connect your app to RhoConnect with rails < 3.** + +Load the `rhoconnect-rb` library + + :::ruby + require 'rhoconnect-rb' + +**NOTE: If you are using DataMapper, install the `dm-serializer` library and require it in your application. `rhoconnect-rb` depends on this utility to interact with RhoConnect applications using JSON.** + +###Configuration: + +You need to define a few configuration variables. You can define them in an initializer. Good practice is to create a file called rhoconnect.rb in the initializers directory of your rails app. Inside of your newly created rhoconnect.rb file you will define the following config block. + + :::ruby + Rhoconnectrb.configure do |config| + config.app_endpoint = "http://localhost:3000" + config.authenticate = lambda { |credentials| return true } + end + +Inside of this block three variables are defined. + +The `app_endpoint` is the location of your rails app. Defining this variable will cause your rails app to automatically (on startup) set the rails url location in your RhoConnect instance. If you do not define this variable, you will have to manually configure the Backend App URL in the RhoConnect console. + +The last variable, `authenticate`, is a lambda and can be used to setup any custom authentication you would like. The credentials passed will be a hash containing a login and password (`{'login' => login, 'password' => password}`). You can then write any custom authentication inside of this block. In the example above authentication is ignored. + +You can also alternatively define these variables in `environment.rb` as an environment variables. + + :::ruby + ENV['APP_ENDPOINT'] = "http://localhost:3000" + + +**NOTE: environment variables take precedence over config variables** + + +Next you will need to include `Rhoconnectrb::Resource` in the model you want to synchronize with your mobile application: + + :::ruby + class Product < ActiveRecord::Base + include Rhoconnectrb::Resource + end + +Or, if you are using DataMapper: + + :::ruby + class Product + include DataMapper::Resource + include Rhoconnectrb::Resource + end + +###Declaring a partition key + +Your model must declare a partition key for `rhoconnect-rb`. This partition key is used by `rhoconnect-rb` to uniquely identify the model dataset when it is stored in a RhoConnect application. It is typically an attribute on the model or related model. `rhoconnect-rb` supports two types of partitions: + +* app - No unique key will be used, a shared dataset is used for all users. +* lambda\{some lambda\} - Execute a lambda which returns the unique key string. + +For example, the Product model above might have a belongs_to :user relationship. + +The partition identifying the username would be declared as: + + :::ruby + class Product < ActiveRecord::Base + include Rhoconnectrb::Resource + + belongs_to :user + + def partition + lambda { self.user.username } + end + end + + +Deploying to Heroku +----------------------- +To use RhoConnect from Heroku, install the RhoConnect add-on: + + :::term + $ heroku addons:add rhoconnect + +###Setup + +From inside your Heroku account, setup the url to your backend service that RhoConnect will connect to. + +First, click the addons drop down and select RhoConnect. +

                                                                              + +You will be redirected to the admin console of your RhoConnect instance where you can set the Backend App url to your backend service. Select Backend App Url from the right menu. +

                                                                              + + +From here you can enter a url to your backend service. Enter a url (for example http://myrailsapp.com), and click the add link to save the url. + + +RhoConnect is now setup with your backend service. + +Connecting a simple rhodes app +------------------------------- +To view a full tutorial about creating a rhodes application and the features of rhodes see [Rhodes framework](http://docs.rhomobile.com/rhodes/tutorial). + +###Gem installation: + + :::term + $ gem install rhodes + +Next using the rhodes gem you can create a rhodes app. + + :::term + $ rhodes app sample_app url_of_rhoconnect_instance + +To get the value for the url_of_rhoconnect_instance argument, go to the RhoConnect console and click on the right Backend App URL link. From there you can copy the syncserver url. + +

                                                                              + +Other resources +---- +[RhoConnect Introduction](http://docs.rhomobile.com/rhoconnect/introduction) + +[RhoConnect Installation](http://docs.rhomobile.com/rhoconnect/install) + +[RhoConnect Tutorial](http://docs.rhomobile.com/rhoconnect/tutorial) + +[Using RhoConnect from Rails/Sinatra](http://docs.rhomobile.com/rhoconnect/rails-plugin) + +[Webinar Using Rhoconnect with Rhoconnect-rb](http://player.vimeo.com/video/27495682?byline=0&portrait=0&color=de0909) \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/install.md b/docs/en/5.5/rhoconnect/install.md new file mode 100644 index 00000000..5d65d59c --- /dev/null +++ b/docs/en/5.5/rhoconnect/install.md @@ -0,0 +1,154 @@ +# Installing RhoConnect + +This section discusses how to install the development environment for RhoConnect. For those who have developed a RhoConnect application, and now wish to deploy that RhoConnect application on a server, refer to the instructions for deploying a RhoConnect application, such as [preparing a RhoConnect app for production](preparing-production) and [deploying a RhoConnect application](deploying). + +## Installing RhoConnect with RhoStudio + +To install RhoConnect on a Windows or Macintosh platform, install RhoMobile Suite. The RhoMobile Suite installer installs Rho products, such as Rhodes, RhoConnect, RhoElements, and RhoStudio. RhoStudio is an Eclipse installation that facilitates development of native smart phone applications. + +[Click here for the RhoMobile Suite installation instructions](../guide/rhomobile-install). + +When you start RhoStudio, you set the location of the workspace directory. Set this path to a workspace directory that does not contain space symbols: if the path has spaces, a RhoConnect application created with RhoStudio will not work properly. + +NOTE: The rest of this chapter consists of instructions for installing RhoConnect from the command line, without using the RhoMobile Suite installer. You do not need to perform those instructions if you installed using the RhoMobile Suite installer. + +## Installing Ruby on Linux and Mac OSX + +Mac OS X comes with Ruby already pre-installed, but it’s an older version (1.8.7) which not supported by RhoConnect. +Every Linux distribution usually has Ruby packages and you should refer to your distribution's documentation and community forums for help installing it. +But, usually, these packages are behind and don't include latest Ruby versions. + +In nutshell, to have latest Ruby version you either need build it from sources, or use one of Ruby installers: + +1. Use [Ruby Version Manager](https://rvm.io) (RVM). RVM starting from v1.19 includes new `autolibs` feature and allow you to automatically install all dependencies on your system. RVM with `autolibs` enabled works with the system package manager. But in the case for OSX +there's no a default package manager, and you have to select what package manager will be installed with autolibs modes `osx_brew` (default), `osx_port`, `osx_fink` and `smf`. + +2. Manually download and install [Ruby v1.9.3](http://www.ruby-lang.org/en/downloads/). Your mileage may vary depending on your machine, since you will need to resolve all build and install dependencies on your own. + +Type this command to install stable RVM release: + + :::term + $ curl -L https://get.rvm.io | bash -s stable + +If you want get the libraries installed automatically, then use autolibs mode 4 a.k.a. enable. + + :::term + $ rvm autolibs 4 + +On Mac OSX you can also optionally enforce a package manager of your choice: + + :::term + $ rvm autolibs homebrew + +And, finally, install desired Ruby version: + + :::term + $ rvm install 1.9.3 + $ rvm install jruby + # rvm install 2.0.0 + +**NOTE: The full list of `autolibs` options is covered in the [RVM docs](https://rvm.io/rvm/autolibs/).** + +**NOTE: On Mac OSX to need to have `Xcode` and `Command Line Tools` installed.** + + +## Installing RhoConnect on Linux + +On Linux, you need the following setup before redis is installed. + + * The `/usr/local` directory exists and is recursively writable by the current user. + * The `/usr/local/etc/` directory exists and is recursively writable by the current user. + * You need a gcc toolchain installed, i.e. via build-essential package on Ubuntu/Debian. + +To install RhoConnect on Linux, you need to install the RhoConnect gem. Download and install: + + +1. Ruby Web Server - We tested with [thin](http://code.macournoyer.com/thin/), and [passenger](http://www.modrails.com/). WEBrick, the web server that ships with ruby, is known to cause issues with HTTP headers/cookies and is ***not*** recommended. + +2. [Redis](http://redis.io/) - RhoConnect includes a simple [rhoconnect task](command-line#rhoconnect-cli-rhoconnect-v32) `rhoconnect redis-install` to install redis, covered in the [Rhoconnect CLI section](command-line#rhoconnect-cli-rhoconnect-v32). Alternatively, you can [install redis directly](http://redis.io/download). + +3. Install the RhoConnect Gem. + +Run this command to install the RhoConnect Gem. + + :::term + $ gem install rhoconnect + +**NOTE: Do not install Ruby as a standalone if you also use Ruby Version Manager (rvm) to install Ruby. If you need only one version of Ruby, you can install Ruby as a standalone. If you need more than one version of Ruby, you should uninstall standalone Ruby and then install Ruby with Ruby Version Manager. Mixed standalone Ruby and rvm-controlled Ruby installations can conflict and cause runtime issues in RhoConnect applications.** + +## Setting the HTTP_PROXY Environment Variable + +If you are using RestClient, you should set the HTTP_PROXY environment variable to your proxy server URL. This allows the bundler to work from behind a proxy. + +From Linux or OSX, you can use the following command. + + $ export http_proxy=http://{username}:{password}@{proxy-server-name} + +From Windows: + + $ SET HTTP_PROXY=http://{username}:{password}@{proxy-server-name} + +This allows you to set the RestClient proxy using the HTTP_PROXY environment variable in your RhoConnect code. + + :::ruby + RestClient.proxy = ENV['http_proxy'] + +## Installing Redis +### Install and Setup Redis + +Next, you will need to setup your [redis](http://redis.io/) server: + + :::term + $ rhoconnect redis-install + +#### Redis Horizontal Scaling + +Starting from v4.0, RhoConnect supports multiple Redis instances per app. +To enable this feature, edit your app `settings/settings.yml` file and replace the `:redis:` configuration +with an array of redis servers you are going to use: + + :::yaml + # ... + :production: + :licensefile: settings/license.key + :syncserver: http://localhost:9292/api/application/ + :push_server: http://appname:secret@localhost:8675/ + # One or more redis servers + :redis: + - localhost:6379 + - localhost:6380 + - localhost:6381 + - localhost:6382 + # ... + +### Installing DTach (Mac OS / Linux only) + +If you're using MacOS / Linux, install [dtach](http://dtach.sourceforge.net/) on your path before running any of the rhoconnect tasks. [DTach](http://dtach.sourceforge.net/) is a simple utility which runs processes in a detached state so you can re-attach your console later. + + :::term + $ cd storeserver + $ rhoconnect dtach-install + +Now you're ready to create a rhoconnect and start app from the command line. See [App Generator and Command Line](command-line) for instructions on this.# Installing RhoConnect. + +## Upgrading From RhoConnect v.4.x to RhoConnect v.5.x +Upgrading from RhoConnect version 4.x is quite simple. All that is needed is to update the version of RhoConnect in your RC app's gemfile. + +For Example: + + :::txt + source 'http://rubygems.org' + + gem 'rhoconnect', '5.0.25' + + gemfile_path = File.join(File.dirname(__FILE__), ".rcgemfile") + begin + eval(IO.read(gemfile_path)) + rescue Exception => e + puts "ERROR: Couldn't read RhoConnect .rcgemfile" + exit 1 + end + + # Add your application specific gems after this line ... + +Note that the RhoConnect gem version is '5.0.25'. Change your RhoConnect gem version to 5.0.25 here and then run bundle install in your app's directory to install the newly specified RhoConnect gem. \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/introduction.md b/docs/en/5.5/rhoconnect/introduction.md new file mode 100644 index 00000000..d47887fb --- /dev/null +++ b/docs/en/5.5/rhoconnect/introduction.md @@ -0,0 +1,20 @@ +RhoConnect Introduction +=== + +RhoConnect is the first of a new category of “mobile app integration” servers. Using RhoConnect drastically simplifies the development of connectivity to an enterprise backend app. The RhoConnect server and built-in RhoConnect client in the smartphone app perform all the work to get data down to the device. This eliminates 50 to 80 percent of the development effort in enterprise smartphone apps: performing the backend application integration. + +RhoConnect also does the ongoing synchronization work: keeping all of the data from backend applications current on the local device. As information is changed in backend applications it is immediately synchronized down to all devices, and available on devices even when they are offline. Data changed on the devices is also synchronized by RhoConnect to the backend system. + +RhoConnect does not require use of Rhodes for the client app. It can also be used from apps written in Objective C or even from other frameworks using JavaScript. + +RhoConnect consists of the following components: + +* Synchronization Framework - The core of RhoConnect, this facilitates data synchronization between the Rhodes / RhoConnect-Client and a 3rd party source (SOAP, REST, etc...). Each source is synchronized by implementing a "source adapter" which consists of model and controller. The client connects with the embedded [sinatra](http://www.sinatrarb.com/) server to interact with the collection of source adapters. RhoConnect uses [redis](http://redis.io/) to efficiently cache data to be synchronized. + +* REST API - RhoConnect exposes a simple REST API for interacting with an application. See the [REST API docs](rest-api) for more information. + +* Administration Web Console - The RhoConnect [web console](web-console) is sinatra server used for manipulating and peeking into a running RhoConnect app. The console uses the [RhoConnect REST API](rest-api) for everything it does. + +* Asynchronous Job System - RhoConnect uses the [resque](https://github.com/defunkt/resque) library to provide asynchronous execution of various tasks it needs to perform. These tasks include source adapter execution, sending push messages, preparing bulk data, etc... Resque is dead-simple to use and highly extensible, so it can easily be used for other functionality not described here. + +The bulk of the work involved in making RhoConnect work with your smartphone application is writing source adapters. This process is described in the [source adapter section](source-adapters). A longer [tutorial](tutorial) is also available. \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/java-plugin.md b/docs/en/5.5/rhoconnect/java-plugin.md new file mode 100644 index 00000000..74c25d6c --- /dev/null +++ b/docs/en/5.5/rhoconnect/java-plugin.md @@ -0,0 +1,633 @@ +RhoConnect-Java +=== + +RhoConnect-Java library is designed for the [RhoConnect](http://rhomobile.com/products/rhoconnect/) Application Integration Server. + +Using the RhoConnect-Java plugin, your [Spring 3 MVC](http://www.springsource.org/) application's data will transparently synchronize with a mobile application built on the [Rhodes framework](http://rhomobile.com/products/rhodes), or any of the available [RhoConnect clients](http://rhomobile.com/products/rhoconnect/). + +## Prerequisites + +* Java (1.6) +* Maven +* Git +* [rhoconnect-java](https://s3.amazonaws.com/rhoconnect-java/rhoconnect-java-1.0.2.jar) RhoConnect Java plugin jar +* [rhoconnect-java-api](https://s3.amazonaws.com/rhoconnect-java/rhoconnect-java-api-1.0.0.jar) RhoConnect Java API jar + +## Getting started + +We assume that you have a complete java end-to-end application using Spring 3.0 MVC as the front end technology and Hibernate as backend ORM. For this application we will also use Maven for build and dependency management and some database to persist the data. The database is accessed by a Data Access (DAO) layer. + +Copy [rhoconnect-java](https://s3.amazonaws.com/rhoconnect-java/rhoconnect-java-1.0.2.jar) and [rhoconnect-java-api](https://s3.amazonaws.com/rhoconnect-java/rhoconnect-java-api-1.0.0.jar) jar files to your PC. +You can also create target rhoconnect-java plugin jar from sources by cloning rhoconnect-java repository + + :::term + $ git clone git@github.com:rhomobile/rhoconnect-java.git + +and executing in cloned project directory the following commands: + + :::term + $ mvn package + +The archived rhoconnect-java-x.y.z.jar file will be created in the project java-plugin/target/ directory. The accompanying rhoconnect-java-api-x.y.z.jar file will be created in the project java-api/target/ directory. + +For testing and evaluation purposes you can use [RhoconnectJavaSample](https://github.com/shurab/RhoconnectJavaSample) application as a starting point before continuing with the following steps. + +### Adding Dependencies to Your Maven Project + +Add dependencies to your Apache Maven project object model (POM): log4j, Apache common beanutils, and Jackson JSON mapper. In the RhoconnectJavaSample application, this code is in the pom.xml file. + + :::xml + + + log4j + log4j + 1.2.9 + jar + false + + + + commons-beanutils + commons-beanutils + 1.8.3 + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.0 + jar + false + + +You must also add the rhoconnect-java and rhoconnect-java-api jars to your Maven project. At this moment they are not available in Maven public repositories and you need install the jar manually into your Maven's local repository. + + :::term + $ mvn install:install-file -Dfile=/path-to-jar/rhoconnect-java-api-1.0.0.jar -DgroupId=com.msi.rhoconnect.api \ + -DartifactId=rhoconnect-java-api -Dversion=1.0.0 -Dpackaging=jar + $ mvn install:install-file -Dfile=/path-to-jar/rhoconnect-java-1.0.2.jar \ + -DgroupId=com.rhomobile.rhoconnect -DartifactId=rhoconnect-java -Dversion=1.0.2 -Dpackaging=jar + +Now, the `rhoconnect-java` jar library is included into your Maven local repository. +In the RhoconnectJavaSample application, you would add this code to the pom.xml file. + + :::xml + + + com.rhomobile.rhoconnect + rhoconnect-java + 1.0.1 + jar + + + + com.msi.rhoconnect.api + rhoconnect-java-api + 1.0.0 + jar + + + com.sun.jersey + jersey-bundle + 1.17 + + + com.googlecode.json-simple + json-simple + 1.1.1 + + +### Updating Your Servlet XML Configuration File + +Update your servlet xml configuration file to include rhoconnect-java metadata: the packages, converters, and beans. In the RhoconnectJavaSample, the following code is added to src/main/webapp/WEB-INF/spring-servlet.xml file. + + :::xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +The `setAppEndpoint` method in the `rhoconnectClient` bean in the above code sample is a main point in establishing the communication +link between the `Rhoconnect` server and the Spring 3 MVC application. It has the following properties that you need to configure. + + + + + + + + + + + + + + +
                                                                              endpointUrlrhoconnect server's url, for example http://localhost:9292
                                                                              appEndpointyour Spring 3 MVC app url, for example http://localhost:8080/contacts
                                                                              apiTokenrhoconnect server's api_token, for example my-rhoconnect-token
                                                                              + +The `authenticate` bean will be called by rhoconnect server to authenticate users, and has to implement `Rhoconnect` interface provided by rhoconnect-java plugin: + + :::java + package com.rhomobile.rhoconnect; + import java.util.Map; + + public interface Rhoconnect { + String authenticate(String userName, String password, Map attributes); + } + +For example: + + :::java + package com.rhomobile.contact; + + import java.util.Map; + import org.apache.log4j.Logger; + import com.rhomobile.rhoconnect.Rhoconnect; + + public class ContactAuthenticate implements Rhoconnect { + private static final Logger logger = Logger.getLogger(ContactAuthenticate.class); + + @Override + public String authenticate(String login, String password, Map attributes) { + logger.debug("ContactAuthenticate#authenticate: implement your authentication code!"); + // TODO: your authentication code goes here ... + // Return null value if authentication fails. + + // Otherwise, returned value is data partitioning: i.e. user name for filtering data on per user basis + //return login; + + // But if you want your data to be partitioned by ‘app’ (i.e. the data will be shared among all users), + // you should return string "app": it will instruct Rhoconnect to partition the data accordingly. + return "app"; + } + } + +### Establishing communication from the RhoConnect server to java back-end application + +You need to establish communication from the RhoConnect instance to your java back-end application by mixing RhoconnectResource interface in your data access (DAO) service class: + + :::java + package com.rhomobile.rhoconnect; + + import java.util.Map; + + public interface RhoconnectResource { + Map rhoconnectQuery(String partition); + Integer rhoconnectCreate(String partition, Map attributes); + Integer rhoconnectUpdate(String partition, Map attributes); + Integer rhoconnetDelete(String partition, Map attributes); + } + +To help rhoconnect-java plugin correctly do mapping of model name to service bean you should take into account the following conventions: + +* Name of the DAO service bean (class) should be model name followed by `ServiceImpl` suffix (i. e. `ContactServiceImpl` for model `Contact`) +* Service bean should be auto-wired into corresponding controller via @Autowired annotation + +Data partitioning in your code should be based on filtering data for unique user (i.e. your user name) or per application (shared dataset for all users). +For more information about RhoConnect partitions, please refer to the [RhoConnect docs](http://docs.rhomobile.com/rhosync/source-adapters#data-partitioning). + +### Establishing communication from java back-end application to the RhoConnect server + +You also must to establish the communication from your java back-end application to the RhoConnect instance by auto-wiring `RhoconnectClient` bean into your DAO service class and inserting notifications hooks into data access (create/update/delete) methods. +`RhoconnectClient` bean is provided by rhoconnect-java plugin and responds to the following methods you have to call: + +* boolean notifyOnCreate(String sourceName, Object objId, Object object) +* boolean notifyOnUpdate(String sourceName, Object objId, Object object) +* boolean notifyOnDelete(String sourceName, Object objId) + +Example for `RhoconnectJavaSample` application: + + :::java + package com.rhomobile.contact.service; + + import java.util.HashMap; + import java.util.Iterator; + import java.util.List; + import java.util.Map; + + import org.apache.commons.beanutils.BeanUtils; + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.stereotype.Service; + import org.springframework.transaction.annotation.Transactional; + + import com.rhomobile.contact.dao.ContactDAO; + import com.rhomobile.contact.form.Contact; + + import com.rhomobile.rhoconnect.RhoconnectClient; + import com.rhomobile.rhoconnect.RhoconnectResource; + + @Service + public class ContactServiceImpl implements ContactService, RhoconnectResource { + //private static final Logger logger = Logger.getLogger(ContactServiceImpl.class); + + @Autowired + private ContactDAO contactDAO; + @Autowired + private RhoconnectClient client; + private static final String sourceName = "Contact"; // name of DAO model + + @Transactional + public int addContact(Contact contact) { + int id = contactDAO.addContact(contact); + client.notifyOnCreate(sourceName, Integer.toString(id), contact); + return id; + } + + @Transactional + public void updateContact(Contact contact) { + contactDAO.updateContact(contact); + client.notifyOnUpdate(sourceName, Integer.toString(contact.getId()), contact); + } + + @Transactional + public void removeContact(Integer id) { + contactDAO.removeContact(id); + client.notifyOnDelete(sourceName, Integer.toString(id)); + } + + @Transactional + public List listContact() { + return contactDAO.listContact(); + } + + @Transactional + public Contact getContact(Integer id) { + return contactDAO.getContact(id); + } + + @Override + @Transactional + public Map rhoconnectQuery(String partition) { + Map h = new HashMap(); + List contacts = listContact(); + + Iterator it = contacts.iterator( ); + while(it.hasNext()) { + Contact c =(Contact)it.next(); + h.put(c.getId().toString(), c); + } + return h; + } + + @Override + @Transactional + public Integer rhoconnectCreate(String partition, Map attributes) { + Contact contact = new Contact(); + try { + BeanUtils.populate(contact, attributes); + int id = addContact(contact); + return id; + } catch(Exception e) { + e.printStackTrace(); + } + return null; + } + + @Override + @Transactional + public Integer rhoconnectUpdate(String partition, Map attributes) { + Integer id = Integer.parseInt((String)attributes.get("id")); + Contact contact = getContact(id); + try { + BeanUtils.populate(contact, attributes); + updateContact(contact); + return id; + } catch(Exception e) { + e.printStackTrace(); + } + return null; + } + + @Override + @Transactional + public Integer rhoconnetDelete(String partition, Map attributes) { + String objId = (String)attributes.get("id"); + Integer id = Integer.parseInt(objId); + removeContact(id); + return id; + } + } + +Click [here](https://github.com/shurab/RhoconnectJavaPluginDemo) to download full source code of Contact manager application with rhoconnect-java plugin. + +## RhoConnect-Java-API + +The rhoconnect-java project contains `java-api` module that provides Java API to all resources available in
                                                                              Rhoconnect. +The `rhoconnect-java-api`is a generic Java library for communicating with RhoConnect RESTful API and it might be used to implement java client apps or components of back-end servers. +This library also is used by RhoConnect-Java plugin to directly access RhoConnect resources. + +The library has the following dependencies: + +* [jersey java](http://jersey.java.net/) +* [json-simple](http://code.google.com/p/json-simple) + +Every usage of API call follows this pattern: + + :::java + ClientResponse response = NameOfResource.method(serverUrl, params); + // Every call returns as a response Jersey object + // To get status code call `response.getStatus()` + // To get body as a jason string call `response.getEntity(String.class)` + +### SystemResource + +#### `POST /rc/v1/system/login` +Login to the RhoConnect server and get API token. + + :::java + public static ClientResponse login(String url, String password); + +#### `POST /rc/v1/system/reset` +Reset the server: flush db and re-bootstrap server. + + :::java + public static ClientResponse reset(String url, String token); + +#### `GET /rc/v1/system/license` +Returns license information of the currently used license. + + :::java + public static ClientResponse license(String url, String token); + +#### `GET /rc/v1/system/appserver` +Returns the url of the plugin’s backend from the RhoConnect server. + + :::java + public static ClientResponse getAppserver(String url, String token); + +#### `POST /rc/v1/system/appserver` +Saves the url of the plugin’s backend to the RhoConnect server. + + :::java + public static ClientResponse setAppserver(String url, String token, String adapterUrl) + +#### `GET /rc/v1/system/stats` +Retrieves stats for a given metric key. + + :::java + public static ClientResponse statsMetricKey(String url, String token, String metricKey, int start, int finish) + +Retrieves a list of metric keys matching a given pattern. This supports ‘glob’ or ‘*’ style pattern matching. + + :::java + public static ClientResponse statsMetricPattern(String url, String token, String pattern); + + +### StoreResource + +#### `GET /rc/v1/store/:doc` +Return content of a given document stored in Redis. + + :::java + public static ClientResponse get(String url, String token, String docname); + + +#### `POST /rc/v1/store/:doc` +Sets the content of the specified server document. Data should be a string. +If append flag is set to true , the data is appended to the current doc (if it exists) +instead of replacing it. + + :::java + public static ClientResponse set(String url, String token, String docname, String data, boolean append); + +### UserResource + +#### `GET /rc/v1/users` +List users registered with this RhoConnect application. + + :::java + public static ClientResponse list(String url, String token); + +#### `POST /rc/v1/users` +Create a user in this RhoConnect application. + + :::java + public static ClientResponse create(String url, String token, String login, String password); + +#### `DELETE /rc/v1/users/:user_id` +Delete User and all associated devices from the RhoConnect application. + + :::java + public static ClientResponse delete(String url, String token, String userId); + +#### `PUT /rc/v1/users/:user_id` +Update attributes for a user on this RhoConnect application. +userAttributes is a hash of attribute/value pairs: +{:a_user_specific_attribute => a_user_specific_attribute_value}. + + :::java + public static ClientResponse update(String url, String token, String userId, JSONObject userAttributes); + +#### `GET /rc/v1/users/:user_id` +Returns the information for the specified user. + + :::java + public static ClientResponse show(String url, String token, String userId); + +#### `GET /rc/v1/users/:user_id/clients` +List clients (devices) associated with given user. + + :::java + public static ClientResponse listClients(String url, String token, String userId); + +#### `DELETE /rc/v1/users/:user_id/clients/:client_id` +Deletes the specified client (device) for the given user. + + :::java + public static ClientResponse deleteClient(String url, String token, String userId, String clientId); + +#### `GET /rc/v1/users/:user_id/sources/:source_id/docnames` +Return list of document keys associated with given source and user. +If userId set to '*', this call will return list of keys for 'shared' documents. + + :::java + public static ClientResponse sourcesDocnames(String url, String token, String userId, String sources); + +#### `POST /rc/v1/users/ping` +Sends PUSH message to all devices of the specified user(s). +pingParams is a hash of the following attribute/pairs: +{ "user_id":[array_of_users], "sources":"source_name", +"message": "hello world", "vibrate": 2000, "sound": "hello.mp3" } + + :::java + public static ClientResponse ping(String url, String token, JSONObject pingParams); + +#### `GET /rc/v1/users/:user_id/sources/:source_id/docs/:doc` +Return content of a given source document for the specified user. + + :::java + public static ClientResponse getSourcesDocs(String url, String token, String userId, String sourceId, String docname); + +#### `POST /rc/v1/users/:user_id/sources/:source_id/docs/:doc` +Sets the content of the specified source document for the given user. +Data should be either a string or hash of hashes. +If append flag is set to true , the data is appended to the current doc (if it exists) +instead of replacing it. + + :::java + public static ClientResponse setSourcesDocs(String url, String token, String userId, String sourceId, + String docname, String data, boolean append); + public static ClientResponse setSourcesDocs(String url, String token, String userId, String sourceId, + String docname, JSONObject data, boolean append); + +### SourceResource + +#### `GET /rc/v1/sources/type/:partition_type` +Return list of source adapters for this RhoConnect application for the given partition type. +Partition type is one of PartitionType.App, PartitionType.User, PartitionType.All. + + :::java + public static ClientResponse getSources(String url, String token, PartitionType partitionType); + +#### `GET /rc/v1/sources/:source_id` +Return attributes associated with a given source. + + :::java + public static ClientResponse getAttributes(String url, String token, String sourceId); + +#### `PUT /rc/v1/sources/:source_id` +Updates attributes associated with a given source. Attributes defined as a hash of attribute/value pair(s). + + :::java + public static ClientResponse setAttributes(String url, String token, String sourceId, JSONObject sourceParams); + +### ClientResource + +#### `GET /rc/v1/clients/:client_id` +Returns client (device) attributes, such as device_type, device_pin, device_port. + + :::java + public static ClientResponse getAttributes(String url, String token, String clientId); + +#### `GET /rc/v1/clients/:client_id/sources/:source_id/docnames` +Returns list of document keys associated with particular client for a given source. + + :::java + public static ClientResponse getSourcesDocnames(String url, String token, String clientId, String sourceId); + +#### `GET /rc/v1/clients/:client_id/sources/:source_id/docs/:doc` +Return content of a given source document for the specified client. + + :::java + public static ClientResponse getSourceDocument(String url, String token, String clientId, String sourceId, String docname); + +#### `POST /rc/v1/clients/:client_id/sources/:source_id/docnames` +Sets the content of the specified source document for the given client. +Data should be either a string or hash of hashes. If append flag is set to true, +the data is appended to the current doc (if it exists) instead of replacing it. + + :::java + public static ClientResponse setSourcesDocnames(String url, String token, String clientId, String sourceId, + String data, boolean append); + public static ClientResponse setSourcesDocnames(String url, String token, String clientId, String sourceId, + JSONObject data, boolean append); + +### PluginResource + +#### `POST /app/v1/:source_name/push_objects` +Push new objects or object updates to RhoConnect. + + :::java + public static ClientResponse pushObjects(String url, String token, String userId, String sourceName, JSONObject data); + +#### `POST /app/v1/:source_name/push_deletes` +Delete objects from RhoConnect. + + :::java + public static ClientResponse deleteObjects(String url, String token, String userId, String sourceName, JSONArray objectIds); + +### ReadStateResource + +#### `PUT /rc/v1/readstate/users/:user_id/sources/:source_id` +Sets source poll interval to “current time plus x seconds”. +Calling method with refreshTime = null will trigger a refresh on the sync request for the source. + + :::java + public static ClientResponse setPollInterval(String url, String token, String userId, String sourceName, Integer refreshTime); + + +### Sample of Java RhoConnect client app + + :::java + import com.msi.rhoconnect.api.SystemResource; + import com.msi.rhoconnect.api.UserResource; + import com.sun.jersey.api.client.ClientResponse; + import org.json.simple.JSONArray; + import org.json.simple.JSONValue; + + public class JavaClient { + static String URL = "http://localhost:9292"; + + public static void main(String[] args) { + try { + ClientResponse response = SystemResource.login(URL, ""); + if(response.getStatus() == 200) { + String token = response.getEntity(String.class); + System.out.println("Login to server. Got API token: " + token); + + // List users registered with this RhoConnect application + response = UserResource.list(URL, token); + JSONArray users = (JSONArray)JSONValue.parse(response.getEntity(String.class)); + System.out.println(users); + + // Create "testuser" in this RhoConnect application + response = UserResource.create(URL, token, "testuser", "password"); + + // Make sure that 'testuser' is registered + response = UserResource.list(URL, token); + users = (JSONArray)JSONValue.parse(response.getEntity(String.class)); + if(users.contains("testuser")) + System.out.println("User 'testuser' created"); + System.out.println(users); + + // .... + + // Delete "testuser" from this rhoconnect app + response = UserResource.delete(URL, token, "testuser"); + if (response.getStatus() == 200) + System.out.println("User 'testuser' deleted"); + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + +## Meta +Created and maintained by Alexander Babichev. + +Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). diff --git a/docs/en/5.5/rhoconnect/metadata.md b/docs/en/5.5/rhoconnect/metadata.md new file mode 100644 index 00000000..cdf11ff8 --- /dev/null +++ b/docs/en/5.5/rhoconnect/metadata.md @@ -0,0 +1,458 @@ +Building Dynamic Views with Metadata +=== + +The metadata framework is a RhoConnect & Rhodes tool which provides synchronized application layouts. For example, if your application had an "account" model with the fields "name" and "address", metadata would allow you to add an additional field "phone" in the source adapter and this new field would automatically display in the Rhodes application. + +In addition to adding/removing/updating fields, metadata also provides powerful features like handling field validations, data-binding, collections, repeatable elements, and much more. + +## How Metadata Works +* Metadata is first defined in a [source adapter](source-adapters) by implementing an adapter method `metadata` that returns a JSON structure. The JSON structure may contain a hash of hashes, as well as having child elements defined as arrays of hashes. The keys in each object can be any string, however there are some reserved labels and labels used by certain elements. + +* The metadata for an adapter is synchronized to Rhodes along with the rest of the adapter dataset. Metadata is called before the query method in the [`SyncEngine` workflow](../guide/using_rhoconnect#syncengine-workflow), so you can tailor your query method based on metadata. + +* Rhodes uses the synchronized [metadata definition](#metadata-definition) to render views at runtime. These views are driven by the metadata definition, so when a new definition is synchronized, the views will automatically reflect the changes. + +## Getting Started with Metadata +The first step is to install the rhodes-translator gem: + + :::term + $ gem install rhodes-translator + +Then add `rhodes_translator` to your extensions in your Rhodes application's `build.yml`: + + :::yaml + extensions: ["rhodes_translator"] + +Now define some metadata and add this to a `metadata` method your [source adapter model](source-adapters). For example: + + :::ruby + def metadata + # define the metadata + row1 = { + :label => 'Address 1', + :value => '123 fake street', + :name => 'address1', + :type => 'labeledrow' + } + table = { + :label => 'Table', + :type => 'table', + :children => [ row1, row1, row1 ] + } + view = { + :title => 'UI meta panel', + :type => 'iuipanel', + :children => [table] + } + + # return the definition as JSON + {'index' => view}.to_json + end + + +## Metadata Definition +The following elements are available for building metadata definitions. + +### Reserved Labels + +The following labels are reserved, used by the metadata framework. + +* `:type` +* `:children` +* `:repeatable` +* `:validation` + +### Children + +Children of an element are defined by an array of hashes. To specify the children of an element you add the ":children" key and specify the children of that element. + +The following example shows a table element that has three `row1` elements as `:children`: + + :::ruby + row1 = { + :label => 'Address 1', + :value => '123 fake street', + :name => 'address1', + :type => 'labeledrow' + } + + table = { + :label => 'Table', + :type => 'table', + :children => [ row1, row1, row1 ] + } + +### Repeatable + +Repeatable elements use [data binding](#data-binding) to specify an array of objects to iterate over. The children of the repeatable element are duplicated for each element in the object referred to by the repeatable hash key. For more information on data-binding see the data binding section on this page. + +The following example will result in a table with 2 child rows, one row with the value set to '123 fake street' and the second row value set to '321 fake street' + + :::ruby + @addresses = [ + { :name => "123 fake street" }, + { :name => "321 fake street" } + ] + + row1 = { + :label => 'Address 1', + :value => '{{name}}', + :name => 'address1', + :type => 'labeledrow' + } + + table = { + :label => 'Table', + :type => 'table', + :children => [ row1 ], + :repeatable => '{{@addresses}}' + } + + +## Controlling How Metadata is Rendered + +By default, any controller actions that have metadata for a given model with the key corresponding to the action will be rendered with metadata instead of the view. + +However, you can render arbitrary metadata in the view with the `render_metadata` method. You must specify the action to the metadata. By default, the metadata provided is pulled from the model, however this can be overridden as well. + +Example: + + :::ruby + <%= render_metadata('indexdata') %> + + +Or, using explicit metadata resource: + + :::ruby + <%= render_metadata('index', Account.metadata) %> + +## Data Binding + +Data binding happens before the elements get translated to html. All of the instance variables in your method are able to be referenced by the data binding keys. + +A data binding key is always contained within a string. It is indicated by using double bracket enclosure: `{{databinding path here}}` + +To reference hash keys, or index arrays, the `/` operator is used. You must specify the whole path to the object, the only exception being within [repeatable](#metadata-definition) elements. + +We will use the following dataset for example: + + :::ruby + @data = { + :key1 => [ 'array', 'with', 'elements'], + :key2 => { :this => "is", :a => "hash" } + } + + +Example data binding keys using this data: + +`{{@data/key1/0}}` will be replaced with 'array' + +`{{@data/key1/2}}` will be replaced with 'elements' + +`{{@data/key1/5}}` will be replaced with an error message + +`{{@data/key2/this}}` will be replaced with 'is' + +`{{@data/key2/this}}` will be replaced with 'hash' + + +Within a repeatable element, the root node is replaced with the element that is being repeated. See the example in the repeatable section above. To reference the root element while inside a repeatable a `/` should be prepended to your data binding expression: `{{/@data/key1/0}}` + +## Validation + +Validation is expressed as a key added to an existing metadata definition. Below is a sample showing all of the validations that can be used. + + :::ruby + :validation => { + :regexp = "^.+$", + :validators = [:required, :number, :currency, :email, :phone], + :min_len = 0, + :max_len = 100, + :min_value = 10, + :max_value = 1000 + } + +## Templates +### Form +An HTML form that is used for submitting data: + + :::html +
                                                                              + + +* **Type** + * `form` +* **Keys** + * `name` - used as name attribute in <form> tag + * `action` - used as action attribute in <form> tag + * `method` - used as method attribute in <form> tag +* **Children** + * Children are rendered between the <form> and </form> tags + +### Panel +Contains children with a <div> tag with the div class set to 'panel': + + :::html +
                                                                              + +* **Type** + * `panel` +* **Keys** + * `unused` +* **Children** + * Children are rendered between the <div> and </div> tags + +### View +Contains children with no extra html. + +* **Type** + * `view` +* **Keys** + * `unused` +* **Children** + * Children rendered directly + +### Table +HTML Table. + + :::html +
                                                                              + +* **Type** + * `table` +* **Keys** + * `class` - class attribute on <table> element +* **Children** + * Children are rendered between the <table> and </table> tags + +### Text +A labeled text display. + + :::html +
                                                                              + + +
                                                                              + +* **Type** + * `text` +* **Keys** + * `div_class` - class attribute for div + * `label_class` - class attribute for label + * `value_class` - class attribute for span + * `label` - value for label element + * `value` - value for inner div element +* **Children** + * Does not render children + +### Text Input, Password +A labeled text input. + + :::html +
                                                                              + + +
                                                                              + +* **Type** + * `textinput|password` +* **Keys** + * `div_class` - class attribute for outer div + * `label_class` - class attribute for label + * `value_class` - class attribute for input + * `label` - value for label element + * `value` - value attribute for input + * `name` - name attribute for input + * `editable` - boolean value, enable/disable changing of selection. Default `true`. +* **Children** + * Does not render children. + +### Text Area +Text area input field. + + :::html + + +* **Type** + * `textarea` +* **Keys** + * `class` - class attribute for textarea + * `value` - value attribute for textarea + * `name` - name attribute for textarea + * `rows` - rows attribute for textarea + * `cols` - cols attribute for textarea + * `editable` - boolean value, enable/disable changing of selection. Default `true`. +* **Children** + * Does not render children. + +### Select +HTML Select. + + :::html +
                                                                              + + +
                                                                              + +* **Type** + * `select` +* **Keys** + * `size` - size attribute for select + * `class` - class attribute for select + * `allow_multi` - boolean value, allow multiple selection on dropdown. Default `false`. + * `editable` - boolean value, enable/disable changing of selection. Default `true`. + * `div_class` - class attribute for outer div + * `label_class` - class attribute for label + * `label` - value for label element + * `value` - default value displayed + * `values` - array of strings to provide as options +* **Children** + * Does not render children. + +### Checkbox +A checkbox field + + :::html +
                                                                              + + +
                                                                              + +* **Type** + * `checkbox` +* **Keys** + * `div_class` - class attribute for outer div + * `label_class` - class attribute for label + * `label` - value for label element + * `name` - name attribute for input + * `default_value` - boolean value, true = checked, false = unchecked. Default `false`. + * `value` - string value, 'true' = checked, anything else = unchecked +* **Children** + Does not render children. + +### link +An anchor tag. + + :::html + + +* **Type** + * `link` +* **Keys** + * `url` - the url inside the href attribute + * `text` - the text that the link displays +* **Children** + * Does not render children. + +### telephone +Anchor tag, with click to call information. + + :::html + + +* **Type** + * `telephone` +* **Keys** + * `number` - the phone number to call + * `text` - The text that the link displays +* **Children** + * Does not render children. + +## Advanced Adapter Example +Here is a more advanced source adapter `metadata` example which demonstrates the concepts we described here: + + :::ruby + def metadata + @contact = { + :label => '{{name}}', + :name => 'contact', + :type => 'labeledrow', # a row which links to another + # object in a different model + :value => '{{age}}, {{year}}' + } # name and phone of the contact object not the account! + + @rows = { + :type => 'view', + :children => [@contact], + :repeatable => '{{@forms}}' + } + + @link = { + :label => 'New', + :value => '{{@link1}}', + :type => 'labeledrow' + } + + @table = { + :label => 'table', + :name => 'table', + :type => 'table', + :class => 'grid', + :children => [@link, @rows] + } + + @index = { + :title => 'PEOPLE', + :type => 'iuipanel', + :children => [@table] + } + + @error = { + :label => '{{@errorlabel}}', + :type => 'text', + :name => 'name', + :value => '{{@errors}}' + } + + @name = { + :label => 'name', + :type => 'textinput', + :name => 'name', + :value => '{{@form/name}}', + :validation => { :validators => [:required] } + } + + @age = { + :label => 'age', + :type => 'textinput', + :name => 'age', + :value => '{{@form/age}}', + :validation => { + :validators => [:required], + :min_value => 13 + } + } + + @year = { + :label => 'year', + :type => 'textinput', + :name => 'year', + :value => '{{@form/year}}', + :validation => { + :validators => [:required], + :max_value => 2010 + } + } + + @submit = { + :name => 'submit', + :value => 'submit', + :type => 'submit' + } + + @form = { + :name => 'inputform', + :action => '{{@submiturl}}', + :type => 'form', + :children => [@error, @name, @age, @year, @submit] + } + + { 'indexdata' => @index, 'new' => @form }.to_json + end + +## Custom Templates + +Templates can be overridden by placing the ERB files in the `app/templates` folder in your Rhodes application. They will be used before using any of the built-in templates. diff --git a/docs/en/5.5/rhoconnect/migration.md b/docs/en/5.5/rhoconnect/migration.md new file mode 100644 index 00000000..76a5debf --- /dev/null +++ b/docs/en/5.5/rhoconnect/migration.md @@ -0,0 +1,167 @@ +# Migrating your application to RhoConnect 5.0 +The best way of migrating your old RhoConnect app to Rhoconnect 5.0+ is to re-generate the application skeleton +using Rhoconnect, then integrate all of your implementation specifics into it. +However, if you prefer to migrate your RhoConnect app manually, perform the steps in this document. + +## Upgrading dependency manifest + +Open the `Gemfile` of your application and find the `rhoconnect` line, it should look something like: + + :::ruby + gem 'rhoconnect', '3.4.4' + +Change this to the latest release version, which you can find on [rubygems.org](http://rubygems.org/gems/rhoconnect), for example if it is 5.0.1: + + :::ruby + gem 'rhoconnect', '4.0.1' + +Run the following command from the root application directory: + + :::term + $ bundle install + +Now update your application's RhoConnect dependency manifest: + + :::term + $ rhoconnect update + +## Migrating application files + +If you have an existing RhoConnect application using version < 5.0 and want to upgrade it to RhoConnect 5.0+, then +you need to update the `Gemfile` file to properly use the latest RhoConnect runtime dependencies. + +First, follow the instructions described in the [previous section](migration#upgrading-dependency-manifest). + +Next, make sure your `Gemfile` looks like the following example, replacing the version as necessary. +The `rhoconnect update` command will generate a reference `Gemfile.new` which you can use to replace your `Gemfile`: + + :::ruby + source 'http://rubygems.org' + + gem 'rhoconnect', '' + gemfile_path = File.join(File.dirname(__FILE__), ".rcgemfile") + + begin + eval(IO.read(gemfile_path)) + rescue Exception => e + puts "ERROR: Couldn't read RhoConnect .rcgemfile" + puts e.message + exit 1 + end + + # DON'T FORGET to add your application specific gems after this line ... + # ... + +You must update `config.ru`, `Rakefile`, 'application.rb' and your source adapter files to match RhoConnect 5.0+ gem requirements. + +Replace your existing `config.ru` with the listing below. Save your old `config.ru` since you will use values within it in the new `config.ru`. + + :::ruby + # config.ru file + + #!/usr/bin/env ruby + require 'rhoconnect/application/init' + + # secret is generated along with the app + # NOTE: + # Substitute 'REPLACE_ME' string by the Rhoconnect::Server.set :secret value from your old config.ru + Rhoconnect::Server.set :secret, 'REPLACE_ME' + + # !!! Add your custom initializers and overrides here !!! + # For example, uncomment the following line to enable Stats + #Rhoconnect::Server.enable :stats + # uncomment the following line to disable Resque Front-end console + #Rhoconnect.disable_resque_console = true + # uncomment the following line to disable Rhoconnect Front-end console + #Rhoconnect.disable_rc_console = true + + # run RhoConnect Application + run Rhoconnect.app + +And replace your existing `Rakefile` with the following: + + :::ruby + require 'rubygems' + require 'bundler/setup' + require 'rhoconnect' + require 'resque/tasks' + + ROOT_PATH = File.expand_path(File.dirname(__FILE__)) + + task 'resque:setup' do + # The number of redis connections you want a job to have + Rhoconnect.connection_pool_size = 1 + require 'rhoconnect/application/init' + + Resque.after_fork do + Store.reconnect + end + end + +Move your existing `application.rb` file into `controllers/ruby/application_controller.rb` and update it with the following: + + :::ruby + class ApplicationController < Rhoconnect::Controller::AppBase + register Rhoconnect::EndPoint + + post "/login", :rc_handler => :authenticate, + :deprecated_route => {:verb => :post, :url => ['/application/clientlogin', '/api/application/clientlogin']} do + login = params[:login] + password = params[:password] + + end + + get "/rps_login", :rc_handler => :rps_authenticate, + :login_required => true do + login = params[:login] + password = params[:password] + + end + + # <.... PLACE HERE ALL OF YOUR EXISTING APPLICATION CODE ...> + end + +NOTE: You must remove `initializer` method from the ApplicationController class. It is no longer supported. + +NOTE: If you had `store_blob` method overridden in the `application.rb` file - you will need to move it into the corresponding model class. Global `store_blob` method is no longer supported. +See below for details. + +Re-generate your sources by running 'rhoconnect source YOUR_SOURCE' command for all of your application sources. This will create source's controller files in the `controllers/ruby` directory +and source's model files in the `models/ruby` directory. After that, move your existing files from the `sources` directory into the `models/ruby` directory, replacing the generated model files. +Then, modify every file to make sure that your SourceAdapter classes now derive from the `Rhoconnect::Model::Base` class - SourceAdapters now became Models: + + :::ruby + class Product < Rhoconnect::Model::Base + # .... rest of your code + end + +If you had global `store_blob` method in the `application.rb` file - you need to move it into every model's class that supports blobs: + + :::ruby + class Product < Rhoconnect::Model::Base + # ... your code here .... + def store_blob(object, field, blob) + + end + end + +If you had source spec files in the `spec/sources` directory - you will need to move them into `spec/models/ruby` directory and adjust the top line of each spec file: + + :::ruby + require File.join(File.dirname(__FILE__),'..','..','spec_helper') + + +Finally, run `bundle install` to install any missing dependencies in your RhoConnect directory: + + :::term + $ bundle install + +### Updating client application +RhoConnect's HTTP routes have changed starting with 5.0, so you'll want to update your client application's `rhoconfig.txt` to drop the trailing `/application`, for example: + + + # sync server url, typically this will look like 'http://:' + # for example: 'http://localhost:9292' + syncserver = 'http://192.168.1.108:9292' + +Next, modify your client application according to the new [client API docs](../api/RhoConnectClient). Be sure to check out the [guides](../guide/using_rhoconnect) periodically as new content is added all the time. diff --git a/docs/en/5.5/rhoconnect/net-plugin.md b/docs/en/5.5/rhoconnect/net-plugin.md new file mode 100644 index 00000000..6362172e --- /dev/null +++ b/docs/en/5.5/rhoconnect/net-plugin.md @@ -0,0 +1,400 @@ +rhoconnect.NET +=== + +The RhoConnect-Java library is designed for the [RhoConnect](http://rhomobile.com/products/rhoconnect/) Application Integration Server. + +The .NET 4 framework library is designed for the [Rhoconnect](http://rhomobile.com/products/rhoconnect) Application Integration Server. + +Using the rhoconnect.NET plugin, your [ASP.NET MVC](http://www.asp.net/mvc/mvc4) application's data will transparently synchronize with a mobile application built on the [Rhodes framework](http://rhomobile.com/products/rhodes), or any of the available [Rhoconnect clients](http://rhomobile.com/products/rhoconnect/). + +image + +## Prerequisites + +* Windows OS +* .NET 4 framework +* Git +* [ASP.NET MVC4](http://www.asp.net/mvc/mvc4) framework +* Visual Studio 2010 +* [`rhoconnect.NET`](https://github.com/rhomobile/rhoconnect.NET) github repository + +## Getting Started + +Copy the [`rhoconnect.NET`](https://github.com/rhomobile/rhoconnect.NET) github repository to your PC: + + $ git clone https://github.com/rhomobile/rhoconnect.NET.git + +By default, the `rhoconnect.NET` repository contains the pre-built `RhoconnectNET.dll` library in the `bin/Release` subdirectory. +However, you can build your own library using the provided Microsoft Visual Studio .NET solution file and the source code files. + +## A Sample ASP.NET MVC4 Backend Application + +You can download and use the sample [`ASP.NET MVC4`](https://github.com/rhomobile/RhoconnectNET_MVC4_App) application to repeat the steps described below. + +In addition, the sample application also contains the final code (the .NET plugin is applied to it) in its `ContactsApp_final` subdirectory. You can use this final code, but you will still need to modify the `set_app_point` with your app endpoints and add the RhoconnectNET library reference to your project. + +To run this application, build it in Visual Studio, create a deployment package (using Project --> Build Deployment Package), then deploy it on Microsoft's IIS server to run. + + + +This sample ASP.NET MVC4 application was created using similar steps to [this tutorial to create a C# application and add support for basic database operations](http://www.asp.net/mvc/tutorials/contact-manager/iteration-1-create-the-application-cs). + +## Settings for the Client App + +Your client application needs to have its model match the model used in your Java Sprint 3.0 MVC backend application. For example, you can generate a Rhodes application for a Contact model to match the sample ASP.NET MVC4 backend application: + + :::term + $ rhodes app contact-app + $ cd contact-app + $ rhodes model contact lastname,firstname,email,phone + +Edit the `rhoconfig.txt` configuration file to point to your RhoConnect server, where is the url for your RhoConnect server. + + :::term + syncserver = 'http:///application' + +And edit the `app/index.erb` view file to say Contacts. + + :::html + ... +
                                                                            • Contacts
                                                                            • + ... + +And edit `app/Contact/contact.rb` file to enable sync. + + :::ruby + ... + enable :sync + ... + +## Settings for the RhoConnect Server App + +You must generate a RhoConnect server application and edit its settings for the RhoConnect .NET plugin. + + :::term + $ rhoconnect app syncserver + $ cd syncserver; bundle install + +Edit the `settings/settings.yml` development section to add an api\_token key/value pair. This value is the same as the api\_token that you will set in the `WEB-INF/spring-servlet.xml` file for your ASP.NET MVC4 backend application. + + :::term + :development: + ... + :api_token: rhoconnect_api_token + +## Including the RhoConnect.NET Library in the Backend Application + +In order to use `Rhoconnect.NET` functionality in your `ASP.NET MVC` application, first you need to include the `Rhoconnect.NET` library +as a dependency to your application. In Visual Studio, click the `Project => Add Reference` menu item and navigate to and select the `RhoconnectNET.dll` library. + +After this step is completed, you can add references to the `Rhoconnect.NET` namespace into the application's and Controller's files: in the case of the ASP.NET MVC4 sample application, the files are ContactsApp/Global.asax.cs and ContactsApp/Controllers/ContactController.cs. + + using RhoconnectNET; + using RhoconnectNET.Controllers; + +## Registering Rhoconnect.NET Routes in the Backend Application + +To establish the communication channel between the ASP.NET MVC application and the Rhoconnect server, you need to implement the following `init_rhoconnect` and `rhoconnect_authenticate` methods in the ASP.NET MVC application's `Global.asax.cs` file and call them from its `Application_Start` method: + + protected void Application_Start() + { + ... ASP.NET initialization routines ... + ... typically, registering routes and filters is done here ... + + // after app is properly initialized + // call RhoconnectNET initialization + init_rhoconnect(); + } + + // implement init_rhoconnect() method to establish + // communication link between `Rhoconnect` server + // and ASP.NET MVC application + private void init_rhoconnect() + { + // this call allows parsing JSON structures into Objects + ValueProviderFactories.Factories.Add(new JsonValueProviderFactory()); + + // this call establishes communication between Rhoconnect and ASP.NET application + // as a last parameter we supply authentication routine that will called + // by rhoconnect server to authenticate users. + // Its parameters are the rhoconnect url, the MVC app url, + // the api_token, and the authenticate method, shown here by + // placeholders. + RhoconnectNET.Client.set_app_endpoint("", + "", + "", + ); + } + + private bool rhoconnect_authenticate(ref String username, String password, Hashtable auth_attrs) + { + // uncomment the following line, if you want to replace the default partitioning to 'app' + // username = "app"; + // perform your authentication here + return true; + } + +The `RhoconnectNET.Client.set_app_endpoint` method is a main point +in establishing the communication link between the `Rhoconnect` server and the ASP.NET MVC application. It has the following parameters that you need to set. + + + + + + + + + + + + + + + + + + + + + + +
                                                                              Stringyour_rhoconnect_server_urlThe RhoConnect server's url, for example http://localhost:9292.
                                                                              Stringapp_endpoint_urlyour MVC app url, for example http://my_pc_host/MyApp.
                                                                              Stringapi_tokenrhoconnect server's api_token, for example rhoconnect_api_token.
                                                                              delegate rhoAuthHandler(ref String, String, Hashtable, bool)Authenticating_Routinehandle to the application's authenticating routine (if null, true is returned by default).
                                                                              + +## Implementing the Backend Application's Authenticate Method + +`Rhoconnect.NET` installs a `/rhoconnect/authenticate` route into your application which will receive credentials from the client. In the ASP.NET MVC application's `Global.asax.cs` file, you can provide the `rhoconnect_authenticate` method and register it with the `Rhoconnect.NET` in the `set_app_endpoint` +method; this maps your application specific authentication to the Rhoconnect `authenticate` requests: + + private bool rhoconnect_authenticate(ref String username, String password, Hashtable auth_attrs) + { + // uncomment the following line, if you want to replace the default partitioning to 'app' + // username = "app"; + // perform your authentication here + return true; + } + +If you want your data to be partitioned by 'app' (i.e. the data will be shared among all users), you can replace +the provided `username` parameter (which is passed by reference) to `app` - which will instruct Rhoconnect to partition the data accordingly. + +## Establishing Communication from the RhoConnect Server to the Backend Application + +The `Rhoconnect.NET` lib installs `/rhoconnect/` routes in your application which the Rhoconnect server instance invokes to perform CRUD operations on the data for the dataset you want to synchronize. +Each of the routes is mapped to a corresponding `rhoconnect_` method in the **IRhoconnectCRUD** interface +which you must implement in the dataset's Controller class. + +In the case of the sample ASP.NET MVC application, you implement these methods in `ContactsApp/Controllers/ContactController.cs`. You could start with code like this: + + public class ContactController : Controller, IRhoconnectCRUD + { + ... implementation of Controller routes + + // You must implement the next four methods + // These methods will be called by the Rhoconnect server + JsonResult rhoconnect_query_objects(String partition); + ActionResult rhoconnect_create(String objJson, String partition); + ActionResult rhoconnect_update(Dictionary changes, String partition); + ActionResult rhoconnect_delete(Object objId, String partition); + } + +And you will implement the rhoconnect_query_objects, rhoconnect_create, rhoconnect_update, and rhoconnect_delete methods. + +### Implement rhoconnect_query_objects to Query the Datasets + +The route `/rhoconnect/query` is mapped to the `rhoconnect_query_objects` method of the **IRhoconnectCRUD** interface. You must implement this method in the corresponding dataset's Controller class. It must return a collection of source objects in the form of a JsonResult. + +In the case of the sample ASP.NET MVC application, you could implement this method in the `ContactsApp/Controllers/ContactController.cs` file as follows: + + public JsonResult rhoconnect_query_objects(String partition) + { + return Json(db.Contacts.ToDictionary(c => c.ID.ToString())); + } + +In the above example, the Contacts Db set is converted to `Dictionary` where the dictionary's key must correspond to an unique object's `ID` field. +After the dictionary is created, it is converted to a JsonResult and sent to the Rhoconnect server. + +### Implement rhoconnect_create to Create New Objects + +The route `/rhoconnect/create` is mapped to the `rhoconnect_create` method of the IRhoconnectCRUD interface that you must implement in the corresponding dataset's Controller class. It should return a newly created object's id in case of success. + +In the case of the sample ASP.NET MVC application, you could implement this method in the `ContactsApp/Controllers/ContactController.cs` file as follows: + + public ActionResult rhoconnect_create(String objJson, String partition) + { + Contact new_contact = (Contact)RhoconnectNET.Helpers.deserialize_json(objJson, typeof(Contact)); + db.Contacts.Add(new_contact); + db.SaveChanges(); + return RhoconnectNET.Helpers.serialize_result(new_contact.ID); + } + +### Implement rhoconnect_update to Update Existing Objects + +In the similar fashion, the route `/rhoconnect/update` is mapped to the `rhoconnect_update` method of the IRhoconnectCRUD +interface that you must implement in the corresponding dataset's Controller class. It should return an updated object's id in case of success. + +In the case of the sample ASP.NET MVC application, you could implement this method in the `ContactsApp/Controllers/ContactController.cs` file as follows: + + public ActionResult rhoconnect_update(Dictionary changes, String partition) + { + int obj_id = Convert.ToInt32(changes["id"]); + Contact contact_to_update = db.Contacts.First(c => c.ID == obj_id); + // this method will update only the modified fields + RhoconnectNET.Helpers.merge_changes(contact_to_update, changes); + db.Entry(contact_to_update).State = EntityState.Modified; + db.SaveChanges(); + return RhoconnectNET.Helpers.serialize_result(contact_to_update.ID); + } + +### Implement rhoconnect_delete to Delete Objects from the Dataset + +The route `/rhoconnect/delete` is mapped to the `rhoconnect_delete` method of the IRhoconnectCRUD interface that you must implement in the corresponding dataset's Controller class. It should return a deleted object's id in case of success. + +In the case of the sample ASP.NET MVC application, you could implement this method in the `ContactsApp/Controllers/ContactController.cs` file as follows: + + public ActionResult rhoconnect_delete(Object objId, String partition) + { + int key = Convert.ToInt32(objId); + + Contact contact = db.Contacts.Find(key); + db.Contacts.Remove(contact); + db.SaveChanges(); + return RhoconnectNET.Helpers.serialize_result(key); + } + +### Partitioning Datasets + +Each of the above methods have a partition key supplied with the CRUD request. This partition key is used by `Rhoconnect` to uniquely identify the model dataset when it is stored in a rhoconnect instance. It is typically an attribute on the model or related model. `Rhoconnect` supports two types of partitions: + +* app - No unique key will be used, a shared dataset is synchronized for all users. +* String partition key - unique key string identifying the partition (typically, user name). + +For example, the `Contact` model above might have a relationship to the User model. This provides us a simple way to organize the `Contact` dataset for rhoconnect by reusing this relationship. +In this case, your implementation might filter out data on a per user basis. + +For more information about Rhoconnect partitions, please refer to the [Rhoconnect docs](http://docs.rhomobile.com/rhoconnect/source-adapters#data-partitioning). + +## Notifying the RhoConnect Server of Changes Made by the Backend Application + +You must implement methods to notify the Rhoconnect server instance about the changes made in your MVC backend application. Typically, your MVC Controller class reacts to the actions by implementing the CRUD POST routes, for example: + + [HttpPost] + public ActionResult Create(Contact new_contact) + { + if (ModelState.IsValid) + { + db.Contacts.Add(new_contact); + db.SaveChanges(); + return RedirectToAction("Index"); + } + + return View(new_contact); + } + +You need to insert calls in your ASP.NET MVC application which will notify the Rhoconnect server instance that the backend created, updated, or deleted an object. For this reason, the `RhoconnectNET` library provides three callback routines for CUD notifications: `notify_on_create`, `notify_on_update`, and `notify_on_delete`. + +### Notifying the RhoConnect Server that the Backend Created a New Object + +You need to insert a call to `notify_on_create` to notify the Rhoconnect server instance that a new object has been created. + +The previous example for ActionResult Create will look like this after inserting the corresponding callback routine: + + // This method is used to access current partition + // in Rhoconnect notification callback + private String partition() + { + // If you're using 'app' partition + // uncomment the following line + // return "app"; + return "testuser"; + } + + [HttpPost] + public ActionResult Create(Contact contact) + { + if (ModelState.IsValid) + { + db.Contacts.Add(contact); + db.SaveChanges(); + + // insert these lines to provide + // notifications to Rhoconnect server + RhoconnectNET.Client.notify_on_create(partition(), contact); + + return RedirectToAction("Index"); + } + + return View(contact); + } + +In the example above, you need to call the `RhoconnectNET.Client.notify_on_create` method with the following parameters: + + + + + + + + + + + + +
                                                                              Stringpartitionpartition to which the object belongs (see above section "Partitioning datasets") + In the above example, the partition string is returned from the partition() method
                                                                              Objectnew_objectnewly inserted object, which will be passed to Rhoconnect in a Json form
                                                                              + +### Overriding To Pass Information Into the notify_on_create Callback Method + +The above notification callback has several overloads. In its simplest form, the +`notify_on_create` callback will obtain information about the source name from the `Contact` object +class name (since it is equal) and will get the `id` field from the object itself. If your model +stores `id` field under the custom name, then you can use the following override to pass its name into +the callback, where its value will be accessed through the Reflection mechanism: + + // insert these lines to provide + // notifications to Rhoconnect server + RhoconnectNET.Client.notify_on_create(partition(), "MyContactCustomID", contact); + +In addition, if your model's class is not equal to the Rhoconnect's Source Adapter name, you can use the following override to pass it along: + + // insert these lines to provide + // notifications to Rhoconnect server + RhoconnectNET.Client.notify_on_create("MyCustomContactSourceName", partition(), "MyContactCustomID", contact); + +### Notifying the RhoConnect Server that the Backend Application Edited or Deleted + +In the same fashion, your dataset's Controller need to implement `Edit` and `Delete` callback notifications. + + [HttpPost] + public ActionResult Edit(Contact contact) + { + if (ModelState.IsValid) + { + db.Entry(contact).State = EntityState.Modified; + db.SaveChanges(); + + // insert this callback to notify Rhoconnect + // about the update operation + RhoconnectNET.Client.notify_on_update(partition(), contact); + + return RedirectToAction("Index"); + } + return View(contact); + } + + [HttpPost, ActionName("Delete")] + public ActionResult DeleteConfirmed(int id) + { + Contact contact = db.Contacts.Find(id); + db.Contacts.Remove(contact); + db.SaveChanges(); + + // insert this callback to notify Rhoconnect + // about the delete operation + RhoconnectNET.Client.notify_on_delete("Contact", partition(), id); + + return RedirectToAction("Index"); + } + +## Meta +Created and maintained by Maxim Zverev. + +Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/plugin-intro.md b/docs/en/5.5/rhoconnect/plugin-intro.md new file mode 100644 index 00000000..20ce4c92 --- /dev/null +++ b/docs/en/5.5/rhoconnect/plugin-intro.md @@ -0,0 +1,10 @@ +RhoConnect Plugins Introduction +=== + +Rhoconnect Plugins allow you to connect your backend apps seamlessly with rhoconnect. You can write the source (query, create, update and delete operations) into a backend application, and use a RhoConnect plugin in the language that matchs your backend application, such as Java or .NET. + +**NOTE: When you create a RhoConnect Plugin to connect your backend apps, you should not create a corresponding RhoConnect source adapter. RhoConnect Plugins do not use RhoConnect source adapters.** + +image + +**NOTE: Instead of using RhoConnect Plugins to connect particular backend applications (such as for Salesforce or Oracle), you can generate a [RhoConnect source adapter](source-adapters) which contains the query, create, update and delete operations.** \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/preparing-production.md b/docs/en/5.5/rhoconnect/preparing-production.md new file mode 100644 index 00000000..62c4bdf0 --- /dev/null +++ b/docs/en/5.5/rhoconnect/preparing-production.md @@ -0,0 +1,82 @@ +# Preparing App for Production +By default your RhoConnect application generates a few files that you should be familiar with and understand the settings. + +## config.ru +This rackup file contains runtime configuration for the RhoConnect sinatra application: + + :::ruby + Rhoconnect::Server.disable :run + Rhoconnect::Server.disable :clean_trace + Rhoconnect::Server.enable :raise_errors + Rhoconnect::Server.set :secret, '' + Rhoconnect::Server.set :root, ROOT_PATH + Rhoconnect::Server.use Rack::Static, :urls => ["/data"], :root => Rhoconnect::Server.root + +The important setting here `:secret` you will want to change. `:secret` should be set to a long random string, it ___should not___ be set to a dictionary word or short string (30 characters or more is sufficient). This is used for the session storage using a digest algorithm as described [here](http://guides.rubyonrails.org/security.html#session-storage). + +If you don't change the `:secret` setting, RhoConnect automatically warns you each time the application starts: + + [11:34:56 AM 2011-01-12] ************************************************************ + + [11:34:56 AM 2012-01-12] WARNING: Change the session secret in config.ru from to something secure. + [11:34:56 AM 2012-01-12] i.e. running `rhoconnect secret` in your app will generate a secret you could use. + + [11:34:56 AM 2011-01-12] ************************************************************ + + +As this warning states, a good way to generate a cryptographically secure secret is by running `rhoconnect secret` in your RhoConnect application. + + :::term + $ cd storemanager-server + $ rhoconnect secret + 040a2355475e9d0fb591ef78d5b9ca61a34cbcfd3f11942b18bc1d91f1ca66c27b2e0386333843a7efa29f40fff03624cd908d0883364ffbfa3208ab23fa2664 + +Then plug this secret into your `config.ru`: + + :::ruby + Rhoconnect::Server.set :secret, '040a2355475e9d0fb591ef78d5b9ca61a34cbcfd3f11942b18bc1d91f1ca66c27b2e0386333843a7efa29f40fff03624cd908d0883364ffbfa3208ab23fa2664' + +To run RhoConnect in production mode, use `RACK_ENV` environment variable set to "production". This ensures RhoConnect will use the `:production` section of the settings. For example: + + :::term + $ thin start -e production -p 9292 + +Will start thin in with `RACK_ENV` set to "production". + +NOTE: If you deploy using passenger or on RhoHub, this variable is automatically set to production. + +### Asynchronous processing + +RhoConnect version 3.2.x introduces a new feature which enables asynchronous processing of the incoming requests to improve the responsiveness of the Rhoconnect application using EventMachine, Fibers API, and Rack Fiber Pool. This new feature is available with Ruby 1.9.x and enabled by default. It is not available with Ruby 1.8.7, JRuby and REE. +To disable the feature and revert back to synchronous handling, you can use the following options in the `config.ru` file: + + :::ruby + Rhoconnect::Server.set :use_async_model, false # true by default + +By default, the Rhoconnect application is started with Rack FiberPool's size equal to 100 and EventMachine's thread pool size set to 20. To adjust those settings you can use the following options: + + :::ruby + # adjust the Rack FiberPool size + Rhoconnect::Server.set :fiberpool_size, 50 # default is 100 + + # adjust the EventMachine Thread Pool size + EventMachine.threadpool_size = 25 # default is 20 + + +## settings/settings.yml +This file contains all source adapter options and settings, such as the redis server connection. Before deploying to production, make sure you have the appropriate production settings. A complete list of the settings is in the [RhoConnect Settings chapter](settings). Some sample settings for production are shown below. In this sample, the `poll_interval` setting was auto-generated for a source adapter named Product. + + :::yaml + :sources: + Product: + :poll_interval: 300 + + :production: + :redis: myredishost:6379 + :licensefile: settings/license.key + :syncserver: http://localhost:9292/application/ + +## settings/license.key +This contains your RhoConnect license key text. By default, a RhoConnect application comes with a 10 device license. Please see the [licensing page](licensing) for more details. + + diff --git a/docs/en/5.5/rhoconnect/push-backend-setup.md b/docs/en/5.5/rhoconnect/push-backend-setup.md new file mode 100644 index 00000000..40c88b63 --- /dev/null +++ b/docs/en/5.5/rhoconnect/push-backend-setup.md @@ -0,0 +1,159 @@ +Setting Up Push on Backend Application +=== + +A RhoConnect push to the client consists of executing a RhoConnect ping call. There are three ways to execute a ping call: you can use the RhoConnect REST API to remotely call the ping, perform the ping job directly in a blocking ruby call, or enqueue a resque job to ping asynchronously. + +The push message can trigger the following actions in the Rhodes client application: alert with a message, sync one or more sources, vibrate, display a badge, and play a sound file. + +## Pushing Remotely with the RhoConnect REST API + +You can trigger a push remotely using the [RhoConnect API Ping method](rest-api). This is useful if you want to fully control the push process from a remote server, such as when you use a RhoConnect plugin to connect your backend application to the RhoConnect server application. + +**NOTE: If you want to sync all the sources, use 'all' for the source list (the source_name parameter) instead of a comma-separated list of the RhoConnect application source names to sync.** + +### Example of Ping for Ruby Backend Application + +As an example, here is how to send a PUSH message to all the devices of the specified user(s) from a Ruby backend app: + + :::ruby + # :message - message which will be used to display notification popup dialog on the device + # :badge - iphone specific badge + # :sound - name of the sound file to play upon receiving PUSH notification + # :vibrate - number of seconds to vibrate upon receiving PUSH notification + # :sources - list of data source names to be synced upon receiving PUSH notification + ping_params = { + :api_token => token, + :user_id => [array_of_users], + :sources => source_name, + :message => 'hello world', + :vibrate => 2000, + :sound => 'hello.mp3' + } + + RestClient.post( + "#{server}/rc/v1/users/ping", ping_params.to_json, + { :content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token } + ) + +### Example of Ping for .NET Backend Application + +As an example, here is how to send a PUSH message to all the devices of the specified user(s) from a .NET backend app: + + private static bool perform_ping(String method, String source_name, String the_message, String vibrate_time, String sound_file, Hashtable reqHash) + { + // add meta information + reqHash.Add("user_id", [array of users]); + reqHash.Add("source_id", source_name); + reqHash.Add("message", the_message); + reqHash.Add("vibrate", vibrate_time); + reqHash.Add("sound", sound_file); + + JavaScriptSerializer js = new JavaScriptSerializer(); + string requestBody = js.Serialize(reqHash); + + Uri address = new Uri(_endpoint_url + "/rc/v1/users /ping"); + HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; + request.ContentType = "application/json"; + request.Method = "POST"; + request.Headers.Add("X-RhoConnect-API-TOKEN", _api_token); + + byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody); + request.ContentLength = byteData.Length; + using (Stream requestStream = request.GetRequestStream()) + { + requestStream.Write(byteData, 0, byteData.Length); + } + using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) + { + ; + } + + return true; + } + +### Example of Ping for Java Backend Application + +As an example, here is how to send a PUSH message to all the devices of the specified user(s) from a Java backend app: + + :::java + private boolean performPing(String method, String sourceName, HashMap hash) { + hash.put("api_token", apiToken); + hash.put("source_id", sourceName); + hash.put("user_id", partition); + hash.put("message", "hello world"); + hash.put("vibrate", "2000"); + hash.put("sound", "hello.mp3"); + + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity(hash, headers); + + ResponseEntity response = restTemplate.exchange( + endpointUrl + "/rc/v1/users/ping", + HttpMethod.POST, + entity, + String.class); + HttpStatus statusCode = response.getStatusCode(); + + return(statusCode.value() == 200); + } + +## Pushing Directly from a RhoConnect Source Adapter + +When you use a RhoConnect source adapter to connect to your backend service, you can use the PingJob.perform method to perform a ping on your mobile client. + + :::ruby + PingJob.perform( + 'user_id' => current_user.login, + 'sources' => ['Product','Customer'], + 'message' => 'hello world', + 'vibrate' => 2000, + 'sound' => 'hello.mp3' + ) + +Let's say we want to execute a ping for the `current_user` at the end of your RhoConnect source adapter query. + + :::ruby + def query(params=nil) + parsed = JSON.parse(RestClient.get("#{@base}.json").body) + + @result = {} + parsed.each do |item| + @result[item["product"]["id"].to_s] = item["product"] + end if parsed + PingJob.perform( + 'user_id' => current_user.login, + 'sources' => ['Product'], + 'message' => "There are new products!", + 'vibrate' => 2000 + ) + @result + end + +## Queuing a Resque Job to Push Asynchronously + +To queue a ping that is executed asynchronously in a job, you can have PingJob queued from anywhere in your RhoConnect application (i.e. at the end of another job or adapter query method). + + :::ruby + Resque.enqueue( + PingJob, + 'user_id' => current_user.login, + 'sources' => ['Product','Customer'], + 'message' => 'hello world', + 'vibrate' => 2000, + 'sound' => 'hello.mp3' + ) + +**Note: For this job to execute, you will need to have a resque worker running. See running [async jobs](async-jobs) for more information.** + +## Triggering Push Automatically after Updating RhoConnect Data from Plugins + +Whenever a backend application modifies RhoConnect data for one of the sources, you can trigger an automatic push notification to be sent to the user's device(s) whose source data was modified. This will force the user's client application to perform a sync on the modified source. +To enable this, you need to specify the following setting in the `settings.yml` file: + + :::yaml + :push_notify: 'true' + +**Note: The automatic push notification will be applied only to the user-partitioned sources. App-partitioned sources can not trigger an automatic push notification.** diff --git a/docs/en/5.5/rhoconnect/push-client-setup-android.md b/docs/en/5.5/rhoconnect/push-client-setup-android.md new file mode 100644 index 00000000..e6b78433 --- /dev/null +++ b/docs/en/5.5/rhoconnect/push-client-setup-android.md @@ -0,0 +1,78 @@ +Setting Up RhoConnect Push-Based Synchronization with Google Cloud Messaging +=== + +This chapter contains the steps you need to set up your Android Rhodes client and RhoConnect server for push messaging. After you perform the steps in this chapter, you will finish by performing the [client setup that is needed for all platforms](push-client-setup). + +**NOTE: If you are setting up RhoConnect Push Service on an Android client, you do not perform the steps in this chapter. Perform the steps in [RhoConnect Push Service setup](push-client-setup-rps) instead.** + +## Setting up Android Google Cloud Messaging + +To set up your Android Rhodes client application and RhoConnect server application for RhoConnect Push, you need to set up Android Google Cloud Messaging (GCM). + +To do so, perform the following sections from the [GCM Getting Started](http://developer.android.com/google/gcm/gs.html) guide. + +1. Creating a Google API project. (This gets a Google API project number which you will set in your Android client application.) +2. Enabling the GCM Service. +3. Obtaining an API Key. (You will set this key in your RhoConnect application.) + +You can optionally stop in these Getting Started instructions once you complete the Obtaining an API Key section. + +You may read common [GCM docs](http://developer.android.com/guide/google/gcm/index.html) at the Google developer site. + +## Setting up RhoConnect Server Application for GCM Push + +To set up your RhoConnect application for Android Google Cloud Messaging (GCM), you must have first set up Android Google Cloud Messaging. Then you can find your GCM API key in your [Google apis dashboard](https://code.google.com/apis/console). + +Update `settings/settings.yml` to include your GCM API key: + + :::yaml + :development: + :redis: localhost:6379 + :syncserver: http://localhost:9292/application/ + :licensefile: settings/license.key + :gcm_api_key: your_gcm_api_key_here + +## Enabling the Rhodes Android Client for Push + +Enable push in your Rhodes client application in build.yml. + + :::yaml + capabilities: + - push + +## Setting up the Rhodes Android (GCM) Client + +Here are some guidelines for developing and testing an Android application that uses the Android Google Cloud Messaging feature. + +* To develop and test your GCM applications, you need to run and debug the applications on an Android 2.2 system image that includes the necessary underlying Google services. +* To develop and debug on an actual device, you need a device running an Android 2.2 system image that includes the Market application. +* To develop and test on the Android Emulator, you need to download the Android 2.2 version of the Google APIs Add-On into your SDK using the Android SDK and AVD Manager. Specifically, you need to download the component named "Google APIs by Google Inc, Android API 8". Then, you need to set up an AVD that uses that system image. +* Android GCM system uses an existing connection for Google services. This requires users to set up their Google account on their mobile devices (and on emulator!). + +### Setting up the Google API project ID in Your Client Application + +To set up your Rhodes client application for Android Google Cloud Messaging (GCM), you must have first set up Android Google Cloud Messaging, where you noted the Google API project number. + +Register the Google API project number for your client application. Modify your application's build.yml to specify the Google API project number used to send PUSH messages: + + :::yaml + android: + push: + sender: + +### Setting up Status Bar Notifications for PUSH Messages + +On the Android client, it is possible to set up status bar notifications for PUSH messages. In this case, push notification can be shown on the Android status bar after ruby callback. The user can activate application by touching this notification. +There are two modes available for push notifications: + - always - push notification is shown always + - background - push notification is shown only if application put into the background (not started) +If no push notification mode is specified in build.yml then no notifications are shown at all. + + :::yaml + android: + push: + notifications: background + +## Finishing Client Setup + +Once you have completed the above steps for setting up push on Android client and RhoConnect server, you must still [perform the client setup that is needed for all platforms](push-client-setup). diff --git a/docs/en/5.5/rhoconnect/push-client-setup-ios.md b/docs/en/5.5/rhoconnect/push-client-setup-ios.md new file mode 100644 index 00000000..dc020596 --- /dev/null +++ b/docs/en/5.5/rhoconnect/push-client-setup-ios.md @@ -0,0 +1,70 @@ +Setting Up RhoConnect Push-Based Synchronization with Apple Push Notification Service +=== + +This chapter contains the steps you need to set up your iOS Rhodes client and RhoConnect server for push messaging. After you perform the steps in this chapter, you will finish by performing the [client setup that is needed for all platforms](push-client-setup). + +## Setting up RhoConnect Server Application for Push to iOS Clients + +To set up your RhoConnect application for pushing to an iOS client, you will need to update `settings/settings.yml` to include the following: + + :::yaml + :development: + :redis: localhost:6379 + :iphonecertfile: settings/apple_push_cert.pem + :iphonepassphrase: #=> must be empty or a string, not a number (i.e. "" or "some-secure-passphrase-here") + :iphoneserver: gateway.sandbox.push.apple.com + :iphoneport: 2195 + :syncserver: http://localhost:9292/application/ + :licensefile: settings/license.key + +This is for running your application in development mode; for production, you will need all of the iphone settings, and you change the `:iphoneserver:` to: + + :::yaml + :iphoneserver: gateway.push.apple.com + +## Enabling Rhodes Client for RhoConnect Server Push + +Enable push in your rhodes application in build.yml. + + :::yaml + capabilities: + - push + +## Setting up the Rhodes iOS (APNS) Client for Push + +iOS PUSH support uses the Apple Push Notification Service (APNS) introduced in iOS SDK 3.0. In order to use the service, you will need to obtain a push-enabled provisioning profile and a server-side push certificate used for encrypting RhoConnect->APNS traffic. + +In case of iOS, regardless of the operation, the user will be presented with the option to activate the application if it is not running. + +**NOTE: For testing push, you will need to build and deploy your application to a physical iPhone (or iPad) device. Apple does not support testing push on simulators.** + +### Setup Push Certificate +The first step to setting up your environment is to create an APNS push certificate. To create the SSL certificate, follow the "Creating the SSL Certificate and Keys" section on the +[developer site](https://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ProvisioningDevelopment.html#//apple_ref/doc/uid/TP40008194-CH104-SW1). + +Once you have the certificate, you will need to export it to a .pem format using [these instructions](https://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ProvisioningDevelopment.html#//apple_ref/doc/uid/TP40008194-CH104-SW6). Make sure to name the output file 'apple_push_cert.pem' file from these instructions, since this is what we configured in our RhoConnect application. + +Once you have this file, copy it to your RhoConnect application directory under the settings folder: + + :::term + $ cd myrhoconnectapp + $ cp /path/to/apple_push_cert.pem settings/apple_push_cert.pem + +Now your RhoConnect application is ready to send APNS messages. + +### Setup Provisioning Profile +Next, you can setup your Apple Push Provisioning Profile using Apple's [developer site instructions](https://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ProvisioningDevelopment.html#//apple_ref/doc/uid/TP40008194-CH104-SW6). Once you have the profile installed in XCode and on your test device, you are ready to test push. + +### Setup iOS Device +Setting up the device is the same process as [building any normal Rhodes application](build#building-a-rhodes-application-for-iphoneipad). When you start the application, make sure to also open the console window (cmd-shift-R). When the application starts, you should see some output in the console that shows the device token (towards the top): + + 2010-08-19 10:14:22.627 rhorunner[1486:307] Device token is <10fd92ab fa8ee481 55d9af6e 73290863 22b323fd 0d18fdbd 19e92d03 c0fef7c8> + +This confirms that your application is running with push enabled. Once you login to the RhoConnect application and sync, you will see the device registered on the RhoConnect console under the user id you used to login. Now you are ready to [test push from your RhoConnect application](push-server-setup#testing-push-in-the-rhoconnect-web-console). + +### Alert Audio File Setup for iOS +In case of iOS, audio files for the push alert should be placed in the `/public/alerts` folder and build script will copy them into root of the application main bundle (iOS wouldn't play file from any other place). + +## Finishing Client Setup + +Once you have completed the above steps for setting up push on iOS client and RhoConnect server, you must still [perform the client setup that is needed for all platforms](push-client-setup). \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/push-client-setup-rps.md b/docs/en/5.5/rhoconnect/push-client-setup-rps.md new file mode 100644 index 00000000..574986a2 --- /dev/null +++ b/docs/en/5.5/rhoconnect/push-client-setup-rps.md @@ -0,0 +1,210 @@ +# Setting Up for RhoConnect Push Service on Client Application +The RhoConnect Push Service is a stand-alone process that brokers push messages between a RhoConnect server and Android or Windows Mobile/CE devices that have registered with the service. This guide covers setting up the RhoConnect server for the RhoConnect Push Service and the registered client. Once these steps are completed, you must then perform the [push client setup](push-client-setup) process that's required for all platforms. + +> **IMPORTANT: Do not continue** if you plan to set up RhoConnect Push for Android devices using Google Cloud Messaging. For those instructions, please refer to [RhoConnect Push for Android setup](push-client-setup-android). + +## Setting up RhoConnect Push Service on the Server +RhoConnect v3.3 introduces the RhoConnect Push Service (RPS), which supports efficient messaging for both Android and Windows Mobile/CE. On Android, this service can be used instead of Google Cloud Messaging. + +The typical flow of a message using RPS: + + Device RPS RhoConnect Backend App + + + + + + | | | | + | | | POST | + | | POST |/rc/v1/users/ping| + | |/instanceId |<----------------+ + | |<-----------+ | + |<----------+ | | + |{"content"}| | | + | | | | + + + + + + +### Download and Install Node.js +On Mac development hosts, go to the [Node.js website](http://nodejs.org/#) and download and install Node.js (The Windows version of the RhoMobile Suite comes with it). + +### Starting the Push Service +RhoConnect Push Service is a separate process that will run on your machine and broker push messages between your RhoConnect server and registered devices. + +Assuming you've installed the latest [RhoMobile Suite](../guide/rhomobile-install), start redis by runing the following command: + + :::term + $ rhoconnect redis-start + +Now start RhoConnect push by running the following command: + + :::term + $ rhoconnect-push + RhoConnect push server started... + +You can also start the server with more verbose logging (see next section for more details): + + :::term + $ rhoconnect-push -d 3 + +Next, make sure you have the following option in your RhoConnect application's `settings/settings.yml` file in the `:development:`, `:production:` and `:test:` sections: + + :::yaml + :push_server: http://someappname@localhost:8675/ + +Where you edit `someappname` to be a shared secret name between your RhoConnect application and your mobile application. + +> Note: This shared secret name ensures that only your RhoConnect application can send push messages to the RPS instance you started up in the previous step. Use this shared secret name in your [mobile app's 'rhoconnect_push_appname' setting](push-client-setup-rps#configuring-rhoconfigtxt). + +Now set up [push notifications](push-client-setup#configuring-a-rhodes-application-to-receive-push-with-rhoconnect-push-service) in your Android or Windows Mobile RhoElements application, then start up your RhoConnect application. + +### Configuring RhoConnect Push +You can control basic settings for RhoConnect push using command line arguments. + + :::term + $ rhoconnect-push --help + + Usage: rhoconnect-push [options] + + Available options: + -c, --config FILE Path to configuration (config.json) file + -d, --debug LEVEL Specify server debug level: 0 (errors) - 3 (everything) + -e, --rcPort PORT Specify RhoConnect instance port + -h, --help Print this help message + -i, --rcHost HOST Host for the RhoConnect instance + -k, --keyFile FILE Path to private SSL keyfile (https only) + -p, --port Run the server on this port (defaults to 8675) + -r, --redis REDIS Redis connection string (i.e. redis://localhost:6379) + -s, --httpSecure Specify whether server uses HTTPS (or HTTP) + -R, --rcSecure Specify whether Rhoconnect server uses HTTPS (or HTTP) + -t, --timeout TIMEOUT Time (in ms) before timeout is sent to client + -T, --registrationTimeout Expiration limit for client registration tokens + -v, --version Display server version + +### Configuring and Running with config.json Advanced Options +You can also configure more advanced settings in RhoConnect push by creating a config.json file. + + :::json + { + "httpSecure": "n", + "rcSecure": "n", + "devAuthHost": "localhost", + "devAuthUrl": "/rc/v1/app/rps_login", + "devAuthPort": "9292", + "userAuthHost": "localhost", + "userAuthUrl": "/rc/v1/app/rps_login", + "userAuthPort": "9292", + "appAuthHost": "localhost", + "appAuthUrl": "/rc/v1/system/rps_login", + "appAuthPort": "9292", + "ansResponseTimeout": "300000", + "ansServerPort": "8675", + "registrationTimeout": "2592000", + "clearDataBase": "n", + "socketPoolSize": 1, + "debugLevel": "3" + } + +To start the server using a config.json file, run the following command. + + :::term + $ rhoconnect-push -c /path/to/config.json + +The JSON file has the following parameters. + +* `httpSecure` - Specify whether to secure the push server (y=HTTPS; n=HTTP). +* `rcSecure` - Specify whether to secure the Rhoconnect server (y=HTTPS; n=HTTP). +* `devAuthHost` - RhoConnect instance used to handle device credentials. +* `devAuthUrl` - Path used on the RhoConnect instance to handle device credentials. +* `devAuthPort` - Port used on the RhoConnect instance to handle device credentials. +* `userAuthHost` - RhoConnect instance used to handle user credentials. +* `userAuthUrl` - Path used on the RhoConnect instance to handle user credentials. +* `userAuthPort` - Port used on the RhoConnect instance to handle user credentials. +* `appAuthHost` - RhoConnect instance used to handle application credentials. +* `appAuthUrl` - Path used on the RhoConnect instance to handle application credentials. +* `appAuthPort` - Port used on the RhoConnect instance to handle application credentials. +* `ansResponseTimeout` - Time (in ms) that the push server will allow a message request from the client to go without a response. Upon expiration of this time, a 204 response will be issued and the request will be considered satisfied. If this parameter is set to 0, then this time limit will not be in effect - there is no limit to how long a client request will go without a response. +* `ansServerPort` - Push server listening port +* `registrationTimeout` - Expiration limit for registration tokens (in seconds), the client-side application is automatically unregistered if there is no activity related to its token for the registrationTimeout period. Activity related to its token consists of either attempted fetches of messages on its behalf by the push client or messages sent to the push server by RhoConnect. +* `clearDataBase` - Clear the redis database containing tokens, instanceIds, etc. at the start of the push server (y/n). +* `socketPoolSize` - The maximum number of sockets the push server will use when connecting to each of the authorization servers. This essentially caps the number of http requests to each authorization server that the push server can have outstanding at any given time. +* `debugLevel` - Print additional information to console to aid in debugging: + * 0 - print only error & warning info + * 1 - print error & warning info and message for each invoked ANS operation + * 2 - reserved for future use + * 3 - print everything + +## Installing the rhoconnect-push-service Runtime Apps on the Mobile Device +To use the RhoConnect Push Service in your client application, you must install the rhoconnect-push-service runtime app(s) on your mobile device. + +On a Mac, the rhoconnect-push-service runtime apps for Android and for Windows Mobile are located in the Zebra RhoMobile Suite installation package, in a folder called rhoconnect-push-service. + +On Windows, the rhoconnect-push-service runtime apps for Android and for Windows Mobile are located in the Zebra RhoMobile Suite installation, in a directory called rhoconnect-push-service. + +### Installing Runtime Apps on Android Device +If you are using an Android device, install `rhoconnect_push_service.apk` to your device. + +#### Using ADB +One way to install the .apk is to connect your Android to your computer with a USB cable and use `adb install`. You can verify that your device is connected by executing: + + $ adb devices + +If connected, you'll see the device name listed. If your computer doesn't see the device, try killing the adb process first: + + $ adb kill-server + +Then navigate to the directory containing the runtime file and run `adb install`. + + $ adb install .apk + +#### Other Installation Methods +You also can use AppGallery or an MDM system to deploy the .apk file to the device, or connect via USB and simply copy it, assuming that the device file system is exposed. These methods would be completed by browsing to the .apk file and executing it. Package contents will install where appropriate. + +### Installing Runtime Apps for Windows Mobile/CE Devices +On Windows Mobile/CE devices, install the following runtime apps on your device. If you already have the [.NET Compact Framework](http://msdn.microsoft.com/en-us/library/bb788171\(v=vs.90\).aspx) on your device, make sure it is v3.5 or higher. + +* `rhoconnect-push-service.CAB` +* `NETCFv35.Messages.EN.wm.cab` +* `NETCFv35.Messages.EN.cab` + +**NOTE: On Windows CE 7.0, you may see the following warning: "The program is not compatible with the current operating system and, therefore, may not run on this device." You can safely ignore this warning and click the "Yes" button.** + +Connect your device to your Windows computer. You can use a USB cable, Bluetooth or any other method. Start Windows Mobile Device Center (ActiveSync on Windows XP). + +Manually copy the .cab files to the device. For example, you can use the device File Explorer to display the .cab files that are on the device. Click on each .cab file and the installation process will be started; after it is finished, you should see the app icon on your device in Programs. You should then create a shortcut in the Startup folder so that this applications runs when the device starts. Or if you are using other methods for ensuring certain applications are always running. If this application is not running, it will not receive RhoConnect Push notifications. + + +### Installing Runtime Apps for Windows XP Embedded +Windows XPE installation requires that you have the following items installed on your XPE device. + +* .NET 3.5 Compact Framework +* .NET 4 Compact Framework + +NOTE: These are both required because the push service for XPE needs parts of both 3.5 and 4 to function properly. + +Next install [Microsoft Messaging Queue (MSMQ)](https://msdn.microsoft.com/en-us/library/aa967729\(v=vs.110\).aspx) on your build machine. + +Connect your device to your Windows computer. You can use a USB cable, Bluetooth or any other method. Start Mobile Device Center (ActiveSync on Windows XP) and copy the `rhoconnect-push-service.exe` file to the device. For example, you can use your computer's file explorer to place the .exe file on your device. Once the file is on your device, navigate to the file and click on the .exe file to start the installation process. After it is finished, you should see the app icon on your device in the programs list. + +NOTE: The RhoConnect push service on Windows XP Embedded is a separate program on your device and will not be uninstalled when uninstalling other apps or programs. + +## Setting up the Rhodes Client for RhoConnect Push Service +To set up your Rhodes client application for RhoConnect Push Service, you configure `rhoconfig.txt` and `build.yml`. + +### Configuring rhoconfig.txt +In your client application `rhoconfig.txt` file, set the following options to configure your RhoConnect Push Service: + + syncserver = 'http://:' + Push.rhoconnect.pushServer = 'http://:' + Push.rhoconnect.pushAppName = 'someappname' + +Next, your RhoConnect application should be running on a network that is accessible to your device. For example, you might have your RhoConnect application running on a LAN with IP 192.168.1.10, PORT 9292. Then make sure your device is connected to the same LAN. + +Below is an example of setting `rhoconfig.txt` for the RhoConnect Push Service. The URLs used for the RhoConnect Push Service (Push.rhoconnect.pushServer) and the RhoConnect server are running on the same host. + + syncserver = 'http://192.168.1.10:9292' + Push.rhoconnect.pushServer = 'http://192.168.1.10:8675' + Push.rhoconnect.pushAppName = 'someappname' + +### Configuring build.yml +When you configure your application `build.yml` file for RhoConnect Push Service, do not add `push` under `capabilities`. Instead, add rhoconnect-push to extensions, as below: + + extensions: ["rhoconnect-push"] + +## Finishing Client Setup +Once the above steps for setting up the RhoConnect Push Service on Android or Windows Mobile/CE client and RhoConnect server are completed, you must then perform the [push client setup](push-client-setup) process that's required for all platforms. \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/push-client-setup.md b/docs/en/5.5/rhoconnect/push-client-setup.md new file mode 100644 index 00000000..0987fe62 --- /dev/null +++ b/docs/en/5.5/rhoconnect/push-client-setup.md @@ -0,0 +1,116 @@ +Setting Up for RhoConnect Push on Client Application +=== + +This chapter contains the final steps for setting up your Rhodes application for RhoConnect Push. You also need to perform the setup on client and server for your mobile device platform (if you have not done so already). + + * [Setup for RhoConnect Push Service on client and server](push-client-setup-rps). + * [Setup for RhoConnect Push on client and server for Rhodes Android Client](push-client-setup-android). + * [Setup for RhoConnect Push on client and server for Rhodes iOS Client](push-client-setup-ios). + +## Configuring a Rhodes Application for RhoConnect Push + +If you want your device to vibrate when it receives a push message, enable vibration in your Rhodes/RhoElements application in build.yml. + + :::yaml + capabilities: + - vibrate #=> if you want to enable vibrate in your push messages + +Set up your application [rhoconfig.txt](../guide/runtime_config) syncserver to point to your RhoConnect server: + + syncserver = 'http://' + +## Registering a Push Callback in the Rhodes Application + +To handle a push message from a Rhodes application, you must register push callback with the Rho::Push `startNotifications` method. + + :::ruby + class AppApplication < Rho::RhoApplication + def initialize + super + Rho::Push.startNotifications '/app/Settings/push_callback' + end + end + +Push callback is set up in the form of a local application URL and called when application receives server initiated push messages. + +The callback push message parameters are presented in the form of a hash. This hash contains parameters and values for the operations to perform. The operations are to show an alert, vibrate the device, play a sound, and perform a sync for a list of sources. + +To have your Rhodes app automatically perform the operations listed in the push message, you can write the callback as follows. + + :::ruby + def push_callback + # Variable @params is a hash of operations to perform + # Show 'alert' popup window + Rho::Notification.showPopup({'message' => @params['alert'], 'buttons' =>['OK']}) + end + +To get push messages from RhoConnect server, the user must be logged into the RhoConnect server. + +In application.rb: + + :::ruby + if SyncEngine::logged_in > 0 + Rho::Push.startNotifications '/app/Settings/push_callback' + end + +## Understanding the Rhodes Push Message Payload + +From Rhodes 2.0.4 on, the callback push message parameters are in the form of a hash. This hash contains parameters and values for the operation to perform. If the parameter for that operation is not listed, the operation is not performed. + +The hash payload may include the parameters of alert, do_sync, sound, and vibrate which perform operations that the client performs when it receives the PUSH message. Here is an example of a push message body with the parameter names and values. It will have a popup alert message of "some message", play a sound of alert.mp3, will vibrate the device, and will sync the product and customer sources. + + :::text + alert=some message here&sound=alert.mp3&vibrate=2000&do_sync=product,customer + +To sync all the sources with do_sync, the source name list would be specified as 'all' in the ping call, instead of 'product,customer' as in this example. + +The Rhodes push payload allows more than one operation in a single message. + +There are no required operations. There are default operations - if operation is not specified, no default operation will be performed. + +Payload may include following operations which client will perform when it receives the PUSH message: + +do_sync - do sync on spec specified sync source; use "all" to sync all sources + :::ruby + # one or more sources, or "all" can be specified + do_sync = "Product,Customer" + +alert - bring app upfront and show specified message + :::ruby + alert = "Some message" + +vibrate - vibrate for the specified number of milliseconds, up to 25500; if 0 or no duration is specified, it will vibrate for 2500 millisecond. + +To enable vibrate in your rhodes application in build.yml: + + capabilities: + - vibrate + +Example of vibrate call: + + vibrate = 2000 #=> duration in milliseconds + +sound - play specified file if media type supported by the phone. iPhone will ignore media-type parameter. + :::ruby + sound = "hello.mp3" + +The sound file should be included to the application bundle in `/public/alerts` folder. + +Media type should be either specified explicitly or may be recognized from file extension. Known file extensions are: .mp3 - audio/mpeg; .wav - audio/x-wav. + +## Handling Push Notifications from a non-RhoConnect Application + +Rhodes applications can also handle PUSH notifications that didn't come from a RhoConnect application. + +In this example, we will get the device ID so we can register the device with some push server: + :::ruby + Rho::Push.getDeviceId url_for(:action => 'registration_callback') + +Application can set push callback to process any commands from server: + :::ruby + Rho::Push.startNotifications '/app/Settings/push_callback' + +Callback parameters: + +* since Rhodes 2.0.4 : contain push message parameters as hash +* rhodes < 2.0.4 : message - contain server push message body diff --git a/docs/en/5.5/rhoconnect/push-testing.md b/docs/en/5.5/rhoconnect/push-testing.md new file mode 100644 index 00000000..f2c0c456 --- /dev/null +++ b/docs/en/5.5/rhoconnect/push-testing.md @@ -0,0 +1,29 @@ +Testing Push in the RhoConnect Web Console +=== + +The [RhoConnect Web Console](web-console) includes a utility for testing push to make sure everything is wired up correctly. + +First, make sure you've logged in and performed a sync on the device/simulator you are going to test. + +Next, once you've logged into the web console, navigate to the user's page you used to login in the Rhodes application. For example, if you logged in as user 't', the url would be: + + http://localhost:9292/console/user?user_id=t + +You should see a registered device for this user, for example: "c92e36874bc74f39a8fbd7c1a86f9e0e". Click on the link for this device and you will see the device attributes: + + device_type: APPLE + device_pin: 10fd92abfa8ee48155d9af6e7329086322b323fd0d18fdbd19e92d03c0fef7c8 + device_port: 100 + user_id: t + app_id: application + +**NOTE: If you don't see all of these attributes, then something is incorrect in your Rhodes application settings. Please verify you followed the [Rhodes application push setup](push-client-setup).** + +Now that the device is registered, go back to the user page and click 'Ping User'. + +Here you can specify an alert message, sources array to sync, badge value (iOS only), sound file to play, and duration to vibrate. + +Enter in some values or try the defaults, you should see a push message on the device when you click "Ping!". + +By default, the sources list will be a comma-separated list of your RhoConnect application's sources. This sources list will be sent in the push message to trigger a sync. You can specify one or more sources, or 'all' to trigger a sync of all sources. + diff --git a/docs/en/5.5/rhoconnect/push.md b/docs/en/5.5/rhoconnect/push.md new file mode 100644 index 00000000..45c26098 --- /dev/null +++ b/docs/en/5.5/rhoconnect/push.md @@ -0,0 +1,27 @@ +Push Synchronization +=== + +Use push synchronization when you want to automatically detect changes on the RhoConnect side, and you want to push those changes to your client without having to tell your client to sync. + +RhoConnect has a simple ruby API for sending push notifications (a ping call) to a user's devices. This API can be called directly, queued as a resque job, or called remotely via the [RhoConnect REST API](rest-api). The push message can trigger the following actions in the Rhodes application: alert with a message, sync one or more sources, vibrate, display a badge, and play a sound file. + +The following sections show how to use the RhoConnect application to deliver push messages to each client platform and how you can handle the push notification in your Rhodes application. + +## Setting up Server and Client + +You will need to perform one of the following set of instructions on the RhoConnect server and your mobile device for your specific platform. + +* [Set up RhoConnect Push Service on client and server for Rhodes Android and Windows Mobile/CE Devices](push-client-setup-rps). +* [Set up Google Cloud Messaging on client and server for Rhodes Android Device](push-client-setup-android). +* [Set up Apple Push Notification Service on client and server for Rhodes iOS Device](push-client-setup-ios). +Then you will need to [perform the final set up on your client](push-client-setup). + +## Executing a Ping Call + +RhoConnect has a simple ruby API for sending push notifications (a ping call) to a user's devices. You can [execute a ping call from your RhoConnect source adapter or from your backend application that uses a RhoConnect plugin](push-backend-setup). + +## Testing Push + +You can [test push from the RhoConnect console](push-testing). + + diff --git a/docs/en/5.5/rhoconnect/rails-plugin.md b/docs/en/5.5/rhoconnect/rails-plugin.md new file mode 100644 index 00000000..64901fe4 --- /dev/null +++ b/docs/en/5.5/rhoconnect/rails-plugin.md @@ -0,0 +1,330 @@ +rhoconnect-rb [![Build Status](https://secure.travis-ci.org/rhomobile/rhoconnect-rb.png)](http://travis-ci.org/rhomobile/rhoconnect-rb) +=== + +A ruby library for the [RhoConnect](http://rhomobile.com/products/rhoconnect) App Integration Server. + +Using rhoconnect-rb, your application's model data will transparently synchronize with a mobile application built on the [Rhodes framework](http://rhomobile.com/products/rhodes), or any of the available [RhoConnect clients](http://rhomobile.com/products/rhoconnect/). This client includes built-in support for [ActiveRecord](http://ar.rubyonrails.org/) and [DataMapper](http://datamapper.org/) models. + +## Getting started + +Load the `rhoconnect-rb` library: + + require 'rhoconnect-rb' + +Note, if you are using datamapper, install the `dm-serializer` library and require it in your application. `rhoconnect-rb` depends on this utility to interact with Rhoconnect applications using JSON. + +## Setup the Model +Now include Rhoconnectrb::Resource in a model that you want to synchronize with your mobile application: + + class Product < ActiveRecord::Base + include Rhoconnectrb::Resource + end + +Or, if you are using DataMapper: + + class Product + include DataMapper::Resource + include Rhoconnectrb::Resource + end + +## Partitioning Datasets + +Next, your models will need to declare a partition key for `rhoconnect-rb`. This partition key is used by `rhoconnect-rb` to uniquely identify the model dataset when it is stored in a rhoconnect instance. It is typically an attribute on the model or related model. `rhoconnect-rb` supports two types of partitions: + +* :app - No unique key will be used, a shared dataset is synchronized for all users. +* lambda { some lambda } - Execute a lambda which returns the unique key string. + +For example, the `Product` model above might have a `belongs_to :user` relationship. This provides us a simple way to organize the `Product` dataset for rhoconnect by reusing this relationship. The partition identifying a username would be declared as: + + class Product < ActiveRecord::Base + include Rhoconnectrb::Resource + + belongs_to :user + + def partition + lambda { self.user.username } + end + end + +Now all of the `Product` data synchronized by rhoconnect will organized by `self.user.username`. Note: You can also used a fixed key if the dataset doesn't require a dynamic value: + + def partition + :app + end + +For more information about Rhoconnect partitions, please refer to the [Rhoconnect docs](http://docs.rhomobile.com/rhoconnect/source-adapters#data-partitioning). + +## Querying Datasets + +`rhoconnect-rb` installs a `/rhoconnect/query` route in your application which the Rhoconnect instance invokes to query the dataset for the dataset you want to synchronize. This route is mapped to a `rhoconnect_query` method in your model. This method should return a collection of objects: + + class Product < ActiveRecord::Base + include Rhoconnectrb::Resource + + belongs_to :user + + def partition + lambda { self.user.username } + end + + def self.rhoconnect_query(partition, attributes = nil) + Product.includes(:user).where("users.username = ?", partition) + end + end + +In this example, `self.rhoconnect_query` returns a list of products where the partition string (provided by the rhoconnect instance) matches the `user_id` field in the products table. + +## Configuration and Authentication + +### Running RhoConnect Manually + +Configure RhoConnect in an initializer like `config/initializers/rhoconnect.rb` (for Rails), or directly in your application (i.e. Sinatra). Here you will setup the rhoconnect uri (the location of your RhoConnect instance), the api\_token (see [rhoconnect:get_token](http://docs.rhomobile.com/rhoconnect/command-line#rake-tasks) rake task), and app\_endpoint (the location of your ruby app): + + config.uri = "http://myrhoconnect.com" + config.token = "secrettoken" + config.app_endpoint = "http://myapp.heroku.com" + +If `app_endpoint` is defined, your Rhoconnect instance will be configured to query data from the endpoint using the rhoconnect_query method in your model. For example, if your `app_endpoint` is defined as "http://myapp.heroku.com", RhoConnect will query data with: + + POST http://myapp.heroku.com/rhoconnect/query + +Example: + + Rhoconnectrb.configure do |config| + config.uri = "http://localhost:8675" + config.token = "mydevtoken" + config.app_endpoint = "http://localhost:3000" + end + +Example with authentication: + +`rhoconnect-rb` installs a `/rhoconnect/authenticate` route into your application which will receive credentials from the client. Add block which handles the credentials: + + Rhoconnectrb.configure do |config| + config.uri = "http://localhost:8675" + config.token = "mydevtoken" + config.app_endpoint = "http://localhost:3000" + config.authenticate = lambda { |credentials| + User.authenticate(credentials[:login], credentials[:password]) + } + end + +### Using the [RhoConnect Heroku Addon](http://docs.rhomobile.com/rhoconnect/heroku-addon) + +If you're using the [RhoConnect Heroku Addon](http://docs.rhomobile.com/rhoconnect/heroku-addon), then you can omit the config.uri and config.token (they are managed for you): + + Rhoconnectrb.configure do |config| + config.app_endpoint = "http://myapp.heroku.com" + config.authenticate = lambda { |credentials| + User.authenticate(credentials[:login], credentials[:password]) + } + end + +## Rhoconnect-rb API + +### Overview of the API + +The Rhoconnectrb::API module contains routes to all the resources available in Rhoconnect. At a high level the API calls take on the following syntax: + + Namespace::Resource.verb_action1_action2_...([resource_id,action1_id,action2_id],data) + +Some of these values are not used for every API call such as resource_id and data. + +### System Resource + +#### `POST /rc/v1/system/login` + + + data = {:login=>'username',:password=>'password'} + Rhoconnectrb::API::System.post_login(data) + +#### `GET /rc/v1/system/license` + + + Rhoconnectrb::API::System.get_license + +#### `POST /rc/v1/system/reset` + + + Rhoconnectrb::API::System.post_reset({}) + +#### `GET /rc/v1/system/appserver` + + + Rhoconnectrb::API::System.get_appserver + +#### `POST /rc/v1/system/appserver` + + + data = {:adapter_url=>'http://test.com'} + Rhoconnectrb::API::System.post_appserver(data) + +#### `GET /rc/v1/system/stats` + + + data ={:names=>"*sources*"} + Rhoconnectrb::API::System.get_stats(data) + +### Store Resource + +#### `GET /rc/v1/store/:doc` + + + Rhoconnectrb::API::Store.get('docname') + +#### `POST /rc/v1/store/:doc` + + + data = {:data=>{:id=3},:append=>false} + Rhoconnectrb::API::Store.post('docname',data) + +### User Resource + +#### `POST /rc/v1/users` + + + data = {:attributes=>{:login=>'login',:password=>'password'}} + Rhoconnectrb::API::Users.post(data) + +#### `DELETE /rc/v1/users/:user_id` + + + Rhoconnectrb::API::Users.delete('user_id') + +#### `PUT /rc/v1/users/:user_id` + + + data = {:attributes=>{:a_user_specific_attribute => a_user_specific_attribute_value}} + Rhoconnectrb::API::Users.put('user_id',data) + +#### `GET /rc/v1/users` + + + Rhoconnectrb::API::Users.get + +#### `Get /rc/v1/users/:user_id` + + Rhoconnectrb::API::Users.get('user_id') + +#### `Get /rc/v1/users/:user_id/clients` + + + Rhoconnectrb::API::Users.get_clients(['user_id','client_id']) + +#### `DELETE /rc/v1/users/:user_id/clients/:client_id` + + + Rhoconnectrb::API::Users.delete_clients(['user_id','client_id']) + +#### `GET /rc/v1/users/:user_id/sources/:source_id/docnames` + + + Rhoconnectrb::API::Users.get_sources_docnames(['user_id','source_id']) + +#### `POST /rc/v1/users/ping` + + + data = { + :api_token => token, + :user_id => [array_of_users], + :sources => source_name, + :message => 'hello world', + :vibrate => 2000, + :sound => 'hello.mp3' + } + Rhoconnectrb::API::Users.post_ping(data) + +#### `GET /rc/v1/users/:user_id/sources/:source_id/docs/:doc` + + + Rhoconnectrb::API::Users.get_sources_docs(['user_id','source_id','docname']) + +#### `POST /rc/v1/users/:user_id/sources/:source_id/docs/:doc` + + + data = {:data=>data,:append=>false} + Rhoconnectrb::API::Users.post_sources_docs(['user_id','source_id','docname'],data) + +### Read State Resource + +#### `POST /rc/v1/read_state/users/:user_id/sources/:source_id` + + + data = {:refresh_time => 100} + Rhconnectrb::API::ReadState.post_users_sources(['user_id','source_id']) + +### Source Resource + +#### `GET /rc/v1/sources/type/:partition_type` + + + Rhoconnectrb::API::Sources.get_type('parition_type') + +#### `GET /rc/v1/sources/:source_id` + + + Rhoconnectrb::API::Sources.get('source_id') + +#### `PUT /rc/v1/sources/:source_id` + + + data = {:user_name=>'username',:data=>{:poll_interval=>25}} + Rhoconnectrb::API::Sources.put('source_id',data) + +### Client Resource + +#### `GET /rc/v1/clients/:client_id` + + + Rhoconnectrb::API::Clients.get('client_id') + +#### `GET /rc/v1/clients/:client_id/sources/:source_id/docnames` + + + Rhoconnectrb::API::Clients.get_sources_docnames(['client_id','source_id']) + +#### `POST /rc/v1/clients/:client_id/sources/:source_id/docnames` + + + data = {:data=>data,:append=>false} + Rhoconnectrb::API::Clients.post_sources_docnames(['client_id','source_id'],data) + +### Resource Resource + +The Resource class is used for API calls to user defined dynamic or source adapters. The resource name is passed in as a parameter. + +#### `POST /app/v1/:source_name/push_objects` + + + data = {:user_id=>'user_id',:objects=>data} + Rhoconnectrb::API::Resource.post_push_objects('source_name',data) + +#### `POST /app/v1/:source_name/push_deletes` + + + data = {:user_id => 'user_id',:objects=>'object_ids'} + Rhoconnectrb::API::Resource.post_push_deletes('source_name',data) + +#### `POST /app/v1/:source_name/fast_insert` + + + data = {:user_id=>'user_id',:objects=>data} + Rhoconnectrb::API::Resource.post_fast_insert('source_name',data) + +#### `POST /app/v1/:source_name/fast_update` + + + data = {:user_id=>'user_id',:objects=>data} + Rhoconnectrb::API::Resource.post_fast_update('source_name',data) + +#### `POST /app/v1/:source_name/fast_delete` + + + data = {:user_id=>'user_id',:objects=>data} + Rhoconnectrb::API::Resource.post_fast_delete('source_name',data) + + +## Meta +Created and maintained by Lucas Campbell-Rossen, Vladimir Tarasov and Lars Burgess. + +Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/rest-api.md b/docs/en/5.5/rhoconnect/rest-api.md new file mode 100644 index 00000000..58b842a5 --- /dev/null +++ b/docs/en/5.5/rhoconnect/rest-api.md @@ -0,0 +1,654 @@ +# RhoConnect REST API +The RhoConnect REST API allows you to control, monitor, and debug a running RhoConnect application using a simple HTTP API. + +Below we describe the REST API using ruby sample code. + +> Note: All routes that require admin privileges must pass the API token using the special header + + :::ruby + 'X-RhoConnect-API-TOKEN':api_token_string + +## API Errors + +All API calls will return http 200 and requested data (if applied). Otherwise, API will return http error code and specific error message in the http message body. + + :::ruby + def handle_api_error(error_message) + @errors ||= [] + begin + yield + rescue RestClient::Exception => re + if re.response.body.nil? or re.response.body.length == 0 + @errors << "#{error_message}: [#{re.http_code}] #{re.message}" + else + @errors << "#{error_message}: #{re.response.body}" + end + rescue Exception => e + @errors << "#{error_message}: #{e.message}" + end + end + + handle_api_error("Can't get license information") do + @license_info = JSON.parse( + RestClient.get( + "#{server}/rc/v1/system/license", + {'X-RhoConnect-API-TOKEN' => @api_token} + ).body + ) + end + +## System Resource - POST login + + :::ruby + POST /rc/v1/system/login + +Before you can use RhoConnect API you should login to the RhoConnect server and get API token: + + :::ruby + require 'rest_client' + require 'json' + + server = "http://localhost:9292" + login = "rhoadmin" + password = "" + + @api_token = RestClient.post("#{server}/rc/v1/system/login", { :login => login, :password => password }.to_json, :content_type => :json) + +## System Resource - GET license + + :::ruby + GET /rc/v1/system/license + +Returns license information of the currently used license + + :::ruby + license_info = RestClient.get( + "#{server}/rc/v1/system/license", + {'X-RhoConnect-API-TOKEN' => @api_token} + ).body + +## System Resource - POST reset + + :::ruby + POST /rc/v1/system/reset + +Reset the server: flush db and re-bootstrap server + + :::ruby + RestClient.post("#{server}/rc/v1/system/reset", + {}.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +## System Resource - GET appserver + + :::ruby + GET /rc/v1/system/appserver + +Returns the url of the plugin's backend from the RhoConnect server. + + :::ruby + adapter_url = RestClient.get( + "#{server}/rc/v1/system/appserver", + {'X-RhoConnect-API-TOKEN' => @api_token} + ).body + +## System Resource - POST appserver + + :::ruby + POST /rc/v1/system/appserver + +Saves the url of the plugin's backend to the RhoConnect server. + + :::ruby + RestClient.post( + "#{server}/rc/v1/system/appserver", + { + :adapter_url => url + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +## System Resource - GET stats + + :::ruby + GET /rc/v1/system/stats + +Retrieves stats for a given metric key: + + :::ruby + RestClient.get( + "#{server}/rc/v1/system/stats", + { + :params => {:metric => 'foo', :start => 0, :finish => -1}, + 'X-RhoConnect-API-TOKEN' => @api_token + } + ) + +Retrieves a list of metric keys matching a given pattern. This supports 'glob' or '*' style pattern matching. For example, all metric keys associated with 'Product' source adapter methods: + + :::ruby + RestClient.get( + "#{server}/rc/v1/system/stats", + { + :params => {:names => 'sources:*:Product'}, + 'X-RhoConnect-API-TOKEN' => @api_token + } + ) + +## Store Resource - GET doc + + :::ruby + GET /rc/v1/store/:doc + +Return content of a given document stored in Redis. + + :::ruby + res = RestClient.get( + "#{server}/rc/v1/store/", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## Store Resource - POST doc + + :::ruby + POST /rc/v1/store/:doc + +Sets the content of the specified server document. Data should be either a string or hash of hashes. +If `append` flag is set to `true` , the data is appended to the current doc (if it exists) instead of replacing it. + + :::ruby + RestClient.post( + "#{server}/rc/v1/store/", + { + :data => data, + :append => false + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +## User Resource - POST user + + :::ruby + POST /rc/v1/users + +Create a user in this RhoConnect application. + + :::ruby + RestClient.post("#{server}/rc/v1/users", + { + :attributes => { + :login => login, + :password => password + } + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +## User Resource - DELETE user_id + + :::ruby + DELETE /rc/v1/users/:user_id + +Delete User and all associated devices from the RhoConnect application. + + :::ruby + RestClient.delete( + "#{server}/rc/v1/users/", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ) + +## User Resource - PUT user_id + + :::ruby + PUT /rc/v1/users/:user_id + +Update attributes for a user on this RhoConnect application. + + :::ruby + RestClient.put( + "#{server}/rc/v1/users/", + { + :attributes => { + :a_user_specific_attribute => a_user_specific_attribute_value + } + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +## User Resource - GET users + + :::ruby + GET /rc/v1/users + +List users registered with this RhoConnect application. + + :::ruby + users = RestClient.get( + "#{server}/rc/v1/users", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## User Resource - GET user_id + + :::ruby + GET /rc/v1/users/:user_id + +Returns the information for the specified user. + + :::ruby + user_info = RestClient.get( + "#{server}/rc/v1/users/", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## User Resource - GET clients + + :::ruby + GET /rc/v1/users/:user_id/clients + +List clients (devices) associated with given user. + + :::ruby + clients = RestClient.get("#{server}/rc/v1/users//clients", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +Returns list of client ids. + +## User Resource - DELETE client_id + + :::ruby + DELETE /rc/v1/users/:user_id/clients/:client_id + +Deletes the specified client (device) for the given user. + + :::ruby + RestClient.delete( + "#{server}/rc/v1/users//clients/", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ) + +## User Resource - GET source_id docnames + + :::ruby + GET /rc/v1/users/:user_id/sources/:source_id/docnames + +Return list of document keys associated with given source and user. + +If `:user_id` set to '*', this call will return list of keys for 'shared' documents. + + :::ruby + docs = RestClient.get( + "#{server}/rc/v1/users//sources//docnames", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## User Resource - POST ping + + :::ruby + POST /rc/v1/users/ping + +Sends PUSH message to all devices of the specified user(s): + + :::ruby + # :message - message which will be used to display notification popup dialog on the device + # :badge - iphone specific badge + # :sound - name of the sound file to play upon receiving PUSH notification + # :vibrate - number of seconds to vibrate upon receiving PUSH notification + # :sources - list of data source names to be synced upon receiving PUSH notification + ping_params = { + :api_token => token, + :user_id => [array_of_users], + :sources => source_name, + :message => 'hello world', + :vibrate => 2000, + :sound => 'hello.mp3' + } + + RestClient.post( + "#{server}/rc/v1/users/ping", ping_params.to_json, + { :content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token } + ) + +## User Resource - GET source_id doc + + :::ruby + GET /rc/v1/users/:user_id/sources/:source_id/docs/:doc + +Return content of a given source document for the specified user. + + :::ruby + res = RestClient.get( + "#{server}/rc/v1/users//sources//docs/", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## User Resource - POST source_id doc + + :::ruby + POST /rc/v1/users/:user_id/sources/:source_id/docs/:doc + +Sets the content of the specified source document for the given user. Data should be either a string or hash of hashes. +If `append` flag is set to `true` , the data is appended to the current doc (if it exists) instead of replacing it. + + :::ruby + RestClient.post( + "#{server}/rc/v1/users//sources//docs/", + { + :data => data, + :append => false + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +## Read State - PUT user source_id + + :::ruby + PUT /rc/v1/readstate/users/:user_id/sources/:source_id + +Sets source poll interval to "current time plus x seconds". + + :::ruby + RestClient.put( + "#{server}/rc/v1/readstate/users//sources/", + { + :refresh_time => 100 + }.to_json, + { :content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token } + ) + +This will set the refresh time to 100 seconds from the current time. Calling `set_refresh_time` with no `:refresh_time` will trigger a refresh on the sync request for the source. + +## Source Controller - GET partition_type + + :::ruby + GET /rc/v1/sources/type/:partition_type + +Return list of source adapters for this RhoConnect application for the given partition type. +Partition type can be either `app` or `user`. + + :::ruby + sources = RestClient.get("#{server}/rc/v1/sources/type/", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## Source Controller - GET source_id + + :::ruby + GET /rc/v1/sources/:source_id + +Return attributes associated with a given source: + +* `name` - name of the data source +* `poll_interval` - query poll interval; defines how often RhoConnect will call source adapter to query for new data, set to -1 to disable polling, 0 to always poll +* `partition_type` - to share data across all users, set partition to :app; otherwise use `:user` partition (default) +* `sync_type` - set to `:bulk_only` to disable `:incremental` sync; regular sync is `:incremental` (default) +* `queue` - name of the queue for both query and create/update/delete (CUD) jobs (used if no specific queues not specified) +* `query_queue` - name of query queue +* `cud_queue` - name of CUD queue + +> Note: query or create/update/delete methods of the source adapter will be executed [asynchronously](async-jobs) if a queue name is defined. + + :::ruby + attributes = RestClient.get("#{server}/rc/v1/sources/", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## Source Controller - PUT source_id + + :::ruby + PUT /rc/v1/sources/:source_id + +Updates attributes associated with a given source: + +`poll_interval` - query poll interval; defines how often RhoConnect will call source adapter to query for new data, set to -1 to disable polling, 0 to always poll. + + :::ruby + RestClient.put("#{server}/rc/v1/sources/", + { + :user_name => user, + :data => {:poll_interval => 25} + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ).body + +## Client Resource - GET client_id + + :::ruby + GET /rc/v1/clients/:client_id + +Returns client (device) attributes, such as `device_type`, `device_pin`, `device_port`. These attributes are used by [RhoConnect push](push). + + :::ruby + client_attributes = RestClient.get( + "#{server}/rc/v1/clients/", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## Client Resource - GET source_id docnames + + :::ruby + GET /rc/v1/clients/:client_id/sources/:source_id/docnames + +Returns list of document keys associated with particular client for a given source. These documents are used by the server to sync data with the client. + + :::ruby + docs = RestClient.get( + "#{server}/rc/v1/clients/:client_id/sources/:source_id/docnames", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## Client Resource - GET source_id doc + + :::ruby + GET /rc/v1/clients/:client_id/sources/:source_id/docs/:doc + +Return content of a given source document for the specified client. + + :::ruby + res = RestClient.get( + "#{server}/rc/v1/clients//sources//docs/", + { + 'X-RhoConnect-API-TOKEN' => @api_token + } + ).body + +## Client Resource - POST source_id doc + + :::ruby + POST /rc/v1/clients/:client_id/sources/:source_id/docs/:doc + +Sets the content of the specified source document for the given client. Data should be either a string or hash of hashes. +If `append` flag is set to `true` , the data is appended to the current doc (if it exists) instead of replacing it. + + :::ruby + RestClient.post( + "#{server}/rc/v1/clients//sources//docs/", + { + :data => data, + :append => false + }.to_json, + { :content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token } + ) + +## Plugin source_name - POST push_objects + + :::ruby + POST /app/v1/:source_name/push_objects + +Push new objects or object updates to RhoConnect. These changes will be sent to the device the next time it synchronizes. + +> Note: you may use [ping](push) to notify client and trigger sync. + + :::ruby + # list of objects in the canonical hash of hashes structure + data = { + '5' => { + 'name' => 'iPhone' + } + } + RestClient.post( + "#{server}/app/v1//push_objects", + { + :user_id => user_id, + :objects => data + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +> Note: Normally, `push_objects` method will refresh the whole :md document in Redis. However, in case of large-size +documents, `push_objects` method can be optimized by invoking only the necessary updates. This can help reducing +the number of transactions with Redis. To force the optimization, user can use the `:rebuild_md => false` flag +in the `push_objects` parameters hash. + +## Plugin source_name - POST delete_objects + + :::ruby + POST /app/v1/:source_name/push_deletes + +Delete objects from RhoConnect. These objects will be deleted from the device the next time it synchronizes. + +> Note: You may use [ping](push) to notify client and trigger sync. + + :::ruby + # object_ids is an array of objects to be deleted + RestClient.post( + "#{server}/app/v1//push_deletes", + { + :user_id => user_id, + :objects => object_ids + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +> Note: Normally, `push_deletes` method will refresh the whole :md document in Redis. However, in case of large-size +documents, `push_deletes` method can be optimized by invoking only the necessary updates. This can help reducing +the number of transactions with Redis. To force the optimization, user can use the `:rebuild_md => false` flag +in the `push_deletes` parameters hash. + +## Plugin sourece_name - POST fast_insert + + :::ruby + POST /app/v1/:source_name/fast_insert + +Push new objects to RhoConnect. Changes are inserted into the Redis set without any checking for previous existence. +This way, the insert is very fast, but user must ensure that the object didn't exist before. No safeguards are implemented. +Use this method only when you can ensure the integrity of the data. + +> Note: you may use [ping](push) to notify client after the insert and trigger sync. + + :::ruby + # list of objects in the canonical hash of hashes structure + data = { + '5' => { + 'name' => 'iPhone' + } + } + RestClient.post( + "#{server}/app/v1//fast_insert", + { + :user_id => user_id, + :objects => data + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +## Plugin source_name - POST fast_update + + :::ruby + POST /app/v1/:source_name/fast_update + +Push object updates to RhoConnect. This method doesn't involve pulling the existing data out of Redis. Instead it required user to provide the previous state of the data. This way, this method allows for very fast updates (since it just removes the previous data from set and adds new ones). However, no data integrity checks are performed. Therefore, this method must be used only if user can ensure the integrity of the data (i.e. previous state must exist, otherwise it won't be properly deleted). Also, this method can be used to perform fast appends and deletes for any of the object's attributes (However, you shouldn't use this method to remove all of the attributes, `fast_delete` should be used instead.) + +> Note: you may use [ping](push) to notify client after the update and trigger sync. + + :::ruby + # list of objects in the canonical hash of hashes structure + # delete_data contains previous state of the object (to be deleted) + delete_data = { + '5' => { + 'name' => 'iPhone' + } + } + # data contains new state of the object + # to be inserted + data = { + '5' => { + 'name' => 'HTC' + } + } + RestClient.post( + "#{server}/app/v1//fast_update", + { + :user_id => user_id, + :delete_data => delete_data, + :data => data + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) + +## Plugin source_name - POST fast_delete + + :::ruby + POST /app/v1/:source_name/fast_delete + +Push object deletes to RhoConnect. This method doesn't involve pulling the existing data out of Redis and removing all of its attributes. Instead it requires the user to provide all of the object's data in the hash to be removed. This way, this method allows for very fast deletes (since it just removes the object's data from set). However, no data integrity checks are performed. Therefore, this method must be used only if user can ensure the integrity of the data (i.e. supply all of the object's data to be removed, otherwise some object's data will remain in Redis). + +> Note: you may use [ping](push) to notify client after the delete and trigger sync. + + :::ruby + # list of objects in the canonical hash of hashes structure + # data contains all of the object's data (to be deleted) + data = { + '5' => { + 'name' => 'iPhone' + } + } + RestClient.post( + "#{server}/app/v1//fast_delete", + { + :user_id => user_id, + :data => data + }.to_json, + {:content_type => :json, + 'X-RhoConnect-API-TOKEN' => @api_token} + ) \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/rhoconnect-calculator.md b/docs/en/5.5/rhoconnect/rhoconnect-calculator.md new file mode 100644 index 00000000..ce0325e3 --- /dev/null +++ b/docs/en/5.5/rhoconnect/rhoconnect-calculator.md @@ -0,0 +1,237 @@ + + + +RhoConnect Calculator +========== +The RhoConnect Calculator helps you estimate the number of processor cores and redis server RAM required to deploy a RhoConnect Production environment. + +1 core equals 1 processor (at 2 GHz) running two thin processes. + + +
                                                                              + + + + + + + +
                                                                              + +syncs per day +
                                                                              +
                                                                              + + + +
                                                                              +
                                                                              + +
                                                                              + +**NOTE: High Availability (HA) is not included into these numbers. So if your environment must provide HA, you will need to include enough extra storage and processor capacity in case of hardware failure.** + +### Calculator Fields +
                                                                                +
                                                                              • Number of Objects - The number of objects across all of your models. If you have 10 models with 10 objects for each model, you would enter 100.
                                                                              • +
                                                                              • Number of Attributes per Object - The average number of attributes per object. E.g. if you have 2 objects, 1 with 10 attributes and 1 with 12 attributes, you would enter 11.
                                                                              • +
                                                                              • Number of devices - The total number of devices that will be using RhoConnect.
                                                                              • +
                                                                              • Sync Frequency - The average sync frequency per device. E.g if you have 2 devices where one syncs 10 times per day and one sync 12 times per day, you would enter 11.
                                                                              • +
                                                                              + +### Result +
                                                                                +
                                                                              • Number of Cores - The number of processor cores required (could be distributed across N number of servers).
                                                                              • +
                                                                              • Redis RAM – RAM required for the master Redis instance. Currently only one master Redis instance can be defined. A typical deployment involves one master Redis instance (with no disk persistence) and N number of read-slaves (with persistence). Slave disk persistence would need at least 2X disk capacity where X is the master instance RAM requirement.
                                                                              • +
                                                                              + + + + + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + + +
                                                                              +
                                                                              +
                                                                              + + +
                                                                              +
                                                                              + +
                                                                              +
                                                                              +
                                                                              +
                                                                              \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/rhoconnect-redis-stack.md b/docs/en/5.5/rhoconnect/rhoconnect-redis-stack.md new file mode 100644 index 00000000..3afd0471 --- /dev/null +++ b/docs/en/5.5/rhoconnect/rhoconnect-redis-stack.md @@ -0,0 +1,426 @@ +# Deploying RhoConnect with High Availability on Amazon Web Services + +This tutorial will guide you through setting up a Redis stack and a RhoConnect application stack in the Amazon Web Service (AWS) cloud. + +The RhoConnect application stack is scalable; it uses load balancing to automatically distribute and balance the incoming application traffic among all the instances you are running. You will set the maximum number of instances that the load balancer can create for your RhoConnect application. + +## Logging onto the Amazon Web Service + +Go to the [Amazon Web Service (AWS) Console](http://aws.amazon.com/console/) and click on the Sign in to the AWS Console button. You can sign into an existing AWS account, or create a new one. + +AWS login button + +Or you can open the URL for your account directly if you have the account number: + + :::term + https://.signin.aws.amazon.com/console + +Enter your User Name and Password for your AWS account, then click the Sign in button. + +AWS login page + +## Creating a Custom RhoConnect Image + +In the AWS Management Console, change the Region to US West (N. California). + +**NOTE:** The stacks created in this document only work in the N. California region. + +Cloud Formation page N California region + +We provide a few public preconfigured images that contains a blank RhoConnect app for `Us West N. California` region: + + * `ami-cbc59e8e` (RhoConnect-3.1.2 with Nginx and phusion passenger) + * `ami-0dfca748` (RhoConnect-3.2.0 with Nginx and cluster of thin servers) + +### Launching an Instance + +To create your own RhoConnect Image, launch an EC2 Image: + +Click the EC2 tab, click EC2 Dashboard, then click the Launch Instance button. + +Launch Instance button + +Click the Launch Classic Wizard radio button. Click Continue. + +create new instance classic wizard + +### Requesting the Instance + +In the Choose an AMI section, click the Community AMIs tab. +Then paste in the AMI ID, i. e. `ami-cbc59e8e`. When the preconfigured RhoConnect AMI appears, click Select. + +request instances - choose AMI + +In the Instance Details section, select the Instance Type (such as Large). + +request instances - instance details + +In the Instance Details section, Advanced Instance Options screen, change nothing. Click Continue. + +In the Instance Details section, Add Tags screen, enter a name for your custom RhoConnect EC2 instance in the Value Column of the Name key, then click Continue. + +request instances - add tags + +In the Create Key Pair section, select your existing key pair or create a new keypair. + +request instances - key pair + +### Requesting the Instance - Configuring the Firewall + +request instances - configure firewall + +In the Configure Firewall section, click the Create New Security Group radio button. + +Click the Add Rule button to add each port. + + * Add port 22 for SSH. + * Add port 80 for HTTP. + * Add port 6379 for redis. + +**NOTE: You may use a preexisting security group if it has ports 22, 80, and 6379 open. ** + +Enter a firewall name and a group description, then click Continue. + +request instances - review + +Make sure all the instance information is correct as shown on the Review page and then click Launch. + +In the window titled "Launch Instance Wizard", click Close and wait for your instance to be Running. + +### Customizing the Instance + +instances - instances + +In the EC2 tab, click on Instances. + +For Viewing, select Running Instances. Select your newly created RhoConnect instance and scroll down to see Private DNS in the lower section of the My Instances screen. + +running instances - public dns + +You will need: + + * your keypair (the .pem file AWS gives you when the keypair is created) + * the public DNS name of the Instance, which you will see as the public DNS name in the running instance. For Example: `ec2-184-72-16-39.us-west-1.compute.amazonaws.com`. + * the username: `ec2-user` + +From the command line, use ssh to login to the running instance, using the keypair, DNS name, and user name. For example: + + :::term + $ ssh -i ~/.ssh/devkey.pem ec2-user@ec2-50-18-229-26.us-west-1.compute.amazonaws.com + +Replace the blank 'rhoapp' application in the /opt/nginx/html folder with your app, and set its owner as 'nginx' user. + + :::term + $ cd /opt/nginx/html + # ... copy your application here under name 'rhoapp' + $ sudo chown -R nginx:nginx rhoapp + +You can test the application. + + :::term + $ sudo /etc/init.d/redis start + $ sudo /etc/init.d/nginx start + +**NOTE: If your instance based on `ami-0dfca748` (RhoConnect-3.2.0) image, then you need to do one more step:** + + :::term + $ sudo /etc/init.d/thin start + +If everything is configured properly, then you can login to the RhoConnect web console in your browser by using the instance's public DNS name as the URL in your browser. When you are done, you can stop the application. + + :::term + $ sudo /etc/init.d/nginx stop + $ sudo /etc/init.d/redis stop + +**NOTE: Do not forget also stop cluster of thin servers if your instance based on `ami-0dfca748` (RhoConnect-3.2.0):** + + :::term + $ sudo /etc/init.d/thin stop + +## Create the Image + +Create Image popup + +In the EC2 tab, right-click the RhoConnect instance and select Create Image (EBS AMI). + +Create Image + +In the Create Image window, enter the image name and description for your custom image. Then click Create This Image. + +Create Image request + +In the Create Image window showing that the request is received, click on "View pending image: ami-XXXXXXXX to go to your Amazon Machine Image. + +amazon machine image + +Copy the AMI number; you will use it when you create the scaleable RhoConnect stack. + +## Creating the Scalable RhoConnect Stack + +Click the Cloud Formation tab. + +Cloud Formation page + +Ensure that the Region selected is US West (N. California) and Click the Create New Stack button. + +Cloud Formation page new stack button + +### Create Stack - Select Template + +In the Select Template section, you must select the template file for your redis stack. This is the template to run the AMI image with the Redis server. + +Create Stack Select Template window + +First, enter the name that you want for your stack into the Stack Name field. + +Now get the template by either providing the URL for the template file, or by uploading the template file. + +#### Providing the URL for the Template File + +Click the Provide a Template URL radio button. + +If your custom image based on `ami-cbc59e8e`(RhoConnect-3.1.2) image, then copy the following URL and paste it into the text field below the Provide a Template URL radio button: + +`https://s3-us-west-1.amazonaws.com/rhoconnect-ca-deploy/rhoconnect_template.txt` + +If your custom image based on `ami-0dfca748` (RhoConnect-3.2.0), then use this URL: + + `https://s3-us-west-1.amazonaws.com/rhoconnect-ca-deploy/rhoconnect_template-3.2.txt` + +#### Uploading the Template File + +Click the Upload a Template File radio button. + +In another browser window, go to [https://s3-us-west-1.amazonaws.com/rhoconnect-ca-deploy/rhoconnect_template.txt](https://s3-us-west-1.amazonaws.com/rhoconnect-ca-deploy/rhoconnect_template.txt) +if your custom image based on `ami-cbc59e8e` (RhoConnect-3.1.2). + +If your custom image based on `ami-0dfca748` (RhoConnect-3.2.0), then to go +[https://s3-us-west-1.amazonaws.com/rhoconnect-ca-deploy/rhoconnect_template-3.2.txt](https://s3-us-west-1.amazonaws.com/rhoconnect-ca-deploy/rhoconnect_template-3.2.txt). + +Save that text file to your computer. + +Click the Choose File button, and navigate to and select your template file. + +Click Continue. + +### Create Stack - Specify Parameters + +Create Stack Specify Parameters window + +In the Create Stack: Specify Parameters window: + + * Enter the AMI image number that you saved earlier. + * Enter the maximum number of RhoConnect application servers that you want to run in your stack. Default = 2. + * Enter the name for your existing EC2 KeyPair to enable SSH access to the stack instances. + +Click Continue. + +### Create Stack - Review + +Create Stack Review window + +Click Continue to see a window entitled \"Create Stack\" showing that the stack is being created. + +Create Stack being created window + +Click Close. + +## Checking the Status + +In the AWS Management Console, Cloud Formation tab, click the checkbox for your stack. To see the progress of the creation of your stack, click the Refresh button; the status should become CREATE_COMPLETE soon. + +To see the progress of the components in your stack, you can click the Events tab. You can click the refresh button to see the progress. + +AWS Management CREATE_COMPLETE window + +## Using the RhoConnect Application URL + +In the AWS Management Console, Cloud Formation tab, click the Outputs tab. You will see a list of the Stack Outputs. + +AWS Management Stack Outputs window + +At the top of the output list is the URL of the RhoConnect application. You can click on it to see the RhoConnect Console for the running RhoConnect server. + +RhoConnect Console + +To use this scaleable RhoConnect server in your Rhodes application, copy the URL for the RhoConnect application into the rhoconfig.txt file in your Rhodes application as the syncserver variable. For example: + + :::term + syncserver = http://rhoconnec-RhoLoadB-OX64XR1IKNT2-1364705573.us-west-1.elb.amazonaws.com + +## Deleting the Stack + +You are charged for the stack that you have created, by the hour. When you no longer want to use the stack, you can delete it by right-clicking on the stack name in the AWS Management Console, Cloud Formation tab, and clicking Delete Stack. + +Delete Stack + +## High Availability/Failover for Redis server + +The described architecture has a weak spot: a single point of failure (SPOF). If the Redis server is down or stops responding, then the entire Rhoconnect stack stops functioning. To address this issue, we need to implement failover — the continuation of a service after the failure of one or more of its components. Redis provides a very simple solution to +configure master-slave replication that allows slave Redis servers to be exact copies of master servers. +So if the master server goes down, we can issue a `SLAVEOF NO ONE` command to the slave and then switch RhoConnect apps to use the slave that is now the master. + +The following is a one possible scenario of how it might be done on the Amazon cloud. + +Redis High Availability proposal: + +* RhoConnect applications do not send queries directly to the Redis server, but communicate with the Redis Elastic Load Balancer (RELB). +* RELB has 2 monitor servers, both running Haproxy and Monit services. RELB responsibility is to do a health check of monitor servers and to distribute incoming traffic to TCP proxy service. +* Each monitor machine has a TCP proxy which relays its traffic to the master redis server. +* Monit service role is to detect failure of redis servers and start recovery process. +* Monit checks redises on a regular basis. It runs a failover script `/home/ubuntu/failover` if there is an failure to get a valid response upon performing a PING command three times in a row. +* Failover script does automatic slave -> master promotion in the case of master failure, and reconfigures Haproxy service to relay traffic to the new master redis. It spins up a new Redis EC2 instance and sets it as slave on the new master. +* The failover script uses AWS `simpleBD` service to store current redis servers configuration (master/slave/backup). So, +if another instance of monitor server detects failure and calls the failover script, it will know the current status of the redis servers +and will wait until the recovery process that was initiated by another Monit service is over. Finally, the failover script reconfigures and restarts the Monit service to track a new pair of master/slave redis servers. +* 1 Redis master +* 1 Redis slave + +The URL for the CloudFormation template that implements the described proposal is available here +[https://s3-us-west-1.amazonaws.com/rhoconnect-ca-deploy/rhoconnect-ha.txt](https://s3-us-west-1.amazonaws.com/rhoconnect-ca-deploy/rhoconnect-ha.txt) +and can be used for evaluation purposes. + +The template will create a sample scalable rhoconnect stack with 2 elastic load balancers and 5 EC2 instances. + +* RhoConnect Load Balancer +* 1 EC2 instance of RhoConnect application +* Redis Load Balancer +* 2 EC2 instances of monitor servers (Haproxy/Monit) +* 2 EC2 instances of redis servers (master/slave) + +## Setting up Redis Servers Horizontal Scaling + +Under heavy load single Redis server might be a bottleneck in RhoConnect stack performance due to high network traffic, +large memory footprints of stored data in server instance. To address redis server performance issues RhoConnect (>= v4.0.0) + supports multiple Redis instances per app, and evenly distributing load across available Redis server instances. + +### Configure RhoConnect app to support multiple Redis instances + +Edit your app `settings/settings.yml` file and replace :redis one liner by array of redis servers you are going to use: + + :::yaml + # ... + :production: + :licensefile: settings/license.key + :syncserver: http://localhost:9292/api/application/ + :push_server: http://appname:secret@localhost:8675/ + # Two or more redis servers per app + :redis: + - localhost:6379 + - localhost:6380 + - localhost:6381 + - localhost:6382 + # ... + + +### Create a custom Amazon Image with multiple Redis instances + +The following recommendations are based on Ubuntu Amazon image, where [RhoConnect Redis](http://docs.rhomobile.com/rhoconnect/deploying#deploying-rhoconnect-redis-and-push-packages-on-linux-servers) package installed and you wanted host 4 redis instances on ports 6379, 6380, 6381, and 6382 respectively. + +Rename `/opt/rhoconnect/etc/redis.conf` configuration file to `/opt/rhoconnect/etc/redis-6379.conf` and make sure that it has settings for the 1st instance: + + :::text + ... + daemonize yes + pidfile /var/run/redis/redis6379.pid + port 6379 + + # DO NOT FORGET comment persistence cmds + # save ... + ... + +For other servers create `/opt/rhoconnect/etc/redis-6380.conf`, `/opt/rhoconnect/etc/redis-6381.conf` and `/opt/rhoconnect/etc/redis-6382.conf` + files and do similar setting for corresponding redis instances: + + :::text + # File /opt/rhoconnect/etc/redis-6380.conf + ... + daemonize yes + pidfile /var/run/redis/redis6380.pid + port 6380 + # DO NOT FORGET comment persistence cmds + ... + + # File /opt/rhoconnect/etc/redis-6381.conf + ... + daemonize yes + pidfile /var/run/redis/redis6381.pid + port 6381 + # DO NOT FORGET comment persistence cmds + ... + + # File /opt/rhoconnect/etc/redis-6382.conf + ... + daemonize yes + pidfile /var/run/redis/redis6382.pid + port 6382 + # DO NOT FORGET comment persistence cmds + ... + + +Delete `/etc/init/rhoconnect-redis.conf` file if it's there. +Create upstart script `/etc/init/rhoconnect-redis-6379.conf` for the 1-st instance: + + :::text + # /etc/init/rhoconnect-redis-6379.conf + + description "Redis Datastore Server" + # Redis is a key value in memory persistent datastore + + start on (local-filesystems and runlevel [2345]) + stop on runlevel [016] + expect fork + respawn + + pre-start script + mkdir -p /var/run/redis + chown redis:redis /var/run/redis + end script + + exec start-stop-daemon --start --chuid redis:redis --pidfile /var/run/redis/redis6379.pid --umask 007 \ + --exec /opt/rhoconnect/bin/redis-server -- /opt/rhoconnect/etc/redis-6379.conf + +Define upstart scripts `/etc/init/rhoconnect-redis-6380.conf`, `/etc/init/rhoconnect-redis-6381.conf`, and `/etc/init/rhoconnect-redis-6382.conf` for other instances: + + :::text + # /etc/init/rhoconnect-redis-6380.conf + # ... + exec start-stop-daemon --start --chuid redis:redis --pidfile /var/run/redis/redis6380.pid --umask 007 \ + --exec /opt/rhoconnect/bin/redis-server -- /opt/rhoconnect/etc/redis-6380.conf + + # /etc/init/rhoconnect-redis-6381.conf + # ... + exec start-stop-daemon --start --chuid redis:redis --pidfile /var/run/redis/redis6381.pid --umask 007 \ + --exec /opt/rhoconnect/bin/redis-server -- /opt/rhoconnect/etc/redis-6381.conf + + # /etc/init/rhoconnect-redis-6382.conf + # ... + exec start-stop-daemon --start --chuid redis:redis --pidfile /var/run/redis/redis6382.pid --umask 007 \ + --exec /opt/rhoconnect/bin/redis-server -- /opt/rhoconnect/etc/redis-6382.conf + + +We provide a public preconfigured image with above settings for Us `West N. California` region: + +* `ami-94b496d1` (Redis-Server-2.6.7 with 4 instances on ports 6379, 6380, 6381, and 6382) + +### Amazon CloudFormation Template File + +This Amazon CloudFormation [template file](https://s3.amazonaws.com/rhoconnect-deploy/rhoconnect-template-2-redises-4-instances.txt) + shows how 2 redis servers with 4 instances per server might be used for a typical rhoconncect application. + + + + + + + + + + + + + + + + + diff --git a/docs/en/5.5/rhoconnect/settings.md b/docs/en/5.5/rhoconnect/settings.md new file mode 100644 index 00000000..faabed2a --- /dev/null +++ b/docs/en/5.5/rhoconnect/settings.md @@ -0,0 +1,62 @@ +# RhoConnect settings +All RhoConnect application and source settings located in the `settings/settings.yml` file. +There are two main categories: application environment settings and source settings. + +## Application settings +Application-wide settings are specified per deployment environment (`:test`, `:development`, `:production`). +Each of the environment categories must have the following entries: + + :::yaml + :syncserver: + :redis: + :licensefile: + +`:licensefile`: application's license file. + +`:redis`: Redis url. Can be specified as an Array of URLs. In that case, RhoConnect will use several Redis servers (this can be used in case of high-volume data) + +`:syncserver`: application's base url. + +In addition, you can specify the following settings: + + :::yaml + :connection_pool_size: + :connection_pool_timeout: + :redis_timeout: + :poll_interval_default: + :bulk_sync_poll_interval: + :gcm_api_key: your_gcm_api_key_here + :node_channel_timeout: + +`:connection_pool_size`: By default, RhoConnect maintains multiple concurrent connections to Redis organized in Connection Pool. This setting allows you to specify the size of the pool. By default, RhoConnect starts with five (5) Redis connections. + +`:connection_pool_timeout`: The timeout value for the Redis Connection Pool, in seconds. Specifies how much time a request will wait for an available Redis connection. Default is 30 seconds. + +`:redis_timeout:` - timeout setting for Redis commands. Default is 30 seconds. + +`:poll_interval_default`: default sync poll interval setting for source adapters, in seconds. This setting is used as a default if source doesn't specify its own value. Also, it is applied to dynamic adapters as a default sync poll interval. + +`:bulk_sync_poll_interval`: poll interval setting for bulk data sync, in seconds. + +`:gcm_api_key`: The [API key for Google Cloud Messaging](push-client-setup-android#setting-up-android-google-cloud-messaging). + +`:node_channel_timeout`: The timeout, in seconds, for requests made from ruby framework to node.js. The default value is __30 seconds__ and is usually fine but it can be modified using this setting if the network requires more time to respond. + +## Source settings + +All source-specific settings are specified under the corresponding source name entry in the `:sources` category. +Typical source settings include: + + :::yaml + :poll_interval: + :force_default: + :partition_type: + :priority: + +`:poll_interval`: source's sync poll interval in seconds. + +`:force_default`: true or false. If specified, this setting forces use of the default application poll interval even if source has its own setting. + +`:partition_type`: app or user. default partition type for the source. + +`:priority:` A priority number used to determine the order in which the models are processed and synchronized. This is useful when there are a set of linked together sources and the client needs to know in which order to process them. Priority starts from lower value 1. If priorities are not specified, then there is no guarantee that models will be listed and processed in natural order. \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/source-adapters-intro.md b/docs/en/5.5/rhoconnect/source-adapters-intro.md new file mode 100644 index 00000000..cf5765ec --- /dev/null +++ b/docs/en/5.5/rhoconnect/source-adapters-intro.md @@ -0,0 +1,28 @@ +RhoConnect Source Adapters +=== + +## What is RhoConnect Source Adapter? + +A RhoConnect Source Adapter is a software entity which encapsulates: + +* Source's business logic implementation (via a Model) +* Source's run-time management and HTTP route handling (via a Controller) + +## Source Adapter Controller + +From a web developer's point of view - each RhoConnect application is a collection of unique HTTP route handlers grouped logically into a Source Adapter Controller. +Each Source Adapter Controller defines a serviceable end point relative to the root of the application and represents itself as a stand-alone [Sinatra](http://www.sinatrarb.com/) app. +As a Sinatra app - Source Adapter Controller defines the available routes and handles the incoming requests. +Typically, you will just re-use the default implementation of the Controller. However, in some cases, you may customize it by adding your own routes or altering the default route's behaviour. In this sense, Controller is still a Sinatra app - and you can re-use any of the available Sinatra tools and techniques. + +## Source Adapter Model + +By default, each RhoConnect Source Adapter Controller defines SYNC routes to be called by the RhoConnect client's application. +At run-time, the Source Adapter controller prepares the context of the request (for example, parses and prepares the query parameters, etc.), then instantiates the corresponding RhoConnect Source Adapter Model and calls its methods. + +As a developer - you will need to implement the business logic inside of the RhoConnect Source Adapter Model class. +Connecting to a backend service with RhoConnect means that you will be required to write a small amount of code for the query, create, update and delete operations of your particular enterprise backend. In this way - the RhoConnect Source Adapter model is a collection of Ruby code to access and process the data from your enterprise backend. + +## Source Adapter API + +Starting with RhoConnect 4, Source Adapters can be developed in Ruby or JavaScript. The next sections describe the Source Adapter API available for each of these languages. \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/source-adapters-js.md b/docs/en/5.5/rhoconnect/source-adapters-js.md new file mode 100644 index 00000000..04d3134c --- /dev/null +++ b/docs/en/5.5/rhoconnect/source-adapters-js.md @@ -0,0 +1,418 @@ +RhoConnect Source Adapters (JavaScript) +=== + +## Generating the Source Adapter from the Command Line + +To generate a JavaScript source adapter for your RhoConnect application, you can run the `rhoconnect source --js` command within your application directory. + + :::term + $ rhoconnect source --help + Usage: rhoconnect source [options] [args] + + Generates a new source adapter (Controller/Model pair). + Required: + name - source name (i.e. product) + + + Options specific for this generator: + --js generate JavaScript code + + General options: + -p, --pretend Run, but do not make any changes. + -f, --force Overwrite files that already exist. + -s, --skip Skip files that already exist. + -d, --delete Delete files that have previously been generated with this generator. + --no-color Don't colorize the output + -h, --help Show this message + --debug Do not catch errors + + +For the storeserver application example, within the storeserver directory, run: + + :::term + $ rhoconnect source product --js + Generating with source generator: + [ADDED] models/js/product.js + [ADDED] controllers/js/product_controller.js + + +## Understanding the Generated Controller File + +The generated source adapter's controller file (in this case, `controllers/product_controller.js`) is similar to the code listing below. +Its purpose is to define the RhoConnect application HTTP end point and to register the corresponding SYNC routes. + + :::javascript + var app = require("ballroom"); + var helpers = require("rhoconnect_helpers"); + + app.controllerName("Product"); + app.registerHandler("sync"); + + // Add your custom routes here + +## Understanding the Generated Model File + +The generated source adapter's model file (in this case, `models/product.js`) is similar to the code listing below: + + :::javascript + var rc = require('rhoconnect_helpers'); + + var Product = function(){ + + this.login = function(resp){ + // TODO: Login to your data source here if necessary + resp.send(true); + }; + + this.query = function(resp){ + var result = {}; + // TODO: Query your backend data source and assign the records + // to a nested hash structure. Then return your result. + // For example: + // + // { + // "1": {"name": "Acme", "industry": "Electronics"}, + // "2": {"name": "Best", "industry": "Software"} + // } + resp.send(result); + }; + + this.create = function(resp){ + // TODO: Create a new record in your backend data source. Then + // return the result. + resp.send('someId'); + }; + + this.update = function(resp){ + // TODO: Update an existing record in your backend data source. + // Then return the result. + resp.send(true); + }; + + this.del = function(resp){ + // TODO: Delete an existing record in your backend data source + // if applicable. Be sure to have a hash key and value for + // "object" and return the result. + resp.send(true); + }; + + this.logoff = function(resp){ + // TODO: Logout from the data source if necessary. + resp.send(true); + }; + + this.storeBlob = function(resp){ + // TODO: Handle post requests for blobs here. + // Reference the blob object's path with resp.params.path. + new rc.Exception( + resp, "Please provide some code to handle blobs if you are using them." + ); + }; + }; + + module.exports = new Product(); + +In this model you will need to implement the functions necessary for the create, query, update and delete sync operations. Optionally you may implement functions for login, logoff and storeBlob (if your application uses blobs). + +## Source Adapter API + +### Source Adapter Controller API + +You can use the following methods and techniques inside of your source adapter controller. + +* [controllerName](../rhoconnectapi/source-adapter-controller-api-js#controllernamename) - Name of the source adapter controller. +* [registerHandler](../rhoconnectapi/source-adapter-controller-api-js#registerhandlername) - Register a RhoConnect handler for the controller. +* [get](../rhoconnectapi/source-adapter-controller-api-js#getroute-options-callback) - Define a GET route. +* [post](../rhoconnectapi/source-adapter-controller-api-js#postroute-options-callback) - Define a POST route. +* [put](../rhoconnectapi/source-adapter-controller-api-js#putroute-options-callback) - Define a PUT route. +* [del](../rhoconnectapi/source-adapter-controller-api-js#delroute-options-callback) - Define a DELETE route. +* [currentUser](../rhoconnectapi/source-adapter-model-api-js#currentuser) - Returns the current user who called the adapter's model. +* [loadModel](http://localhost:9393/rhoconnectapi/source-adapter-controller-api-js#loadmodelname) - Returns the current model instance for this controller. + +### Source Adapter Model API + +You can write the following methods for your source adapter model. These methods will be called by the controller at run-time and allow your source adapter model to interact with your backend service. + +* [login](../rhoconnectapi/source-adapter-model-api-js#login) - Login to your backend service. +* [logoff](../rhoconnectapi/source-adapter-model-api-js#logoff) - Logoff from your backend service. +* [query](../rhoconnectapi/source-adapter-model-api-js#query) - Query your backend service and build a hash of hashes. +* [create](../rhoconnectapi/source-adapter-model-api-js#create) - Create a new record in the backend. +* [update](../rhoconnectapi/source-adapter-model-api-js#update) - Update an existing record in the backend. +* [del](../rhoconnectapi/source-adapter-model-api-js#del) - Delete an existing record in the backend. +* [stashResult](../rhoconnectapi/source-adapter-model-api-js#stashresultresp) - Saves the current state of the result to redis and sets it `undefined`. +* [getData](../rhoconnectapi/source-adapter-model-api-js#getdataresp-callback) - Get the model document data from Store. +* [currentUser](../rhoconnectapi/source-adapter-model-api-js#currentuser) - Returns the current user who called the adapter's model. +* [storeBlob](../rhoconnectapi/source-adapter-model-api-js#storeblob) - Save the incoming blob data into permanent storage for the future processing. +* [partitionName](../rhoconnectapi/source-adapter-model-api-js#partitionname) - Provide a custom user partition for a model. + +### Request API +The [request object](../rhoconnectapi/source-adapter-request-api-js) contains information about the HTTP request the app is receiving. + +* [params](../rhoconnectapi/source-adapter-request-api-js#params) - Access in the incoming request parameters (i.e. from the HTTP query string). +* [header](../rhoconnectapi/source-adapter-request-api-js#header) - HTTP request headers. +* [model](../rhoconnectapi/source-adapter-request-api-js#model) - The corresponding model name of the request. + +### Response API +The [response](../rhoconnectapi/source-adapter-response-api-js) is used to pass application control and return the `result` hash to RhoConnect. + +* [params](../rhoconnectapi/source-adapter-response-api-js#params) - Access in the incoming request parameters (i.e. from the HTTP query string). +* [header](../rhoconnectapi/source-adapter-response-api-js#header) - HTTP request headers. +* [send](../rhoconnectapi/source-adapter-response-api-js#sendvalue) - Return program control (most controller and model methods will need to do this). +* [exception](../rhoconnectapi/source-adapter-response-api-js#exception) - Holds the exception for the request (if one is raised). +* [currentUser](../rhoconnectapi/source-adapter-model-api-js#currentuser) - Returns the current user who called the adapter's model. + +## Store API +RhoConnect provides a simple [redis interface](../rhoconnectapi/source-adapter-store-api-js) for saving/retrieving arbitrary data. This is useful if you want to save data in your application to be used later (i.e. in an async job or a subsequent source adapter execution). + +* [getValue](../rhoconnectapi/source-adapter-store-api-js#getvaluerespcallback) - Retrieve a simple value from redis. +* [putValue](../rhoconnectapi/source-adapter-store-api-js#putvaluerespcallback) - Add a simple value to redis. +* [getData](../rhoconnectapi/source-adapter-store-api-js#getdatarespcallback) - Retrieve an array or hash from redis. +* [putData](../rhoconnectapi/source-adapter-store-api-js#putdatarespcallback) - Add an array or hash to redis. + +## Exception API +Use the following exception types in your JavaScript application to handle any error conditions. Don't worry, if your application throws an uncaught exception, the base `RhoConnect::Model::Exception` will automatically be used. + +* [Exception](../rhoconnectapi/source-adapter-exception-api-js#exceptionresponse-message) - Raise a `RhoConnect::Model::Exception`. +* [LoginException](../rhoconnectapi/source-adapter-exception-api-js#loginexceptionresponse-message) - Raise a `RhoConnect::Model::LoginException`. +* [LogoffException](../rhoconnectapi/source-adapter-exception-api-js#logoffexceptionresponse-message) - Raise a `RhoConnect::Model::LogoffException`. +* [ServerTimeoutException](../rhoconnectapi/source-adapter-exception-api-js#servertimeoutexceptionresponse-message) - Raise a `RhoConnect::Model::ServerTimeoutException`. +* [ServerErrorException](../rhoconnectapi/source-adapter-exception-api-js#servererrorexceptionresponse-message) - Raise a `RhoConnect::Model::ServerErrorException`. +* [ObjectConflictErrorException](../rhoconnectapi/source-adapter-exception-api-js#objectconflicterrorexceptionresponse-message) - Raise a `RhoConnect::Model::ObjectConflictErrorException`. + + +## Sample Model +Here's a complete example of how the completed [product model might look](https://gist.github.com/larsburgess/87753882f3a4a366b48b): + + :::javascript + var http = require('http'); + var host = 'rhostore.herokuapp.com'; + + var Product = function(){ + + this.login = function(resp){ + resp.send(true); + }; + + this.query = function(resp){ + var result = {}; + var str = ''; + + http.request('http://' + host + '/products.json', function(res){ + res.on('data', function(chunk){ + str += chunk; + }); + res.on('end', function(){ + var data = JSON.parse(str); + for(var i in data){ + var item = data[i]; + result[item.product.id.toString()] = item.product; + } + resp.send(result); + }); + }).end(); + }; + + this.create = function(resp){ + var postData = JSON.stringify({ 'product': resp.params.create_object }); + var str = ''; + var options = { + host: host, + path: '/products.json', + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': postData.length + } + }; + var req = http.request(options, function(res){ + res.on('data', function(chunk){ + str += chunk; + }); + res.on('end', function(){ + var data = JSON.parse(str); + resp.send(data.product.id.toString()); + }); + }); + req.write(postData); + req.end(); + }; + + this.update = function(resp){ + var objId = resp.params.update_object.id; + var putData = JSON.stringify({ "product": resp.params.update_object }); + // Remove the id from the hash, we don't need it. + delete putData.id; + var options = { + host: host, + path: '/products/' + objId + '.json', + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': putData.length + } + }; + var req = http.request(options, function(res){ + res.on('data', function(){}); + res.on('end', function(){ + resp.send(true); + }); + res.on('error', function(){ + resp.send(false); + }); + }); + req.write(putData); + req.end(); + }; + + this.del = function(resp){ + var objId = resp.params.delete_object.id; + var options = { + host: host, + path: '/products/' + objId + '.json', + method: 'DELETE', + headers: { 'Content-Type': 'application/json' } + }; + var req = http.request(options, function(res){ + res.on('data', function(){}); + res.on('end', function(){ + resp.send(true); + }); + res.on('error', function(){ + resp.send(false); + }); + }); + req.end(); + }; + + this.logoff = function(resp){ + resp.send(true); + }; + + this.storeBlob = function(resp){ + // TODO: Handle post requests for blobs here. + // Reference the blob object's path with resp.params.path. + new rc.Exception( + resp, "Please provide some code to handle blobs if you are using them." + ); + }; + }; + + module.exports = new Product(); + +## A RhoConnect Query + +If you're doing a read-only non-authenticated source adapter, you can just write one method, query, to retrieve records as we describe here. The following is a sample query method to interact with a simple product catalog (available at http://rhostore.herokuapp.com) that exposes a REST interface. Note that RhoConnect can work with any protocol. This example shows JSON over HTTP with a REST interface, since that is common. + +For a more complete example of rewriting the source adapter methods (such as create, update, and delete), refer to the [source adapter example](source-adapters#sample-adapter) above. + +Our sample web service for returning all products in the catalog (http://rhostore.herokuapp.com/products.json) returns data like this: + + :::json + [ + { + "product": { + "name": "iPhone", + "brand": "Apple", + "updated_at": "2010-05-11T02:04:57Z", + "price": "$299.99", + "quantity": "5", + "id": 649, + "sku": "1234", + "created_at": "2010-05-11T02:04:57Z" + } + }, + { + "product": { + "name": "Accord", + "brand": "Honda", + "updated_at": "2010-05-13T22:24:48Z", + "price": "$6000", + "quantity": "", + "id": 648, + "sku": "123", + "created_at": "2010-05-11T02:04:53Z" + } + } + ] + +The JavaScript code for parsing that data, `models/js/product.js`, is listed below. JSON is part of node.js by default so there is no need to explicitly include it. + +You can edit `models/js/product.js` within RhoStudio, or you can navigate to it within your RhoConnect application folder and edit it with a text editor. + +Fill in the query method: + + :::javascript + this.query = function(resp){ + var result = {}; + var str = ''; + + http:request('http://' + host + '/products.json', function(res){ + res.on('data', function(chunk){ + str += chunk; + }); + res.on('end', function(){ + var data = JSON.parse(str); + for(var i in data){ + var item = data[i]; + result[item.product.id.toString()] = item.product; + } + resp.send(result); + }); + }).end(); + }; + +Each hash key in the inner hash represents an attribute of an individual object. All datatypes must be strings (so the hash values need to all be strings, not integers). + +For example: + + :::javascript + result = { + "1" => { + "name" => "inner tube", + "brand" => "Michelin" + }, + "2" => { + "name" => "tire", + "brand" => "Michelin" + } + } + +## Creating Objects with RhoConnect + +For your create method, the RhoConnect server will pass you a hash containing the new record, called "create_hash". For example, it might be: + + :::javascript + { + "name" => "Hovercraft", + "brand" => "Acme" + } + +The RhoConnect `models/js/product.js` create method will be called once for every object that has been created on the client since the last sync. Below is an example of a create method against the [rhostore](http://rhostore.herokuapp.com), which accepts an HTTP POST to perform a create action. The create method should return a unique id string for the object for it to be later modifiable by the client. If no id is returned, then you should treat the client object as read only, because it will not be able to be synchronized. + + :::javascript + this.create = function(resp){ + var postData = JSON.stringify({ 'product': resp.params.create_object }); + var str = ''; + var options = { + host: host, + path: '/products.json', + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': postData.length + } + }; + var req = http.request(options, function(res){ + res.on('data', function(chunk){ + str += chunk; + }); + res.on('end', function(){ + var data = JSON.parse(str); + resp.send(data.product.id.toString()); + }); + }); + req.write(postData); + req.end(); + }; + +You will need to restart RhoConnect to reload the source adapter after modifying code. Note that the object will be created on the client right away, but it will be sent to the server on the next sync. \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/source-adapters.md b/docs/en/5.5/rhoconnect/source-adapters.md new file mode 100644 index 00000000..ec42b2b0 --- /dev/null +++ b/docs/en/5.5/rhoconnect/source-adapters.md @@ -0,0 +1,499 @@ +RhoConnect Source Adapters (Ruby) +=== + +## Generating the Source Adapter from RhoStudio + +To generate a RhoConnect source adapter and create the associated Controller/Model templates, open your RhoConnect project in RhoStudio. Then right-click on the project in the Project Explorer and select New->RhoConnect Source Adapter. + + + +In the Source Adapter Information window, enter the name for your source adapter. + +Click the Finish button to create the source adapter. + + + +After pressing the Finish button, you'll see the RhoConnect source adapter generator script output in the output console (Rhomobile build console). + + + +## Generating the Source Adapter from the Command Line + +To generate a source adapter for your RhoConnect application, you can run the `rhoconnect source` command within your application directory. + + :::term + $ rhoconnect source + Usage: rhoconnect source name [options] [args] + + Generates a new source adapter. + + Required: + name - the source adapter name(i.e. product) + + + Options specific for this generator: + + General options: + -p, --pretend Run, but do not make any changes. + -f, --force Overwrite files that already exist. + -s, --skip Skip files that already exist. + -d, --delete Delete files that have previously been generated with this generator. + --no-color Don't colorize the output + -h, --help Show this message + --debug Do not catch errors + +For the storeserver application example, within the storeserver directory, run: + + :::term + $ rhoconnect source product + Generating with source generator: + [ADDED] models/ruby/product.rb + [ADDED] controllers/ruby/product_controller.rb + [ADDED] spec/models/ruby/product_spec.rb + [ADDED] spec/controllers/ruby/product_controller_spec.rb + +## Understanding the Generated Controller File + +The generated source adapter's controller file (in this case, product_controller.rb) is similar to the code listing below. +Its purpose is to define the RhoConnect application HTTP end point and to register the corresponding SYNC routes. +Under the hood - it's an isolated Sinatra application designated to handle all incoming Product requests: + + :::ruby + class ProductController < Rhoconnect::Controller::Base + register Rhoconnect::EndPoint + + # add all SYNC routes + register Rhoconnect::Handler::Sync + + # add your custom Product routes here + end + +## Understanding the Generated Model File + +The generated source adapter's model file (in this case, product.rb) is similar to the code listing below: + + :::ruby + class Product < Rhoconnect::Model::Base + def initialize(source) + super(source) + end + + def login + # TODO: Login to your data source here if necessary + end + + def query + # TODO: Query your backend data source and assign the records + # to a nested hash structure called @result. For example: + # @result = { + # "1"=>{"name"=>"Acme", "industry"=>"Electronics"}, + # "2"=>{"name"=>"Best", "industry"=>"Software"} + # } + raise Rhoconnect::Model::Exception.new("Please provide some code to read records from the backend data source") + end + + def create(create_hash) + # TODO: Create a new record in your backend data source + # If your rhodes rhom object contains image/binary data + # (has the image_uri attribute), then a blob will be provided + raise "Please provide some code to create a single record in the backend data source using the create_hash" + end + + def update(update_hash) + # TODO: Update an existing record in your backend data source + raise "Please provide some code to update a single record in the backend data source using the update_hash" + end + + def delete(delete_hash) + # TODO: write some code here if applicable + # be sure to have a hash key and value for "object" + # for now, we'll say that its OK to not have a delete operation + # raise "Please provide some code to delete a single object in the backend application using the object_id" + end + + def logoff + # TODO: Logout from the data source if necessary + end + end + +During generation of the model, the `settings/settings.yml` file will be updated with some default options for the corresponding source: + + :::yaml + :sources: + Product: + :poll_interval: 300 + + +## Source Adapter API + +### Source Adapter Controller API (Ruby) + +You can use the following methods and techniques inside of your source adapter controller. + +* [register Rhoconnect::EndPoint](../rhoconnectapi/source-adapter-controller-api-ruby#register Rhoconnect::EndPoint) - adds Controller into the application's URL Map. +* [register Rhoconnect::Handler::Sync](../rhoconnectapi/source-adapter-controller-api-ruby#register Rhoconnect::Handler::Sync) - adds SYNC routes to your Controller. +* [pre-defined conditions](../rhoconnectapi/source-adapter-controller-api-ruby#pre-defined-conditions) - adds common helpers and conditions to your routes. +* [@model](../rhoconnectapi/source-adapter-controller-api-ruby#@model) - Access to the source adapter's model instance. +* [params,request,response](../rhoconnectapi/source-adapter-controller-api-ruby#sinatra-context) - Allows to use any standard Sinatra context objects. +* [Sinatra framework](../rhoconnectapi/source-adapter-controller-api-ruby#sinatra-framework) - Allows to use any standard Sinatra features. + +### Source Adapter Model API (Ruby) + +You can write the following methods for your source adapter model. These methods will be called by the controller at run-time and allow your source adapter model to interact with your backend service. + +* [login](../rhoconnectapi/source-adapter-model-api-ruby#login) - Login to your backend service (optional). +* [logoff](../rhoconnectapi/source-adapter-model-api-ruby#logoff) - Logoff from your backend service (optional). +* [query](../rhoconnectapi/source-adapter-model-api-ruby#query) - Query your backend service and build a hash of hashes (required). +* [search](../rhoconnectapi/source-adapter-model-api-ruby#search) - Search your backend based on params and build a hash of hashes (optional). +* [create](../rhoconnectapi/source-adapter-model-api-ruby#create) - Create a new record in the backend (optional). +* [update](../rhoconnectapi/source-adapter-model-api-ruby#update) - Update an existing record in the backend. +* [delete](../rhoconnectapi/source-adapter-model-api-ruby#delete) - Delete an existing record in the backend. +* [current_user](../rhoconnectapi/source-adapter-model-api-ruby#currentuser) - Returns the current user which called the adapter's model. +* [stash_result](../rhoconnectapi/source-adapter-model-api-ruby#stashresult) - Saves the current state of `@result` to redis and assigns it to `nil`. +* [store_blob](../rhoconnectapi/source-adapter-model-api-ruby#store_blob) - Save the incoming blob data into permanent storage for the future processing. +* [self.partition_name](../rhoconnectapi/source-adapter-model-api-ruby#self.partition_name) - Implement this class method to provide custom user partition. +* [get_data](../rhoconnectapi/source-adapter-model-api-ruby#get_data) - Get the model document data from Store. + +## Data Partitioning + +Data is stored in RhoConnect using [redis sets](http://redis.io/commands#set). The `@result` hash from the `query` method is stored in redis and referred to as the Master Document or MD. + +The MD is referenced in RhoConnect by a corresponding partition. Source adapters can partition data in two ways: user and app. As you might have guessed, user partitioning stores a copy of the source adapter MD for each user (one copy shared across all devices for a given user). + +Likewise, app partitioning stores one copy of the source adapter MD for the entire application (all users and devices share the same data). App partitioning can be particularly useful if you have source adapter models which retrieve large amounts of data that is fixed from user to user, for example a global product catalog. Using app partitioning wherever possible ***greatly reduces*** the amount of data in redis. + +### User Partition +User partitioning is the default mode for source adapters, however you can explicitly define it in `settings/settings.yml` with: + + :::yaml + :sources: + Product: + :poll_interval: 300 + :partition_type: user + +### App Partition +Enable app partitioning the same way: + + :::yaml + :sources: + Product: + :poll_interval: 300 + :partition_type: app + +Now you have a single copy of the `Product` source adapter dataset for all users. + +## Pass Through +RhoConnect provides a simple way to keep data out of redis. If you have sensitive data that you do not want saved in redis, add the `pass_through` option in settings/settings.yml for each source: + + :::yaml + :sources: + Product: + :pass_through: true + +**NOTE: When running query or search the entire data set will be returned from your backend service. ** + +## Redis Interface +RhoConnect provides a simple redis interface for saving/retrieving arbitrary data. This is useful if you want to save data in your application to be used later (i.e. in an async job or a subsequent source adapter execution). + + :::ruby + Store.put_value('hello','world') + + Store.get_value('hello') #=> 'world' + + # You can store nested hashes too! + Store.put_data( + 'mydata', + { + '1' => { 'hello' => 'world' } + } + ) + + Store.get_data('mydata') #=> { '1' => { 'hello' => 'world' } } + +## Handling Exceptions +If your source adapter model raises an instance of `Rhoconnect::Model::Exception`, the resulting message will be sent to the client's sync callback(in `@params['error_message']`). See the rhodes [sync exception handling docs](../guide/using_rhoconnect#handling-exceptions) for more details. + +You can use `Rhoconnect::Model::Exception` as a convenient way to notify your application of various error conditions. + +For example, your delete method might check the web service HTTP response code was 200 to make sure the record was deleted: + + :::ruby + def delete(delete_hash) + rest_result = RestClient.delete("#{@base}/#{delete_hash['id']}") + if rest_result.code != 200 + raise Rhoconnect::Model::Exception.new("Error deleting record.") + end + end + +**NOTE: When your adapter method raises an exception, no data is removed from the adapter's master document.** + +The following exceptions are provided for convenience: + +### `Rhoconnect::Model::LoginException` +Useful to raise in your model's login method if it failed. + +### `Rhoconnect::Model::LogoffException` +Similar to login, raise this if your model's logoff failed. + +### `Rhoconnect::Model::ServerTimeoutException` +Raise if your backend service connection times out. + +### `Rhoconnect::Model::ServerErrorException` +Raise this if your backend service returns a non-successful response. + + +## Handling Conflicts + +Handling conflicts in RhoConnect follows the same pattern as handling exceptions. Once your model method has detected a conflict, you can raise a `Rhoconnect::Model::ObjectConflictError` which will be sent to your application's sync callback. + +### `Rhoconnect::Model::ObjectConflictError` +Raise this if your model has detected a conflict. + + :::ruby + def update(update_hash) + obj_id = update_hash['id'] + update_hash.delete('id') + rest_result = RestClient.put("#{@base}/#{obj_id}",:product => update_hash) + if rest_result.code != 200 + raise Rhoconnect::Model::ObjectConflictError.new("Conflict detected updating the object.") + end + end + +## Sample Model +Here's a complete example of how the completed [product model might look](https://github.com/rhomobile/store-server/blob/master/sources/product.rb): + + :::ruby + require 'json' + require 'rest_client' + + class Product < Rhoconnect::Model::Base + + def initialize(source) + @base = 'http://rhostore.herokuapp.com/products' + super(source) + end + + def query(params=nil) + rest_result = RestClient.get("#{@base}.json").body + + if rest_result.code != 200 + raise Rhoconnect::Model::Exception.new("Error connecting!") + end + parsed = JSON.parse(rest_result) + + @result={} + parsed.each do |item| + @result[item["product"]["id"].to_s] = item["product"] + end if parsed + end + + def create(create_hash) + res = RestClient.post(@base,:product => create_hash) + + # After create we are redirected to the new record. + # We need to get the id of that record and return + # it as part of create so rhoconnect can establish a link + # from its temporary object on the client to this newly + # created object on the server + JSON.parse( + RestClient.get("#{res.headers[:location]}.json").body + )["product"]["id"] + end + + def update(update_hash) + obj_id = update_hash['id'] + update_hash.delete('id') + RestClient.put("#{@base}/#{obj_id}",:product => update_hash) + end + + def delete(delete_hash) + RestClient.delete("#{@base}/#{delete_hash['id']}") + end + end + +## A RhoConnect Query + +If you're doing a read-only non-authenticated source adapter, you can just write one method, query, to retrieve records as we describe here. The following is a sample query method to interact with a simple product catalog (available at http://rhostore.herokuapp.com) that exposes a REST interface. Note that RhoConnect can work with any protocol. This example shows JSON over HTTP with a REST interface, since that is common. The RhoConnect source adapter is Ruby code and there are ruby libraries (aka gems) that will make it easy to connect to and parse whatever you need -- the query code would just be slightly different. + +For a more complete example of rewriting the source adapter methods (such as create, update, and delete), refer to the [source adapter example](source-adapters#sample-adapter) in the RhoConnect Developer Reference. + +Our sample web service for returning all products in the catalog (http://rhostore.herokuapp.com/products.json) returns data like this: + + :::json + [ + { + "product": { + "name": "iPhone", + "brand": "Apple", + "updated_at": "2010-05-11T02:04:57Z", + "price": "$299.99", + "quantity": "5", + "id": 649, + "sku": "1234", + "created_at": "2010-05-11T02:04:57Z" + } + }, + { + "product": { + "name": "Accord", + "brand": "Honda", + "updated_at": "2010-05-13T22:24:48Z", + "price": "$6000", + "quantity": "", + "id": 648, + "sku": "123", + "created_at": "2010-05-11T02:04:53Z" + } + } + ] + +The Ruby code for parsing that data, sources.product.rb, is listed below. It uses the standard Ruby JSON library and the RestClient library for easy access to the REST web service. This example uses the id of the product record as the hash key. Note that the key for this hash must be a string and the value can be any set of name-value pairs which are represented as a Ruby hash. The instance variable @result must be set by the query method to this "hash of hashes", indexed by a unique identifier, so that the base SourceAdapter class sync method can populate Redis data store. + +You can edit sources/product.rb within RhoStudio, or you can navigate to it within your RhoConnect application folder and edit it with a text editor. + +We need to declare the standard libraries that we are using at the top of the sources/product.rb file: + + :::ruby + require 'json' + require 'rest_client' + +For convenience, we'll add an instance variable @base which contains the base URL of the web service and sets the value in the constructor: + + :::ruby + def initialize(source) + @base = 'http://rhostore.herokuapp.com/products' + super(source) + end + +Then fill in the query method: + + :::ruby + def query + parsed=JSON.parse(RestClient.get("#{@base}.json").body) + + @result={} + if parsed + parsed.each do |item| + key = item["product"]["id"].to_s + @result[key]=item["product"] + end + end + end + +**NOTE: The code above could be much more concise, but it is written to be easily readable by programmers who are unfamiliar with the Ruby language. If you are new to Ruby, you can read [Ruby from other languages](http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) for a good introduction.** + +Each hash key in the inner hash represents an attribute of an individual object. All datatypes must be strings (so the hash values need to all be strings, not integers). + +For example: + + :::ruby + @result = { + "1" => { + "name" => "inner tube", + "brand" => "Michelin" + }, + "2" => { + "name" => "tire", + "brand" => "Michelin" + } + } + +## Creating Objects with RhoConnect + +For your create method, the RhoConnect server will pass you a hash containing the new record, called "create_hash". For example, it might be: + + :::ruby + { + "name" => "Hovercraft", + "brand" => "Acme" + } + +The RhoConnect sources/product.rb create method will be called once for every object that has been created on the client since the last sync. Your code for create (or edit or delete) needs to use this populated array to do its work. Below is an example of a create method against the [rhostore](http://rhostore.herokuapp.com), which accepts an HTTP POST to perform a create action. The create method should return a unique id string for the object for it to be later modifiable by the client. If no id is returned, then you should treat the client object as read only, because it will not be able to be synchronized. + + :::ruby + def create(create_hash) + result = RestClient.post(@base, :product => create_hash) + + # after create we are redirected to the new record. + # The URL of the new record is given in the location header + location = "#{result.headers[:location]}.json" + + # We need to get the id of that record and return it as part of create + # so rhoconnect can establish a link from its temporary object on the + # client to this newly created object on the server + + new_record = RestClient.get(location).body + JSON.parse(new_record)["product"]["id"].to_s + end + +You will need to restart RhoConnect to reload the source adapter after modifying code. Note that the object will be created on the client right away, but it will be sent to the server on the next sync. + +## Authentication + +The generated RhoConnect application code includes a file at the root of the directory called "application.rb" which contains a hook for authentication. The complete file looks like this: + + :::ruby + class Application < Rhoconnect::Base + class << self + def authenticate(username,password,session) + true # do some interesting authentication here... + end + + # Add hooks for application startup here + # Don't forget to call super at the end! + def initializer(path) + super + end + + # Calling super here returns rack tempfile path: + # i.e. /var/folders/J4/J4wGJ-r6H7S313GEZ-Xx5E+++TI + # Note: This tempfile is removed when server stops or crashes... + # See http://rack.rubyforge.org/doc/Multipart.html for more info + # + # Override this by creating a copy of the file somewhere + # and returning the path to that file (then don't call super!): + # i.e. /mnt/myimages/soccer.png + def store_blob(blob) + super #=> returns blob[:tempfile] + end + end + end + + Application.initializer(ROOT_PATH) + +If your back end web service requires authentication, add code to the authenticate method and return true if authentication was successful or false to deny access to the application from this client. For example: + + :::ruby + def authenticate(username, password, session) + # ... connect to backend using API and authenticate ... + if success + # save the data for later use in the source adapter + Store.put_value("username:#{username}:token",username) + end + return success + end + + +## Compatibility with older versions of RhoConnect + +The RhoConnect Source Adapter Controller/Model concept was introduced in RhoConnect 4.0. In previous versions, a Source Adapter consisted only of one class - which is now has been moved to Source Adapter model. "Controller" part of the Source Adapter has been hidden inside of the RhoConnect library code. This posed a significant obstacle in a way how the developer could utilize the code and the common techniques. To overcome this obstacle, RhoConnect 4 provides you with direct access to the Controller allowing you to customize route behavior and utilize all of the powerful sinatra plugins/extensions that are available. + +At the same time, applications that were written using the pre-4.0 versions of RhoConnect will still continue to function without modifications for at least one version cycle. This is accomplished by providing the "default" implementation of the controller for the pre-4.0 Source Adapters. All the Model APIs that are described throughout the documentation are still applicable to the pre-4.0 Source Adapters. In this sense - the RhoConnect 4 Source Adapter Model class and pre-4.0 Source Adapter are interchangeable. + +However, we strongly recommend migrating your pre-4.0 application using this [guide](migration). RhoConnect 4 will print a warning at startup if it detects a pre-4.0 code structure. + + RhoConnect has detected that you're using deprecated Application class. + + Application class support was removed in RhoConnect 4.1. + Please, migrate your Application class into ApplicationController. + + For more details, see RhoConnect Migration guidelines at + docs.rhomobile.com + + RhoConnect has detected that you're using deprecated SourceAdapter classes. + + SourceAdapter class support was removed in RhoConnect 4.1. + Please, migrate your SourceAdapter classes into RhoConnect Models. + + For more details, see RhoConnect Migration guidelines at + docs.rhomobile.com \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/stats-middleware.md b/docs/en/5.5/rhoconnect/stats-middleware.md new file mode 100644 index 00000000..44be16e2 --- /dev/null +++ b/docs/en/5.5/rhoconnect/stats-middleware.md @@ -0,0 +1,49 @@ +Collecting Runtime Stats +=== +RhoConnect provides a simple stats [rack middleware](http://railscasts.com/episodes/151-rack-middleware) for collecting runtime information on your application. These stats are accessible from the [REST API](rest-api) and some default graphs are available from the [web console](web-console). + +## Enabling Stats +To enable stats in your RhoConnect application, simply turn on the stats middleware by editing config.ru: + + :::ruby + Rhoconnect::Server.enable :stats + +A complete config.ru might look like: + + :::ruby + require 'rhoconnect/application/init' + + # secret is generated along with the app + Rhoconnect::Server.set :secret, 'my_secret' + + # !!! Add your custom initializers and overrides here !!! + Rhoconnect::Server.enable :stats + + # run RhoConnect Application + run Rhoconnect.app + + +Now just restart your rhoconnect application: + + :::term + $ rhoconnect restart + +And navigate to the 'Statistics' tab in your RhoConnect console: + + :::term + $ rhoconnect web + +## Stats Console +You should see graphs, organized by categories: + + + +RhoConnect statistics are organized into the following categories: + +* User Count - # of users stored in redis + +* Device Count - # of devices currently registered with RhoConnect + +* HTTP Timing - # average HTTP request time by URL + +* Source Timing - # average source adapter execution time by method \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/supported-platforms.md b/docs/en/5.5/rhoconnect/supported-platforms.md new file mode 100644 index 00000000..8e105ddc --- /dev/null +++ b/docs/en/5.5/rhoconnect/supported-platforms.md @@ -0,0 +1,71 @@ +Supported Platforms +=== +## Support Matrix + +RhoConnect gem is available on the following platforms: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                              OSDistributionRuby 1.9.3Ruby 2.0.0JRubyEnvironment
                                                                              Linux CentOS / RHEL 5.x & 6.x,
                                                                              Ubuntu 12.04
                                                                              ruby-1.9.3-p448 TBD jruby-1.7.4 Development &
                                                                              Production
                                                                              Mac OS Mac OS X 10.7/10.8 ruby-1.9.3-p448 TBD jruby-1.7.4 Development
                                                                              Windows Windows 7 ruby-1.9.3-p448 TBD jruby-1.7.4 Development
                                                                              + +Other Ruby versions and releases might work with RhoConnect gem, but there are no guarantees. + +## Release Notes + +RhoConnect for Windows is supported only in development environments. The components you should have for this environment are: + +* Ruby 1.9.3 +* Redis 2.6.x +* Latest RhoConnect and Rhodes gems +* Eclipse 3.6 with latest RhoStudio plugin, or RhoStudio for Windows 32-bit +* Make 3.81 +* DevKit for Windows (or other Windows development environment) + +RhoConnect for Linux is supported for both development and production environments. +On Linux servers RhoConnect is available in the format of [Debian (deb) and Red Hat (rpm) packages](http://edgedocs.rhomobile.com/rhoconnect/deploying) for Ubuntu and CentOS respectively. +RhoConnect Mac OS X is supported in development environment. +The components you should have for this environment are: + +* Ruby 1.9.3 +* Nginx HTTP server (1.4.x) +* Redis data store (2.6.x) +* Thin application server +* RhoConnect gem with all required dependencies + +## Known issues for JRuby: + +* Usually JDK is shipped with only weak encryption, and that simply will not allow the proper key sizes being created by openssl. RhoConnect uses strong encryption for license keys and to function properly in JRuby environment installation of Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction policy files might be required. +* Path to user’s gems, warbler data should not include white spaces (i.e. in user's account name). + + diff --git a/docs/en/5.5/rhoconnect/testing.md b/docs/en/5.5/rhoconnect/testing.md new file mode 100644 index 00000000..0e2e3864 --- /dev/null +++ b/docs/en/5.5/rhoconnect/testing.md @@ -0,0 +1,220 @@ +Testing Your RhoConnect Application +=== +RhoConnect provides a [spec](http://rspec.info/) framework for [behavior driven development](http://en.wikipedia.org/wiki/Behavior_Driven_Development) of your application. When your application and source adapters are generated, you will see spec files generated in the top-level 'spec' folder of your application. + +## Example Spec + +Here is a simple example model spec for the [rhostore product adapter](http://github.com/rhomobile/store-server/blob/master/sources/product.rb): + + :::ruby + it "should process Product query" do + test_query.size.should > 0 + query_errors.should == {} + end + +This simple spec runs the query method of our product adapter model and verifies the result is greater than one object and has no errors. + +The full code listing for this product_spec is available [on github](http://github.com/rhomobile/store-server/blob/master/spec/sources/product_spec.rb). + +## Running Specs +From your application's root folder: + + :::term + $ rhoconnect spec + [05:51:48 PM 2012-04-19] Rhoconnect Server v4.0.1 started... + Product + it should behave like SpecHelper + should process Product query (PENDING: No reason given) + should process Product create (PENDING: No reason given) + should process Product update (PENDING: No reason given) + should process Product delete (PENDING: No reason given) + Pending: + Product it should behave like SpecHelper should process Product query + Product it should behave like SpecHelper should process Product create + Product it should behave like SpecHelper should process Product update + Product it should behave like SpecHelper should process Product delete + + Finished in 0.05877 seconds + 4 examples, 0 failures, 4 pending + + +This will also automatically generate an rcov report under 'coverage' if you have rcov installed (currently only Mac/Linux support rcov). + +## Test API + +The [RhoConnect Source Adapter Model Test API](../rhoconnectapi/test-api) provides the following methods to perform spec tests. + + * [setup_test_for](../rhoconnectapi/test-api-ruby#setuptestfor) - Executes the adapter's query method and returns the master document. + * [test_query](../rhoconnectapi/test-api-ruby#testquery) - Executes the adapter's query method and returns the master document. + * [query_errors](../rhoconnectapi/test-api-ruby#queryerrors) - Returns any errors stored in redis for the previous source adapter query. + * [test_create](../rhoconnectapi/test-api-ruby#testcreate) - Executes the adapter's create method with a provided record and returns the object string from the create method. + * [create_errors](../rhoconnectapi/test-api-ruby#createerrors) - Returns the result of the adapter's create method.. + * [test_update](../rhoconnectapi/test-api-ruby#testupdate) - Execute the source adapter's update method. + * [update_errors](../rhoconnectapi/test-api-ruby#updateerrors) - Returns any errors stored in redis from the previous source adapter update. + * [test_delete](../rhoconnectapi/test-api-ruby#testdelete) - Execute the source adapter's delete method. + * [delete_errors](../rhoconnectapi/test-api-ruby#deleteerrors) - Returns any errors stored in redis from the previous source adapter delete. + * [md](../rhoconnectapi/test-api-ruby#md) - Returns the master document (:md) for the source adapter stored in redis. + * [cd](../rhoconnectapi/test-api-ruby#cd) - Returns the client document (:cd) for the source adapter + client under test. + +## Example of setup_test_for + +This example initializes a source adapter model named Product under test for a user named testuser. + + :::ruby + # 'testuser' will be used by rest of the specs + setup_test_for(Product,'testuser') + +## Example of test_query + +The `test_query` method executes the model's query method and returns the master document (:md) stored in redis. + +For example, if your source adapter query method was: + + :::ruby + def query(params=nil) + @result = { + "1" => { + "name"=>"Acme", + "industry"=>"Electronics"}, + "2" => { + "name"=>"Best", + "industry"=>"Software" + } + } + end + +`test_query` would return: + + :::ruby + { + "1" => { + "name" => "Acme", + "industry"=>"Electronics" + }, + "2" => { + "name" => "Best", + "industry" => "Software" + } + } + +## Example of query_errors + +Returns any errors stored in redis for the previous model's query. + +For example: + + :::ruby + { + "query-error" => { + "message" => "error connecting to web service!" + } + } + +## Example of test_create + +The `test_create` method executes the model's create method with a provided record and returns the object string from the create method. If the create method returns a string, then a link will be saved for the device next time it synchronizes. + +For example, in your spec: + :::ruby + @product = { + 'name' => 'iPhone', + 'brand' => 'Apple', + 'price' => '$299.99', + 'quantity' => '5', + 'sku' => '1234' + } + new_product_id = test_create(@product) + create_errors.should == {} + md[new_product_id].should == @product + +If you have set [pass through](http://docs.rhomobile.com/rhoconnect/source-adapters#pass-through) to true, the create method will not return a string but instead a json hash of the object ids created. When testing the id will always be set to 'temp_id'. + +For example, in your spec: + :::ruby + @product = { + 'name' => 'iPhone', + 'brand' => 'Apple', + 'price' => '$299.99', + 'quantity' => '5', + 'sku' => '1234' + } + @s.pass_through = 'true' + new_product = test_create(@product) + new_product.should == {'processed' => ["temp-id"]}.to_json + +## Example of test_update + +This example executes the model's update method, calling the adapter's update method for object_id '4'. + + :::ruby + test_update({'4' => {'price' => '$199.99'}}) + update_errors.should == {} + test_query + md[product_id]['price'].should == '$199.99' + + +**NOTE: To test the master document, you will need to run `test_query` as shown above.** + +If you have set [pass through](http://docs.rhomobile.com/rhoconnect/source-adapters#pass-through) to true, the update method will return a json hash of the object id updated. + +For example, in your spec: + :::ruby + record = {'4'=> { 'price' => '199.99' }} + @s.pass_through = 'true' + test_update(record).should == {'processed' => ["4"]}.to_json + +## Example of test_delete + +This example executes the source model's delete method, calling the adapter's delete method for product '4'. + + :::ruby + @product = { + 'name' => 'iPhone', + 'brand' => 'Apple', + 'price' => '$299.99', + 'quantity' => '5', + 'sku' => '1234' + } + test_delete('4' => @product) + delete_errors.should == {} + md.should == {} + +**NOTE: The master document (:md) will be updated and can be verified as shown above.** + +If you have set [pass through](http://docs.rhomobile.com/rhoconnect/source-adapters#pass-through) to true, the delete method will return a json hash of the object id deleted. You could have the following code in your spec. + + :::ruby + @product = { + 'name' => 'iPhone', + 'brand' => 'Apple', + 'price' => '$299.99', + 'quantity' => '5', + 'sku' => '1234' + } + record = {'4'=> { 'price' => '199.99' }} + @s.pass_through = 'true' + test_update(record).should == {'processed' => ["4"]}.to_json + +## Example of md + +The md method returns the master document (:md) for the source adapter model stored in redis. This is equivalent to the @result hash of hashes structure. + + :::ruby + md.should == { + "1" => { + "name"=>"Acme", + "industry"=>"Electronics" + }, + "2" => { + "name"=>"Best", + "industry"=>"Software" + } + } + +## Example of cd + +This example shows that the master document (:md) and client document (:cd) should be equal after the query is executed. + + :::ruby + test_query.size.should > 0 + md.should == cd diff --git a/docs/en/5.5/rhoconnect/tutorial.md b/docs/en/5.5/rhoconnect/tutorial.md new file mode 100644 index 00000000..bbb58f57 --- /dev/null +++ b/docs/en/5.5/rhoconnect/tutorial.md @@ -0,0 +1,451 @@ +# RhoConnect Tutorial + +## Adding Data synchronization to Your Backend Application with RhoConnect + +RhoConnect is a synchronization framework consisting of a client application (a client component on the mobile device) and a server component (a RhoConnect application) that runs on any server capable of running Ruby. The client application can be a Rhodes application, or another mobile application written without the use of Rhodes (such as an iOS/Objective C or Android/Java application). + +RhoConnect requires that you write a small amount of code for the query, create, update and delete operations of your particular enterprise backend. You can write this code in JavaScript or Ruby as a RhoConnect source adapter, or you can write this code as a RhoConnect plug-in application written in Java, .NET, or Ruby on Rails. + +In this tutorial, you will learn: + +1. How to generate a RhoConnect Application +2. How to create a source adapter +3. How to enable synchronization in a RhoMobile application + +Full documentation of all capabilities of RhoConnect can be found in the [RhoConnect Developer Guides](introduction). + +## Installing RhoConnect + +You can install RhoConnect in two ways: + + * Install the RhoConnect gem from the [command-line](install). + * Install RhoConnect along side the other Rhomobile Suite tools with the [Rhomobile Suite installation](../guide/rhomobile-install). + +If you have been issued a RhoConnect license, you can license your app as described [here](licensing). + +## Generating a RhoConnect App + +Currently there are two different types of RhoConnect apps that can be generated, Ruby and JavaScript: + +
                                                                              + +
                                                                              +
                                                                              +
                                                                              +

                                                                              Generating a JavaScript RhoConnect app. Change `app_name` to what you would like to call your application.

                                                                              +
                                                                              $ rhoconnect app app_name --js
                                                                              +
                                                                              +
                                                                              +

                                                                              Generating a Ruby RhoConnect app. Change `app_name` to what you would like to call your application.

                                                                              +
                                                                              $ rhoconnect app app_name
                                                                              +
                                                                              +
                                                                              + + +Ruby RhoConnect apps can also be generated using RhoStudio. To use this method, see [Generating a RhoConnect app with RhoStudio](command-line#generating-a-rhoconnect-app-with-rhostudio) + +After code generation, the bundle install command will be run for the first time automatically. + +NOTE: It is required to have a connection to the internet to create an application. There are certain Ruby gems that RhoConnect is dependant on. + +## Starting Your RhoConnect App + +Once you have generated your app code, you'll need to start your redis server and the RhoConnect app in order to ensure that everything is working properly. + +
                                                                              + +
                                                                              +
                                                                              +
                                                                              +

                                                                              Before starting your RhoConnect app on your Mac you’ll first need to install Dtach

                                                                              +
                                                                              +      $ rhoconnect dtach-install
                                                                              +    
                                                                              +

                                                                              Once Dtach is installed, any app on your machine that runs in the terminal (if started with Dtach) will be able to be detached from the current terminal activity and be put into the background. In our case, redis and the RhoConnect service itself run using Dtach which lets us run them all in the same terminal window

                                                                              +

                                                                              Starting RhoConnect is a two-step command process: Start redis, then start the RhoConnect app. Both commands must be run from within the RhoConnect app's directory.

                                                                              +
                                                                              +      $ rhoconnect redis-start
                                                                              +    
                                                                              +
                                                                              +      $ rhoconnect start
                                                                              +    
                                                                              +
                                                                              +
                                                                              +

                                                                              On Windows there is no need to start the redis server because starting RhoConnect will start the redis server automatically.

                                                                              +
                                                                              +      C:\rc_app>rhoconnect start
                                                                              +    
                                                                              +
                                                                              +
                                                                              + +If all went well, you should see: + + :::term + Listening on 0.0.0.0:9292, CTRL+C to stop + +This means that your RhoConnect app is up and running on localhost:9292. If you go to this address in your browser you will see the RhoConnect Console, pictured below. + + + +## Defining RhoConnect Source Adapters + +Once RhoConnect is installed we’re ready to build a RhoConnect source adapter to integrate with our backend application. To define a RhoConnect source you just need to identify a handful of operations to interact with your backend data source: login, query, sync, create, update, delete and logoff. If you generated a JavaScript RhoConnect application then you will need to generate [JavaScript Source adapters](source-adapters). Likewise, if you generated a Ruby RhoConnect application, you will need to generate [Ruby Source Adapters](source-adapters-js). + +To demonstrate how this works we have setup a [dummy backend](http://rhostore.herokuapp.com) for a `Product` model. This backend will allow you to perform all CRUD operations, however the data will be reset every hour. + +Let's go ahead and create a source adapter for this model. + +
                                                                              + +
                                                                              +
                                                                              +
                                                                              +
                                                                               rhoconnect source product --js
                                                                              + +
                                                                              +
                                                                              +
                                                                               rhoconnect source product
                                                                              + You can also accomplish this from RhoStudio as explained in the Ruby Source Adapter guide +
                                                                              +
                                                                              + +Now let's replace the contents of the Source Adapter generated code. Normally, you will replace each method with code specific to your backend. + + +
                                                                              +
                                                                              +
                                                                              
                                                                              +var rc = require('rhoconnect_helpers');
                                                                              +var http = require('http');
                                                                              +var host = 'rhostore.herokuapp.com';
                                                                              +
                                                                              +var Product = function(){
                                                                              +
                                                                              +  this.login = function(resp){
                                                                              +    resp.send(true);
                                                                              +  };
                                                                              +
                                                                              +  this.query = function(resp){
                                                                              +    var result = {};
                                                                              +    var str = '';
                                                                              +
                                                                              +    http.request('http://' + host + '/products.json', function(res){
                                                                              +      res.on('data', function(chunk){
                                                                              +        str += chunk;
                                                                              +      });
                                                                              +      res.on('end', function(){
                                                                              +        var data = JSON.parse(str);
                                                                              +        for(var i in data){
                                                                              +          var item = data[i];
                                                                              +          result[item.product.id.toString()] = item.product;
                                                                              +        }
                                                                              +        resp.send(result);
                                                                              +      });
                                                                              +    }).end();
                                                                              +  };
                                                                              +
                                                                              +  this.create = function(resp){
                                                                              +    var postData = JSON.stringify({ 'product': resp.params.create_object });
                                                                              +    var str = '';
                                                                              +    var options = {
                                                                              +      host: host,
                                                                              +      path: '/products.json',
                                                                              +      method: 'POST',
                                                                              +      headers: { 
                                                                              +        'Content-Type': 'application/json', 
                                                                              +        'Content-Length': postData.length
                                                                              +      }
                                                                              +    };
                                                                              +    var req = http.request(options, function(res){
                                                                              +      res.on('data', function(chunk){
                                                                              +        str += chunk;
                                                                              +      });
                                                                              +      res.on('end', function(){
                                                                              +        var data = JSON.parse(str);
                                                                              +        resp.send(data.product.id.toString());
                                                                              +      });
                                                                              +    });
                                                                              +    req.write(postData);
                                                                              +    req.end();
                                                                              +  };
                                                                              +
                                                                              +  this.update = function(resp){
                                                                              +    var objId = resp.params.update_object.id;
                                                                              +    var putData = JSON.stringify({ "product": resp.params.update_object });
                                                                              +    // Remove the id from the hash, we don't need it.
                                                                              +    delete putData.id;
                                                                              +    var options = {
                                                                              +      host: host,
                                                                              +      path: '/products/' + objId + '.json',
                                                                              +      method: 'PUT',
                                                                              +      headers: { 
                                                                              +        'Content-Type': 'application/json',
                                                                              +        'Content-Length': putData.length
                                                                              +      }
                                                                              +    };
                                                                              +    var req = http.request(options, function(res){
                                                                              +      res.on('data', function(){});
                                                                              +      res.on('end', function(){
                                                                              +        resp.send(true);
                                                                              +      });
                                                                              +      res.on('error', function(){
                                                                              +        resp.send(false);
                                                                              +      });
                                                                              +    });
                                                                              +    req.write(putData);
                                                                              +    req.end();
                                                                              +  };
                                                                              +
                                                                              +  this.del = function(resp){
                                                                              +    var objId = resp.params.delete_object.id;
                                                                              +    var options = {
                                                                              +      host: host,
                                                                              +      path: '/products/' + objId + '.json',
                                                                              +      method: 'DELETE',
                                                                              +      headers: { 'Content-Type': 'application/json' }
                                                                              +    };
                                                                              +    var req = http.request(options, function(res){
                                                                              +      res.on('data', function(){});
                                                                              +      res.on('end', function(){
                                                                              +        resp.send(true);
                                                                              +      });
                                                                              +      res.on('error', function(){
                                                                              +        resp.send(false);
                                                                              +      });
                                                                              +    });
                                                                              +    req.end();
                                                                              +  };
                                                                              +
                                                                              +  this.logoff = function(resp){
                                                                              +    resp.send(true);
                                                                              +  };
                                                                              +
                                                                              +  this.storeBlob = function(resp){
                                                                              +    // TODO: Handle post requests for blobs here.
                                                                              +    // Reference the blob object's path with resp.params.path.
                                                                              +    new rc.Exception(
                                                                              +      resp, "Please provide some code to handle blobs if you are using them."
                                                                              +    );
                                                                              +  };
                                                                              +};
                                                                              +
                                                                              +module.exports = new Product();       
                                                                              +      
                                                                              + +
                                                                              +
                                                                              +
                                                                               
                                                                              +require 'json'
                                                                              +require 'rest_client'
                                                                              +
                                                                              +class Product < Rhoconnect::Model::Base
                                                                              +
                                                                              +  def initialize(source)
                                                                              +    @base = 'http://rhostore.herokuapp.com/products'
                                                                              +    super(source)
                                                                              +  end
                                                                              +
                                                                              +  def query(params=nil)
                                                                              +    rest_result = RestClient.get("#{@base}.json").body
                                                                              +
                                                                              +  if rest_result.code != 200
                                                                              +    raise Rhoconnect::Model::Exception.new("Error connecting!")
                                                                              +  end
                                                                              +    parsed = JSON.parse(rest_result)
                                                                              +
                                                                              +    @result={}
                                                                              +    parsed.each do |item|
                                                                              +      @result[item["product"]["id"].to_s] = item["product"]
                                                                              +    end if parsed
                                                                              +  end
                                                                              +
                                                                              +  def create(create_hash)
                                                                              +    res = RestClient.post(@base,:product => create_hash)
                                                                              +
                                                                              +    # After create we are redirected to the new record.
                                                                              +    # We need to get the id of that record and return
                                                                              +  # it as part of create so rhoconnect can establish a link
                                                                              +  # from its temporary object on the client to this newly
                                                                              +  # created object on the server
                                                                              +    JSON.parse(
                                                                              +    RestClient.get("#{res.headers[:location]}.json").body
                                                                              +  )["product"]["id"]
                                                                              +  end
                                                                              +
                                                                              +  def update(update_hash)
                                                                              +    obj_id = update_hash['id']
                                                                              +    update_hash.delete('id')
                                                                              +    RestClient.put("#{@base}/#{obj_id}",:product => update_hash)
                                                                              +  end
                                                                              +
                                                                              +  def delete(delete_hash)
                                                                              +    RestClient.delete("#{@base}/#{delete_hash['id']}")
                                                                              +  end
                                                                              +end
                                                                              +      
                                                                              +
                                                                              +
                                                                              + +The above example will work with our test backend, if you are attempting to connect to your own backend data, you should read more about [Source Adapters](source-adapters-intro) and the corresponding methods: + +* [JavaScript Source Adapters](source-adapters-js) +* [Ruby Source Adapters](source-adapters) + + +## Testing Sync From the Client + +To test to make sure the sync is working, we need to create a basic RhoMobile application. + +### Creating the RhoMobile Application + +1. Open RhoStudio +2. Select File / New Project / RhoMobile Application +3. After choosing an application name click `Finish` + +### Adding the Product Model + +1. While in RhoStudio, right click on the project you just created +2. Choose New / RhoMobile Model +3. Enter `Product` in the `Model name` field +4. Enter `name,brand,quantity,price` in the `Model attributes` field + +NOTE: Pay attention to spelling of the model and attributes, as the sample code is assuming that it will match exactly to the JSON object coming from the backend. + +### Enabling Sync + +1) Open the folder `app\Product` and edit the file `product.rb` + +2) Uncomment the line `enable :sync` line. + + + :::ruby + # The model has already been created by the framework, and extends Rhom::RhomObject + # You can add more methods here + class Product + include Rhom::PropertyBag + + # Uncomment the following line to enable sync with Product. + enable :sync + + #add model specific code here + end + +### Adding Product views + +1) Open the file `app\index.erb` + +2) Replace the line: + + :::html +
                                                                            • Add link here...
                                                                            • + +with: + + :::html +
                                                                              + +
                                                                              + +### Configuring your SyncServer +Make sure your server URL is configured in the Rhomobile app. If your server is running on YourIPAddress with the port 9292, the following line should be at the bottom of your corresponding Rhodes app, `rhoconfig.txt`: + + :::text + syncserver = 'http://YourIPAddress:9292' + +NOTE: If you are using Android, syncserver cannot be set to localhost, you must use your machine's local IP Address. Ex: 192.168.x.x + + +### Syncing Data +To sync with the RhoConnect server, the Rhodes client must log in. The Rhodes generated app includes some screens for login and other common functions, which you will typically modify to suit the design of your application. The generated UI is useful since it allows you to focus on the core functionality of your application before implementing the important, but mundane, details of user authentication and settings. + +
                                                                              +
                                                                              +

                                                                              + 1. From the home page in the Rhodes app, click on the login button in the upper right corner. Alternatively, you can click on the tool icon at the bottom of the screen to go to the Settings screen. +

                                                                              +

                                                                              + 2. Login using any name & password. The generated code allows any login, but you can modify that in application.rb. +

                                                                              +
                                                                              +
                                                                              +

                                                                              + App Home Page +

                                                                              + +
                                                                              +
                                                                              +

                                                                              + App Login Page +

                                                                              + +
                                                                              +
                                                                              + + +
                                                                              +
                                                                              +

                                                                              + 3. If login is successful, you will see a Client ID in the settings screen. The ClientID is generated the first time you log in and is stored in the client database. It serves as a unique identifier which is required for rhoconnect. (Note: this value will persist across logins, but if you reset the client database or the user re-installs the app, a new ClientID will be generated.) +

                                                                              +

                                                                              + 4. Sync is triggered automatically. Click on the home icon and then select “Products” and you should see the list of product records from the server. +

                                                                              +
                                                                              +
                                                                              +

                                                                              + App Settings Page With Client ID +

                                                                              + +
                                                                              +
                                                                              +

                                                                              + List of Products on Local Storage +

                                                                              + +
                                                                              +
                                                                              + + +

                                                                              5. You can now add, modify or delete products to your app locally and then sync them to the Rhostore back-end.

                                                                              + +
                                                                              +
                                                                              +

                                                                              + Create New Product Page +

                                                                              + +
                                                                              +
                                                                              +

                                                                              + Rhostore Before Sync +

                                                                              + +
                                                                              +
                                                                              +

                                                                              + Rhostore After Sync +

                                                                              + +
                                                                              +
                                                                              + +

                                                                              6. You can also simulate changes that occur on the backend, by using the CRUD operations from your browser. These changes will not appear on the device for at least 5 minutes. This is due to the default setting for the RhoConnect application to query the backend for updates. You can modify this by changing the `poll_interval` setting in the `settings\setting.yml` file in the RhoConnect application. +

                                                                              + +Now that you have your RhoConnect server successfully syncing to your back-end application, you're ready to move on to more advanced topics using RhoConnect such as PUSH notifications, RhoConnect plug-ins, and sync conflict resolution to name a few. For more information on these and other topics, refer to our [RhoConnect Guides](introduction). \ No newline at end of file diff --git a/docs/en/5.5/rhoconnect/web-console.md b/docs/en/5.5/rhoconnect/web-console.md new file mode 100644 index 00000000..09718342 --- /dev/null +++ b/docs/en/5.5/rhoconnect/web-console.md @@ -0,0 +1,39 @@ +Web Console +=== + +Your RhoConnect application exposes a web interface which runs on http://localhost:9292/console/ (port 80 on Windows) by default. You can open the console by running the following in your application directory: + + :::term + $ rhoconnect web + +To login to the console: + +1. Click on the "Console" link +2. Make sure the server field matches the host and port your rhoconnect app is running +3. Default username is 'rhoadmin' and the password is empty +4. Now you will be presented with a page showing your current license, for example: + + + Licensed to Rhomobile on Fri Apr 23 17:20:13 -0700 2010, + available 9 of 10 devices + +It will also show a link to "Application Users" where you can view users of the system as well as devices they have registered. + +To reset the server, you can click on the "Reset" button at the bottom. + +**NOTE: Resetting the server will remove all data from redis including registered devices, this cannot be undone.** + +If you want to disable this web interface, you can do so by editing the rackup file, config.ru: + + :::ruby + # Setup the url map + run Rack::URLMap.new \ + "/" => Rhoconnect::Server.new, + "/resque" => Resque::Server.new, # If you don't want resque frontend, disable it here + #"/console" => RhoconnectConsole::Server.new # If you don't want rhoconnect frontend, disable it here + +**NOTE: This web console is intended to be used for basic tests and views into the running RhoConnect application. It uses the [RhoConnect REST API](rest-api) for everything it does, so it is very easy to extend this console or programmatically control your RhoConnect application directly using the [RhoConnect API](rest-api). ** + +Here is a screenshot of the web console: + + \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectapi/source-adapter-controller-api-js.md b/docs/en/5.5/rhoconnectapi/source-adapter-controller-api-js.md new file mode 100644 index 00000000..388bfc3d --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/source-adapter-controller-api-js.md @@ -0,0 +1,95 @@ +Source Adapter Controller API (JavaScript) +=== +Your RhoConnect source adapter controller can use any of these methods to facilitate handling of the incoming requests. + +## app +A JavaScript RhoConnect application by default will create a controller object called `app`. This can really be called anything, but we will use the name `app` throughout this document. If you are familiar with the popular Node.js [express framework](http://expressjs.com/api.html), the `app` object is similar in concept to an express application. + + :::javascript + var app = require('ballroom'); + +## controllerName(name) +Set the name for a controller. This should match your client model and RhoConnect model name. + + :::javascript + app.controllerName('Product'); + +## registerHandler(name) +Register a RhoConnect handler for this controller. This will install default behavior into the controller. Currently only the 'sync' handler is available, which installs the necessary `sync` routes for a source adapter controller: + + :::javascript + app.registerHandler('sync'); + +## get(route, options, callback) +Register a get route with the server. The callback must make a `send` call to return the response to RhoConnect. + + + :::javascript + app.get('/my_custom_route', {}, function(req,resp){ + resp.send('hello world'); + }); + +## post(route, options, callback) +Register a post route with the server. The callback must make a `send` call to return the response to RhoConnect. The HTTP request body is available as `req.params`: + + :::javascript + app.post('/my_custom_route', {}, function(req,resp){ + var someId = req.params.someId; + resp.send('ok'); + }); + +## put(route, options, callback) +Register a put route with the server. The callback must make a `send` call to return the response to RhoConnect. The HTTP request body is available as `req.params`: + + :::javascript + app.put('/my_custom_route', {}, function(req,resp){ + var someId = req.params.someId; + resp.send('ok'); + }); + +## del(route, options, callback) +Register a delete route with the server. The callback must make a `send` call to return the response to RhoConnect. + + :::javascript + app.del('/my_custom_route/:id', {}, function(req,resp){ + var deleteId = req.params.id; + resp.send('ok'); + }); + +## currentUser +Returns the current user who made the request. + + :::javascript + app.get('/echo_user', {}, function(req,resp){ + var user = resp.currentUser; + resp.send(user); + }); + +## loadModel(name) +Returns the current model instance for this controller. + + :::javascript + app.get('/custom_query_route', {}, function(req,resp){ + var model = app.loadModel(req.model); + model.query(resp); + }); + +## Sample Controller +Here's a sample controller that uses several of the methods described in this document: + + :::javascript + var app = require('ballroom'); + + app.controllerName('Product'); + app.registerHandler('sync'); + + // Add your custom routes here ... + app.post('/my_custom_route', {}, function(req,resp){ + app.loadModel(req.model).someCustomFunction(resp); + }); + + app.get('/status', {}, function(req,resp){ + resp.send( + JSON.stringify({'status': 'ok'}) + ); + }); \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectapi/source-adapter-controller-api-ruby.md b/docs/en/5.5/rhoconnectapi/source-adapter-controller-api-ruby.md new file mode 100644 index 00000000..0677459f --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/source-adapter-controller-api-ruby.md @@ -0,0 +1,228 @@ +Source Adapter Controller API (Ruby) +=== +Your RhoConnect source adapter controller can use any of these methods to facilitate handling of the incoming requests. + +## register Rhoconnect::EndPoint + +`Rhoconnect::EndPoint` is a [Sinatra extension](http://www.sinatrarb.com/extensions.html) which adds the Controller into the application's URLMap. +The Source Adapter Controller becomes available at the root path `/app/v1/`. +One exception here is the Application Controller - which has its own special root `/rc/v1/app`. +All of the Controller's routes are registered relative to its root, for example: + + GET '/my_custom_route' declared inside of the Product Controller expands into GET '/app/v1/Product/my_custom_route' + +NOTE: You can see which routes are available for your application by using `rhoconnect routes` command inside of your app's root directory. + +## register Rhoconnect::Handler::Sync + +`Rhoconnect::Handler::Sync` is a [Sinatra extension](http://www.sinatrarb.com/extensions.html) which adds default SYNC routes into your Source Adapter Controller. When used, it adds the following routes into the Source Adapter Controller: + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                              GET '/'Main SYNC route responsible for data query and downloading the changes to the client.Handler: :rc_handler => :queryOptions: :source_required => true, :client_required => true, :login_required => true
                                                                              POST '/'Create/Update/Delete route responsible for handling incoming changes (creates/updates/deletes) from the client.Handler: :rc_handler => :cudOptions: :source_required => true, :client_required => true, :login_required => true
                                                                              PUT '/:id'Update route responsible for updating a single object from the client.Handler: :rc_handler => :updateOptions: :source_required => true, :client_required => true, :login_required => true
                                                                              DELETE '/:id'Update route responsible for deleting a single object from the client.Handler: :rc_handler => :deleteOptions: :source_required => true, :client_required => true, :login_required => true
                                                                              + +Also, the `Rhoconnect::Handler::Sync` extension adds the following Plugin Callback routes (requires API Token): + + + + + + + + + + + + + +
                                                                              POST '/push_objects'This route is used to upload changes (creates or updates) from the plugin (or any 3rd party application).Handler: :rc_handler => :push_objectsOptions: :admin_required => true
                                                                              POST '/push_deletes'This route is used to delete objects (called from the plugin or any 3rd party application).Handler: :rc_handler => :push_deletesOptions: :admin_required => true
                                                                              + + +## @model + +@model variable is available implicitly only inside of the Source Adapter Controller's routes that enforce :source_required => true condition (which in turn requires valid session cookie upon the call). +Access your source adapter model instance variable inside of the route: + + :::ruby + post '/my_custom_route', :source_required => true do + "Hello! I am - #{@model.source.inspect}" + end + +NOTE: Application Controller doesn't have the @model variable available, since it is not a Source Adapter Controller. + +Alternatively, you can construct the model's instance by using the following method inside of your route: + + :::ruby + post '/my_custom_route' do + source_instance = Source.load('', + {:user_id => '', :app_id => Rhoconnect::APP_NAME} + @model = Rhoconnect::Model::Base.create(source_instance) + "Hello! I am - #{@model.source.inspect}" + end + +Here: + + + + + + + + + + +
                                                                              source_namename of the source that you want to load (for example, Product). Source here can be considered as the model's run-time meta context.
                                                                              usernamename of the user whose source data you want to load. Source (and model) always operate in the context of a certain user.
                                                                              + +## Sinatra context + +You can access and use any of the standard Sinatra objects defined in the context of the request: params, request, response, etc. + + :::ruby + post '/my_custom_route' + log params.inspect + response.headers['my_ret_header'] = 'This is my response header' + status 200 + end + +## Sinatra framework + +Source adapter controller is a Sinatra app - you can use any of the standard Sinatra features: + +* [extensions](http://www.sinatrarb.com/extensions.html) +* [middleware](http://www.sinatrarb.com/intro.html#Sinatra::Base%20-%20Middleware,%20Libraries,%20and%20Modular%20Apps) +* [conditions](http://www.sinatrarb.com/intro.html#Conditions) +* [helpers](http://www.sinatrarb.com/intro.html#Helpers) +* [`before` and `after` blocks](http://www.sinatrarb.com/intro.html#Filters) + +Look for more info in the [Sinatra documentation](http://www.sinatrarb.com/) + +In the below example, you can register and use custom defined logger. + + :::ruby + module MyCustomLogger + def my_custom_log(message) + # do some interesting stuff here + end + end + + class Product < Rhoconnect::Controller::Base + helpers MyCustomLogger + + # use my_custom_log before the route is called + before '/my_custom_route' do + my_custom_log("Calling from before") + end + + # route definitions + post '/my_custom_route' do + 'Hello World' + end + end + +## Pre-defined conditions + +Some of the most commonly used features and helpers are exposed to the user via pre-defined Sinatra conditions. + +For more info on what is Sinatra condition and how to use it - [look here](http://www.sinatrarb.com/intro.html#Conditions) + +### admin_required + +When installed, this condition enforces presence of the `api-token`, thus, making the route accessible only to the admin user. Typically, all `system` routes using this condition: + + :::ruby + post '/my_custom_admin_route', :admin_required => true do + puts 'Only admin can access this route' + end + +### login_required + +When installed, this condition enforces presence of the `Session Cookie`, i.e. only logged-in user can access this route. Typically, this condition enabled by default for all user-defined Controllers. +If want to alter this behavior, you can enable/disable this condition for any particular route: + + :::ruby + get '/my_custom_route', :login_required => false do + puts 'Hello World - no user required to access this route' + end + +### source_required + +When installed, this condition enforces presence of the `source_id`. This condition is enabled by default for all user-defined Controllers - since they by definition based upon Source. +To customize behavior of your route - you can disable this check and load any desired sources manually inside of your route. Also, this condition initializes `@model` variable: + + :::ruby + get '/my_custom_route', :source_required => false do + other_source = Source.load('', + {:user_id => '', :app_id => Rhoconnect::APP_NAME} + other_model = Rhoconnect::Model::Base.create(other_source) + puts "Hello World - using my #{other_model.inspect}" + end + +### client_required + +When installed, this condition enforces presense of the `client_id`. This condition is enabled by default for all `sync` routes - because they are called from the client. Also, `client_required` condition implicitly enforces presence of the `source_id` parameter and therefore is used together with `source_required` condition. You may enable/disable it in your custom route: + + :::ruby + post '/my_custom_route_many_sources', :client_required => false, :source_required => false, :login_required => false, :admin_required => true do + puts "Admin is required here - this is my admin route and client is not required!" + # my custom sources_data is a JSON hash-table + user_name = @params['username'] + sources_data = @params['sources_data'] + sources_data.each do |source_name, source_data| + # do something with data + end + end + +### verbs + +You can use this helper condition whenever you need to make some functionality available only to routes with specific verbs. Typically, this can be helpful in your custom `:before` or `:after` filters. +For example, if you have two routes using the same path, but different verbs (POST and GET) and you want to execute `:before` filter only for the GET route: + + :::ruby + class Product < Rhoconnect::Controller::Base + # use my_custom_log before the route is called + before '/my_custom_route', :verbs => ['GET'] do + puts "This code will be executed only before the GET route" + end + + # route definitions + post '/my_custom_route' do + puts 'my POST route' + end + + get 'my_custom_route' do + puts 'My GET route' + end + end + +### default settings + +Every user-defined Source Adapter Controller has certain conditions enabled by default. This means that whenever you're defining your custom route inside of the Source Adapter Controller, it will implicitly install several conditions. Below is the list of the conditions installed by default: + + * :source_required => true + * :client_required => true + * :login_required => true + +NOTE: If you want disable one of predefined conditions, then you should do it manually inside of your custom routes declaration. diff --git a/docs/en/5.5/rhoconnectapi/source-adapter-exception-api-js.md b/docs/en/5.5/rhoconnectapi/source-adapter-exception-api-js.md new file mode 100644 index 00000000..a65f3cb1 --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/source-adapter-exception-api-js.md @@ -0,0 +1,72 @@ +Source Adapter Exception API (JavaScript) +=== +Exception types in JavaScript source adapters are mapped to their ruby equivalent. See the [ruby exception section](../rhoconnect/source-adapters#handling-exceptions) for more details about these exception types. + +## Setup +Make sure you have a Rhoconnect Helpers object in your model: + + :::javascript + var rc = require('rhoconnect_helpers'); + +## Exception(response, message) +Raise a generic RhoConnect adapter exception. + + :::javascript + new rc.Exception(resp, 'Something went wrong!'); + +## LoginException(response, message) +Raise an exception on the login procedure. + + :::javascript + new rc.LoginException(resp, 'A login error occurred.'); + +## LogoffException(response, message) +Raise an exception on the logoff procedure. + + :::javascript + new rc.LogoffException(resp, 'A logoff error occurred.'); + +## ServerTimeoutException(response, message) +Raise an exception indicating a timeout occurred. + + :::javascript + new rc.ServerTimeoutException(resp, 'A timeout occurred.'); + +## ServerErrorException(response, message) +Raise an exception concerning the backend service. + + :::javascript + new rc.ServerErrorException(resp, 'An error occurred with our systems, please try again.'); + +## ObjectConflictErrorException(response, message) +Raise a [conflict exception](../rhoconnect/cud-conflicts) to indicate there was a conflict in handling the record. This will trigger RhoConnect's automatic processing for conflicts. + + :::javascript + new rc.ObjectConflictErrorException( + resp, 'A conflict error occurred, please update your copy and try again' + ); + + +## Sample +The following example raises a `ServerErrorException` in the [delete function](source-adapter-model-api-js#del) if the record was not successfully deleted. + + :::javascript + this.del = function(resp){ + var objId = resp.params.delete_object.id; + var options = { + host: host, + path: '/products/' + objId + '.json', + method: 'DELETE', + headers: { 'Content-Type': 'application/json' } + }; + var req = http.request(options, function(res){ + res.on('data', function(){}); + res.on('end', function(){ + resp.send(true); + }); + res.on('error', function(){ + new rc.ServerErrorException(resp, 'There was an error deleting, please try again'); + }); + }); + req.end(); + }; diff --git a/docs/en/5.5/rhoconnectapi/source-adapter-model-api-js.md b/docs/en/5.5/rhoconnectapi/source-adapter-model-api-js.md new file mode 100644 index 00000000..07e7d6a0 --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/source-adapter-model-api-js.md @@ -0,0 +1,237 @@ +Source Adapter Model API (JavaScript) +=== +Your RhoConnect source adapter model can use any of these methods to interact with your backend service. Refer to the [js source adapter sample](../rhoconnect/source-adapters-js#sample-model) for a complete example. As with the [controller API](source-adapter-controller-api-js), each function that accepts a [response object](source-adapter-response-api-js) must call `.send()` on it to return control to RhoConnect. + +## login +Login to your backend service (optional). + + :::javascript + this.login = function(resp){ + resp.send(true); + }; + +## logoff +Logoff from your backend service (optional). + + :::javascript + this.logoff = function(resp){ + resp.send(true); + }; + +## query +Query your backend service and build a hash of hashes (required). + +**NOTE: This method must call resp.send(data) where `data` is a hash of hashes.** + + :::javascript + this.query = function(resp){ + var result = {}; + var str = ''; + + http.request('http://' + host + '/products.json', function(res){ + res.on('data', function(chunk){ + str += chunk; + }); + res.on('end', function(){ + var data = JSON.parse(str); + for(var i in data){ + var item = data[i]; + result[item.product.id.toString()] = item.product; + } + resp.send(result); + }); + }).end(); + }; + +## search +Search your backend based on params and build a hash of hashes (optional). Similar to query, however the master document accumulates the data in redis instead of replacing each time it runs. + + :::javascript + this.search = function(resp){ + var result = {}; + var str = ''; + var name = resp.params.name; + + http.request('http://' + host + '/products.json?name=' + name, function(res){ + res.on('data', function(chunk){ + str += chunk; + }); + res.on('end', function(){ + var data = JSON.parse(str); + for(var i in data){ + var item = data[i]; + result[item.product.id.toString()] = item.product; + } + resp.send(result); + }); + }).end(); + }; + +Next, you will need to add search to your Rhodes application. For details, see the [Rhodes search section](../guide/using_rhoconnect#filtering-datasets-with-search). + +## create +Create a new record in the backend (optional). + +**NOTE: RhoConnect can establish a 'link' between the local record id provided by the client and the new record id provided by the backend service. To enable this link, return the new record id as a string.** + + :::javascript + this.create = function(resp){ + var postData = JSON.stringify({ 'product': resp.params.create_object }); + var str = ''; + var options = { + host: host, + path: '/products.json', + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': postData.length + } + }; + var req = http.request(options, function(res){ + res.on('data', function(chunk){ + str += chunk; + }); + res.on('end', function(){ + var data = JSON.parse(str); + resp.send(data.product.id.toString()); + }); + }); + req.write(postData); + req.end(); + }; + +## update +Update an existing record in the backend (optional). + + :::javascript + this.update = function(resp){ + var objId = resp.params.update_object.id; + var putData = JSON.stringify({ "product": resp.params.update_object }); + // Remove the id from the hash, we don't need it. + delete putData.id; + var options = { + host: host, + path: '/products/' + objId + '.json', + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': putData.length + } + }; + var req = http.request(options, function(res){ + res.on('data', function(){}); + res.on('end', function(){ + resp.send(true); + }); + res.on('error', function(){ + resp.send(false); + }); + }); + req.write(putData); + req.end(); + }; + +## del +Delete an existing record in the backend (optional). + + :::javascript + this.del = function(resp){ + var objId = resp.params.delete_object.id; + var options = { + host: host, + path: '/products/' + objId + '.json', + method: 'DELETE', + headers: { 'Content-Type': 'application/json' } + }; + var req = http.request(options, function(res){ + res.on('data', function(){}); + res.on('end', function(){ + resp.send(true); + }); + res.on('error', function(){ + resp.send(false); + }); + }); + req.end(); + }; + +## stashResult(resp) +Saves a partial dataset to redis. Typically this is used when your adapter has to paginate through data. The following example data to redis one item at a time. + + :::javascript + this.query = function(resp){ + var rc = require('rhoconnect_helpers'); + var result = {}; + var str = ''; + + http.request('http://' + host + '/products.json', function(res){ + res.on('data', function(chunk){ + str += chunk; + }); + res.on('end', function(){ + var data = JSON.parse(str); + for(var i in data){ + var item = data[i]; + resp.params = {}; + resp.params[item.product.id.toString()] = item.product; + rc.stashResult(resp); + } + resp.send(true); + }); + }).end(); + }; + +## getData(resp, callback) +You can access your model's document data by with `getData` method. This will return the redis Master Document (:md). + + :::javascript + var data = {}; + var rc = require('rhoconnect_helpers'); + rc.getData(resp, function(resp){ + data = resp.result; + // data contains the model's Master Document. + resp.send(data); + }); + +## currentUser +Returns the current user which called the adapter. The current user is part of the [response object](source-adapter-response-api-js). For example, you could filter results for a specific user in your query method. + + :::javascript + this.query = function(resp){ + var result = {}; + var str = ''; + var user = resp.currentUser; + + // ... + }; + +## storeBlob +If your Rhodes application sends blobs as a part of the create/update operation - you must implement this method inside of your Source Adapter Model. We do not recommend using the default implementation where blob is stored in the tempfile provided by Rack, because RhoConnect processing is asynchronous and there is no guarantee that the temporary file will exist at the actual time when `create` is called. + +The following example opens the file (contained in `resp.params.path`) if it exists. + + :::javascript + this.storeBlob = function(resp){ + var fs = require('fs'); + if(fs.existsSync(resp.params.path)){ + + // read and process the file here ... + + resp.send('some_filename'); + } else{ + resp.send(false); + } + }; + +## partitionName +Use `partitionName` to define a custom data partition for your source adapter. This is useful if you want groups of users to share data or you want to define some other kind of custom scoping. See [this source adapter section](../rhoconnect/source-adapters#data-partitioning) for more details about RhoConnect data partitioning. + + :::javascript + this.partitionName = function(resp){ + if(someCustomRoleLookup(resp.params.user_id) === 'admin'){ + resp.send('admin_restricted_data'); + } else{ + resp.send(resp.params.user_id); + } + }; + diff --git a/docs/en/5.5/rhoconnectapi/source-adapter-model-api-ruby.md b/docs/en/5.5/rhoconnectapi/source-adapter-model-api-ruby.md new file mode 100644 index 00000000..c4fdd5c4 --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/source-adapter-model-api-ruby.md @@ -0,0 +1,142 @@ +# Source Adapter Model API (Ruby) + +Your RhoConnect source adapter model can use any of these methods to interact with your backend service. Refer to the [source adapter sample](../rhoconnect/source-adapters#sample-adapter) for a complete example. + +## login + +Login to your backend service (optional). + + :::ruby + def login + MyWebService.login(current_user.login) + end + +## logoff +Logoff from your back-end service (optional). + + :::ruby + def logoff + MyWebService.logoff(current_user.login) + end + +## query +Query your back-end service and build a hash of hashes (required). The `query_params` parameter in this method is nil by default but you can use it to pass custom data from the client to the RhoConnect server using [`RhoConnectClient.doSyncSource()`](../api/RhoConnectClient#mdoSyncSource) method. Typically this is done when you want to implement some custom query behavior. + +**NOTE: This method must assign `@result` to a hash of hashes. If @result is `nil` or `{}`, the master document will be erased from redis.** + + :::ruby + def query(query_params = nil) + parsed = JSON.parse(RestClient.get("#{@base}.json").body) + + @result = {} + parsed.each do |item| + @result[item["product"]["id"].to_s] = item["product"] + end if parsed + end + +## search +Search your back-end based on params and build a hash of hashes (optional). Similar to query, however the master document accumulates the data in `@result` instead of replacing when it runs. + + :::ruby + def search(params) + parsed = JSON.parse(RestClient.get("#{@base}.json").body) + + @result = {} + parsed.each do |item| + if item["product"]["name"].downcase == params['name'].downcase + @result[item["product"]["id"].to_s] = item["product"] + end + end if parsed + end + +Next, you will need to add search to your Rhodes application. For details, see the [Rhodes search section](../guide/using_rhoconnect#filtering-datasets-with-search). + +## create +Create a new record in the back-end (optional). + +**NOTE: RhoConnect can establish a 'link' between the local record id provided by the client and the new record id provided by the backend service. To enable this link, return the new record id as a string.** + + :::ruby + def create(create_hash) + res = MyWebService.create(create_hash) + + # return new product id so we establish a client link + res.new_id + end + +## update + +Update an existing record in the backend (optional). + + :::ruby + def update(update_hash) + end + +## delete + +Delete an existing record in the backend (optional). + + :::ruby + def delete(delete_hash) + MyWebService.delete(delete_hash['id']) + end + +## current_user + +Returns the current user which called the adapter. For example, you could filter results for a specific user in your query method: + + :::ruby + def query + @result = MyWebService.get_records_for_user(current_user.login) + end + +## stash_result + +Saves the current state of `@result` to redis and assigns it to `nil`. Typically this is used when your adapter has to paginate through backend service data. + + :::ruby + def query + @result = {} + ('a'..'z').each_with_index do |letter,i| + @result ||= {} + @result.merge!( DictionaryService.get_records_for(letter) ) + stash_result if i % 2 == 0 + end + end + +## store_blob + +If your Rhodes application sends blobs as a part of the create/update operation - you must implement this method inside of your Source Adapter Model and do not use default implementation where blob is stored in the tempfile provided by Rack, because RhoConnect processing is asynchronous and there is no guarantee that the temporary file will exist at the actual time when `create` is called. + +The following example stores the file permanently and keeps its `:filename` argument as another object attribute. + + :::ruby + def store_blob(obj,field_name,blob) + # ... custom code to store the blob file ... + my_stored_filename = do_custom_store[blob[:filename]] + obj['filename'] = my_stored_filename + end + +## self.partition_name + +Sometimes, different groups of users share the common source data. To leverage this, you can implement the following method in your Source Adapter Model to provide custom partition names for the users with shared data. In this case, RhoConnect will store the data for MD of the grouped users using your custom partition name, which will reduce the memory footprint in Redis. From this standpoint, `app` partition is the edge-case of the custom user partitioning where all users share the same data for the particular source. + +To use the custom user partitioning, implement the following class method in your Source Adapter's model: + + :::ruby + class Product < Rhoconnect::Model::Base + # group users by the first letter + def self.partition_name(user_id) + return user_id[0] + end + end + +## get_data + +You can access your model's document data by with `get_data` method. By default, when called without arguments - it returns the Master Document (:md). + + :::ruby + # some custom controller's method that has access to model + def my_custom_method + my_model_md = @model.get_data + end \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectapi/source-adapter-request-api-js.md b/docs/en/5.5/rhoconnectapi/source-adapter-request-api-js.md new file mode 100644 index 00000000..efc31670 --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/source-adapter-request-api-js.md @@ -0,0 +1,31 @@ +Source Adapter Request API (JavaScript) +=== +The Source Adapter Request API provides access to an incoming HTTP request context and can be used in your [controller](source-adapter-controller-api-js). + +## params +A hash of parameters available from the request. + + :::javascript + app.post("/login",{"rc_handler":"authenticate"}, function(req,resp){ + var login = req.params.login; + var password = req.params.password; + if(someAuthFunction(login,password) === true) { + resp.send(false); + } else { + resp.send(true); + } + }); + +## header +Access the request headers. + + :::javascript + req.header['Content-Type'] + // 'application/json' + +## model +Returns the model name for the request. + + :::javascript + req.model + //=> 'Product' \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectapi/source-adapter-response-api-js.md b/docs/en/5.5/rhoconnectapi/source-adapter-response-api-js.md new file mode 100644 index 00000000..8a2ec533 --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/source-adapter-response-api-js.md @@ -0,0 +1,46 @@ +Source Adapter Response API (JavaScript) +=== +The Source Adapter Response API provides access to the HTTP response context (typically as a variable called `resp`) and can be used in your model or controller. The response object manages the control flow of your JavaScript business logic, so it is important to always call [resp.send()](#send) in your functions so that they don't hang. + +## params +A hash of parameters available from the request. + + :::javascript + createObject = resp.params.create_object; + var postData = JSON.stringify({ 'product': createObject }); + // ... + resp.send('someId'); + +## header +Access the response headers. + + :::javascript + resp.header['Content-Type'] + // 'application/json' + resp.send(true); + +## send(value) +Return program control. + +**NOTE: Most controller and model methods will need to do this.** + + :::javascript + app.get('/status', {}, function(req,resp){ + resp.send('ok'); + }); + +## exception +Set an exception for the response. + + :::javascript + resp.exception = 'Error accessing web service!'; + resp.send(true); + +## currentUser +Returns the current user of the response context. + + :::javascript + app.get('/echo_user', {}, function(req,resp){ + var user = resp.currentUser; + resp.send(user); + }); diff --git a/docs/en/5.5/rhoconnectapi/source-adapter-store-api-js.md b/docs/en/5.5/rhoconnectapi/source-adapter-store-api-js.md new file mode 100644 index 00000000..686e9986 --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/source-adapter-store-api-js.md @@ -0,0 +1,55 @@ +Source Adapter Store API (JavaScript) +=== +RhoConnect provides a simple redis interface for saving/retrieving arbitrary data. This is useful if you want to save data in your application to be used later (i.e. in an async job or a subsequent source adapter execution). As with the other JavaScript methods execution is asynchronous, so be sure to call [resp.send()](source-adapter-response-api-js#sendvalue) or your method will hang. + +## Setup +To create a Store object that you can use in your model: + + :::javascript + var rc = require('rhoconnect_helpers'); + var Store = rc.Store; + +## getValue(resp,callback) +Retrieve a simple value from redis. + + :::javascript + var value = ''; + resp.params = 'hello'; + Store.getValue(resp, function(resp){ + value = resp.result; + // value is now 'world' + resp.send(resp.result); + }); + +## putValue(resp,callback) +Add a simple value to redis. The first array item is the key, the second is the value. + + :::javascript + resp.params = ['hello', 'world'] + Store.putValue(resp, function(resp){ + resp.send(true); + }); + +## getData(resp,callback) +Retrieve an array or hash from redis. + + :::javascript + // assuming 'foo' contains {'1': {'name': 'iPhone'}} + resp.params = 'foo'; + Store.getData(resp,function(resp){ + resp.send(resp.result); + // returns {'1': {'name': 'iPhone'}} + }); + +## putData(resp,callback) +Add an array or hash to redis. The key and data are contained in the `resp.params` object. + + :::javascript + resp.params = [ + 'foo', + { '1': {'name': 'iPhone'} } + ] + Store.putData(resp,function(resp){ + resp.send(resp.result); + }); + // 'foo' key now contains { '1': {'name': 'iPhone'} } \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectapi/source-adapter-store-api-ruby.md b/docs/en/5.5/rhoconnectapi/source-adapter-store-api-ruby.md new file mode 100644 index 00000000..2ba4830b --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/source-adapter-store-api-ruby.md @@ -0,0 +1,44 @@ +Source Adapter Store API (Ruby) +=== +RhoConnect provides a simple redis interface for saving/retrieving arbitrary data. This is useful if you want to save data in your application to be used later (i.e. in an async job or a subsequent source adapter execution). + +## get_value(key) +Retrieve a simple value from redis. + + :::ruby + key = 'hello' + + value = Store.get_value(key) + +## put_value(key, value) +Add a simple value to redis. The first array item is the key, the second is the value. + + :::ruby + key = 'hello' + value = 'world' + + Store.put_value(key, value) + +**NOTE: To delete a value from redis, simply use `put_value(key, nil)`** + +## get_data(key) +Retrieve an array or hash from redis. + + :::ruby + key = 'foo' + # assuming 'foo' references { '1' => { 'name' => 'iPhone' }} + + data = Store.get_data(key) + # data now contains { '1' => { 'name' => 'iPhone' }} + +## put_data(key, data) +Add an array or hash to redis. + + :::ruby + key = 'foo' + data = { '1'=> {'name' => 'iPhone' }} + + Store.put_data(key, data) + # 'foo' key now contains { '1' => { 'name' => 'iPhone' }} + +**NOTE: To delete data from redis, simply use `put_data(key, nil)`** \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectapi/test-api-ruby.md b/docs/en/5.5/rhoconnectapi/test-api-ruby.md new file mode 100644 index 00000000..4d428133 --- /dev/null +++ b/docs/en/5.5/rhoconnectapi/test-api-ruby.md @@ -0,0 +1,112 @@ +# Source Adapter Test API + +The test API allows you to spec test your RhoConnect source adapter application. + +## setup_test_for + +Initializes the source adapter under test for a given user, typically in a before(:each) block. Refer to [Example of setup_test_for](../rhoconnect/testing#example-of-setuptestfor) for an example. + + :::ruby + setup_test_for(adapter,user_id) + + + + + + + + + + +
                                                                              adapterThe name of the source adapter.
                                                                              user_idThe name of the user.
                                                                              + +## test_query + +Executes the adapter's query method and returns the master document (:md) stored in redis. Refer to [Example of test_query](../rhoconnect/testing#example-of-testquery) for an example. + + :::ruby + test_query + +## query_errors + +Returns any errors stored in redis for the previous source adapter query. Refer to [Example of query_errors](../rhoconnect/testing#example-of-queryerrors) for an example. + + :::ruby + query_errors + +## test_create + +Executes the adapter's create method with a provided record and returns the object string from the create method. If the create method returns a string, then a link will be saved for the device next time it synchronizes. Refer to [Example of test_create](../rhoconnect/testing#example-of-testcreate) for an example. + + :::ruby + test_create(record) + + + + + + +
                                                                              recorda local database partition.
                                                                              + +## create_errors + +Returns the result of the adapter's create method. The master document (:md) should also contain the new record. Returns any errors stored in redis from the previous source adapter create (same structure as query errors). + + :::ruby + create_errors + +## test_update + +Execute the source adapter's update method. Refer to [Example of test_update](../rhoconnect/testing#example-of-testupdate) for an example. + + :::ruby + test_update(record) + + + + + + +
                                                                              recordA record as hash of hashes (object_id => object).
                                                                              + +## update_errors + +Returns any errors stored in redis from the previous source adapter update (same structure as query errors). + + :::ruby + update_errors + +## test_delete + +Execute the source adapter’s delete method. Takes a record as hash of hashes (object_id => object). Refer to [Example of test_delete](../rhoconnect/testing#example-of-testdelete) for an example. + + :::ruby + test_delete(record) + + + + + + +
                                                                              recordA record as hash of hashes (object_id => object).
                                                                              + +## delete_errors + +Returns any errors stored in redis from the previous source adapter delete (same structure as query errors). Refer to [Example of test_delete](../rhoconnect/testing#example-of-testdelete) for an example. + + :::ruby + delete_errors + +## md + +Returns the master document (:md) for the source adapter stored in redis. This is equivalent to the @result hash of hashes structure. Refer to [Example of md](../rhoconnect/testing#example-of-md) for an example. + + :::ruby + md + +## cd + +Returns the client document (:cd) for the source adapter + client under test. The master document (:md) and client document (:cd) should be equal after the query is executed. Refer to [Example of cd](../rhoconnect/testing#example-of-cd) for an example. + + :::ruby + cd \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectjs/creating-app.md b/docs/en/5.5/rhoconnectjs/creating-app.md new file mode 100644 index 00000000..d78eecb5 --- /dev/null +++ b/docs/en/5.5/rhoconnectjs/creating-app.md @@ -0,0 +1,533 @@ +Creating an application +=== +The following instructions describe how to use `rhoconnect.js` to connect your application to a rhoconnect instance. jQuery Mobile will be used for the UI and persistence.js will be used as an object-database mapper. Currently rhoconnect.js supports both Sencha Touch and persistence.js. + +To view the finished application, which is written to run with the PhoneGap framework, visit rho-fat-freec-crm example. + +NOTE: Unless you are using Sencha Touch for your UI as well, you will need to use persistence.js as your object-database mapper to avoid framework conflicts. + +## Getting Started + +You need to add libraries and define the rhoconnect location. + +### Adding Dependent Libraries + +Add all of the JavaScript and stylesheet libraries to the application. Inside of the index.html file, add the following lines: + + :::html + + + + + + + + + + + + + +The first five files included are for jQuery mobile. They include jQuery 1.6.1, jQuery.base64.js (needed for binary encoding of data), json.js, and jquery.mobile css and js files. + +The next two files are for persistence.js, and since we are using SQLite, persistence.store.sql.js. See persistence.js documentation for more information on this. + +The next file is, at this time, the latest version of rhoconnect.js. We will add all of our JavaScript code into a file called application.js, so include that file as well. + +### Defining the rhoconnect Location + +Include the location of our rhoconnect instance. In this example, we are connecting to a rhoconnect instance provisioned on heroku. We also define our application name and set the log level. + + :::html + + +## Creating a Login View + +Next we will create a simple login view to login to the rhoconnect instance. + +### Defining a jQuery Mobile Page + +Inside of index.html we will define a jQuery Mobile page with two textfields for username and password. Notice the onload event attached to the body tag. This will be used to attach the JavaScript functions that we will write inside of application.js. + + :::html + + +
                                                                              +
                                                                              +

                                                                              Fat Free CRM

                                                                              +
                                                                              +
                                                                              + +
                                                                              + + + + + Login +
                                                                              +
                                                                              +
                                                                              + + + +### Defining a Login Function + +Inside of application.js, define a login function that is returned with the onload event attached to the body tag. + + var username = null; + var password = null; + onLoad = (function($) { + function mapPages() { + $('a#login').live('tap',function(event){ + setNames(); + loginRhoConnect(username, password).done(function(){ + sync(); + $.mobile.changePage("#home", "slideup"); + attach_events(); + $('.greeting').replaceWith("

                                                                              Welcome " + username + '

                                                                              '); + }).fail(function(errCode){ + $('.login-error').replaceWith(""); + $('.login-error').fadeOut(3000); + }) + }) + } + + + var modelDefinitions = [ + { + name: 'User', + fields: [ + {name: 'username', type: 'string'}, + {name: 'email', type: 'string'}, + {name: 'first_name', type: 'string'}, + {name: 'last_name', type: 'string'}, + {name: 'title', type: 'string'}, + {name: 'company', type: 'string'}, + {name: 'created_at', type: 'string'}, + {name: 'updated_at', type: 'string'} + ] + }, + { + name: 'Task', + fields: [ + {name: 'user_id', type: 'string'}, + {name: 'assigned_to', type: 'string'}, + {name: 'completed_by', type: 'string'}, + {name: 'name', type: 'string'}, + {name: 'asset_id', type: 'string'}, + {name: 'priority', type: 'string'}, + {name: 'category', type: 'string'}, + {name: 'bucket', type: 'string'}, + {name: 'due_at', type: 'string'}, + {name: 'completed_at', type: 'string'}, + {name: 'deleted_at', type: 'string'}, + {name: 'created_at', type: 'string'}, + {name: 'updated_at', type: 'string'}, + {name: 'background_info', type: 'string'} + ] + } + ] + + return mapPages; + })(jQuery); + +### Get the Username and Password + +Inside of the mapPages() function, call setNames(). The setNames() function grabs the username and password from the fields defined in the jQuery mobile page defined in index.html. + + function setNames(){ + username = $('input#username')[0].value; + password = $('input#password')[0].value; + } + +### Call Rhoconnect.login, Rhoconnect.init, and Rhoconnect.syncAllSources + +Next, call loginRhoConnect(username,password). We are using deferred objects to chain multiple callbacks. First Rhoconnect.login is called, on success Rhoconnect.init is called. + + function loginRhoConnect(username, password) { + persistence.store.rhoconnect.config(persistence); + + return $.Deferred(function(dfr){ + RhoConnect.login(username, password, + new RhoConnect.SyncNotification(), true /*do db init*/).done(function(){ + // Init DB for the user on success + initRhoconnect(username, false).done(function(){ + dfr.resolve(); + }).fail(function(errCode, err){ + alert('DB init error: ' +errCode); + dfr.reject(errCode, err); + }); + }).fail(function(errCode, err){ + //alert('RhoConnect login error: ' +errCode); + dfr.reject(errCode, err); + }); + }).promise(); + } + + // RhoConnect.js initialization + function initRhoconnect(username, doReset) { + return RhoConnect.init(modelDefinitions, 'persistencejs', doReset); + } + +Rhoconnect.init takes three parameters: an array of hashes defining each model or data-object, the data-object mapping library (either persistencejs or extjs), and a callback function. All parameters are optional except for the modelDefinitions (the hash array). + +On success of Rhoconnect.init, the callback chain will be resolved and a promise object (see deferred objects) will be returned. + +Inside of loginRhoConnect(username, password), the sync() function will be called. + + function sync(){ + RhoConnect.syncAllSources().done(function(){ + alert('sync successful'); + }).fail(function(errCode, err){ + alert('Data sync error: ' +errCode); + }); + } + +Rhoconnect.syncAllSources() will attempt to sync all model definitions defined with the rhoconnect instance. + +## Querying objects + +Since we have logged in successfully and synced with the rhoconnect instance, we will want to display all of the records. + +### Define a New jQuery Mobile Page + +Notice in the login function, we call $.mobile.changePage("#home", "slideup") as well as attach\_events(). Define a new jQuery Mobile page called "home" inside of index.html. + + :::html + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + Tasks +
                                                                              +
                                                                              + + +The button called "tasks" is used to display all the records from the Task model. + +### Map the Tasks Button + +We can now define the attach\_events() function to map this task button: + + function attach_events() { + $('a#tasks').live('tap',function(event){ + pull_data('Task'); + }) + } + + var fields = [ + 'user_id','assigned_to','completed_by','name','asset_id','priority','category','bucket', + 'due_at','completed_at','deleted_at','created_at','updated_at','background_info','campaign_id', + 'first_name','last_name','title','company','status','email','lead_id','probability','closes_on', 'source' + ] + +### Accept the Model to Query + +The pull\_data function accepts any model we would like to query. In this case it is passed the Task model. + + function pull_data(model) { + var store = RhoConnect.dataAccessObjects()[model]; + + current_model = model; + persistence.loadFromRhoConnect(function() { + storeLoaded(); + }); + + function storeLoaded() { + html = ""; + html = "
                                                                              "; + store.all().each(null, function(record){ + html += "

                                                                              "+ get_title(record) + "

                                                                              \ + edit
                                                                              \ + delete
                                                                              "; + for( var j=0; j
                                                                              " + + format_field(record[fields[j]],fields[j]) + "
                                                                              "; + } + } + html += "
                                                                              " + }); + html += "
                                                                              " + $('#list-data').replaceWith(html); + $('a#delete').live('tap',function(){ + delete_object($(this).attr('rhoId')); + }); + $('a#edit').live('tap',function(){ + edit_object($(this).attr('rhoId')); + }); + $('#list-data').page(); + $.mobile.changePage('#list',"slideup"); + } + } + +This is a very busy function. The important calls to take out of it are: + + var store = RhoConnect.dataAccessObjects()[model]; + +This function is passed a model name and returns a hash of data access objects. + + persistence.loadFromRhoConnect(function() { + storeLoaded(); + }); + +When using persistance.js, you need to call loadFromRhoConnect and parse the hash of dataAccessObjects inside of the callback function: in this case, storeLoaded(). + +The storeLoaded() function iterates through all the models constructing html to be inserted into a page yet to be defined in index.html. Buttons for edit and delete are also being mapped here. + +### Display the Results + +Create a new page in index.html to display the results from pull\_data(). + + +
                                                                              +
                                                                              +
                                                                              + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + +Notice `
                                                                              `. This is a place holder that is used to insert the constructed html list of Tasks. + +## Creating an Object + +To create a new Task object, first add a button to the page we defined above. + + +
                                                                              +
                                                                              +
                                                                              + +
                                                                              + new +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + +### Show a Form to Enter Object Values + +Create another page to show a form for a user to enter object values. + + +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              +
                                                                              + + +### Map the Task Button + +In the attach\_events function, map this button: + + function attach_events() { + $('a#tasks').live('tap',function(event){ + pull_data('Task'); + }) + $('a#new_form').live('tap',function(event){ + var rec = null; + form = get_form_html(); + html = "
                                                                              " + form + "
                                                                              "; + $('#form-create').replaceWith(html); + $('.form-header').replaceWith("
                                                                              New " + current_model + "
                                                                              ") + $('#form-create').page(); + $.mobile.changePage("#form-new", "slideup"); + }) + } + + function get_form_html(){ + if(current_model == 'Task') { + html += "
                                                                              \ + \ + \ + \ + \ +
                                                                              \ + \ +
                                                                              \ +
                                                                              \ + \ +
                                                                              \ + create \ +
                                                                              " + } + } + +This function calls get\_form\_data(), which constructs the html form to insert into the newly created page `form-new`. It then uses the place holder + `
                                                                              ` +to insert this html. After this + `$.mobile.changePage("#form-new", "slideup");` +is called and the form-new page defined above is loaded. + +### Map the Create Event + +In the function attach_events(), add another function to map the event that a user selects with the create button on the form. + + function attach_events() { + $('a#tasks').live('tap',function(event){ + pull_data('Task'); + }) + $('a#new_form').live('tap',function(event){ + var rec = null; + form = get_form_html(); + html = "
                                                                              " + form + "
                                                                              "; + $('#form-create').replaceWith(html); + $('.form-header').replaceWith("
                                                                              New " + current_model + "
                                                                              ") + $('#form-create').page(); + $.mobile.changePage("#form-new", "slideup"); + }) + $('#create').live('tap',function(event){ + create_obj(); + }) + } + +### Create the Data Object + +Then define the create\_obj() function. + + function create_obj(){ + var record = null; + + var model = RhoConnect.dataAccessObjects()[current_model]; + var f = $('#form-create').serializeArray() + record = new model(); + for(var i=0;i < f.length; i++) { + record[f[i].name] = f[i].value; + } + record['user_id'] = get_user_id(username); + persistence.add(record); + persistence.flush(); + persistence.saveToRhoConnect(function() { + alert("New " + current_model + " saved successfully!"); + }); + + $.mobile.changePage("#home", "slideup"); + } + +### Grab the Hash from the Data Object + +Inside of this function, grab the hash of the data object for the current\_model: in this case, current\_model = 'Task'. + + var model = RhoConnect.dataAccessObjects()[current_model]; + +### Create a New Model and Populate the Record Fields + +Now create a new model. + + record = new model(); + +The next loop populates the record fields. You will then add this new record to persistence. When modifications to objects have been made, persistence.js requires you to flush to database. This is done by calling persistence.flush. + + persistence.add(record); + persistence.flush(); + +### Save to RhoConnect + +The last step is to save to RhoConnect. + + persistence.saveToRhoConnect(function() { + alert("New " + current_model + " saved successfully!"); + }); + +At this point you have created a new object locally. To synch with your rhoconnect instance you need to call the sync() function described above at login. + +## Updating an Object + +Updating an object is very similar to creating an object. The code required to update an object is shown below. You can see all the UI functionality by looking at the complete project. + +Inside of application.js is a function named update\_object(). + + function update_object() { + var rec = null; + + var model = RhoConnect.dataAccessObjects()[current_model]; + var f = $('#form-create').serializeArray(); + var len = f.length - 1; + model.all().each(null, function(record){ + if(record._rhoId == f[len].value){ + rec = record; + return; + } + }) + if(rec != null) { + for(var i=0;i < f.length; i++) { + if(rec[f[i].name] != undefined && rec[f[i].name].match(/(_at)/) == null){ + rec[f[i].name] = f[i].value; + } + } + persistence.flush(); + persistence.saveToRhoConnect(function() { + alert(current_model + " updated successfully!"); + }); + } + else { + alert("error updating record"); + } + $.mobile.changePage("#home", "slideup"); + } + +You will notice this function is very similar to create\_object. The only difference is that a new model is not created. Instead a model is searched for, when found, its fields are assigned new values and the object is flushed and saved to Rhoconnect. You do not need to call `persistence.add(record)` in this case because the item already exists in the persistence hash. + +## Deleting an Object + +Deleting an object is exactly like creating an object except that instead of call `persistance.add(recored)`, you call `persistance.remove(record)`. The other calls to persistence and rhoconnect are the same. + + function delete_object(id){ + var model = RhoConnect.dataAccessObjects()[current_model]; + var del_rec = null; + model.all().each(null, function(record){ + if(record._rhoId == id){ + del_rec = record; + return; + } + }) + if(del_rec != null){ + persistence.remove(del_rec); + persistence.flush(); + persistence.saveToRhoConnect(function() { + alert(current_model + " deleted successfully!"); + }); + $.mobile.changePage("#home", "slideup"); + } + else { + alert('could not find record ' + id); + } + } \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectjs/getting-started.md b/docs/en/5.5/rhoconnectjs/getting-started.md new file mode 100644 index 00000000..a308a410 --- /dev/null +++ b/docs/en/5.5/rhoconnectjs/getting-started.md @@ -0,0 +1,90 @@ +RhoConnect.js Getting Started +=== +Here is a brief description on how to get started with RhoConnect.js. You may use code from +*samples/app-template* directory as a template to start your own application. + +## Getting Started +Load the `rhoconnect.js` library: + + + + + + + + + + + + +## Usage +To use rhoconnect.js, you need to login and initialize rhoconnect.js with model definitions as in the following example. + + function onSomeClick() { + loginRhoConnect("someUser", "somePass", false).done(function(){ + // start you business logic here, say.. + + var syncInterval = setInterval(function(){ + + RhoConnect.syncAllSources().done(function(){ + // performSomeRealWork(); + // updateSomeUI(); + }).fail(function(errCode, err){ + alert('Data sync error: ' +errCode); + clearInterval(syncInterval); + syncInterval = null; + }); + + }, 3 * 1000) + }); + } + + var modelDefinitions = [ + { + name: 'Customer', + fields: [ + {name: 'id', type: 'int'}, + {name: 'first', type: 'string'}, + {name: 'last', type: 'string'}, + {name: 'phone', type: 'string'}, + {name: 'email', type: 'string'}, + {name: 'address', type: 'string'}, + {name: 'city', type: 'string'}, + {name: 'state', type: 'string'}, + {name: 'zip', type: 'string'}, + {name: 'lat', type: 'string'}, + {name: 'long', type: 'string'} + ] + } + ]; + + function loginRhoConnect(username, password, doDataReset) { + return $.Deferred(function(dfr){ + + RhoConnect.login(username, password, + new RhoConnect.SyncNotification(), doDataReset).done(function(){ + + // Init DB for the user on success + RhoConnect.init(modelDefinitions /*, dataApiType, syncProgressCallback */).done(function(){ + dfr.resolve(); + }).fail(function(errCode, errMessage){ + alert('DB init error: ' +errCode); + dfr.reject(errCode, errMessage); + }); + + }).fail(function(errCode, err){ + alert('RhoConnect login error: ' +errCode); + dfr.reject(errCode, err); + }); + + }).promise(); + } + +You can use *RhoConnect.dataAccessObjects()* to obtain data API specific objects to access your data. See the [API reference](reference). \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectjs/introduction.md b/docs/en/5.5/rhoconnectjs/introduction.md new file mode 100644 index 00000000..9af36019 --- /dev/null +++ b/docs/en/5.5/rhoconnectjs/introduction.md @@ -0,0 +1,18 @@ +# RhoConnect.js Introduction +There is a JavaScript client library for the [RhoConnect](http://rhomobile.com/rhoconnect.html) App Integration Server. + +Using rhoconnect.js, your application's model data will transparently synchronize with a mobile application built using the [RhoElements framework](http://rhomobile.com/rhoelements.html), or any of the available [RhoConnect clients](http://rhomobile.com/rhoconnect.html). This client includes built-in support for the [SenchaTouch](http://www.sencha.com/) data API and [Persistence.js](http://persistencejs.org/) models. + +Rhoconnect.js is a completely UI-agnostic framework, so feel free to use any type of UI JavaScript library. + +Due to the CORS support in [RhoConnect](http://rhomobile.com/rhoconnect.html) server, you are able to create cross-domain applications and standalone mobile applications using the [PhoneGap](http://www.phonegap.com/) framework. + +It depends on the following jQuery libraries and plugins. +* [jQuery](http://jquery.com/) library. +* jQuery [Base64](http://github.com/carlo/jquery-base64) plugin. +* jQuery [JSON](https://sites.google.com/site/jollytoad/json.js?attredirects=0) plugin. + +Rhoconnect.js actively uses *deferred/promise* objects from jQuery API. All asynchronous results are returned as parameter values of the *done(..)* method call of the returned *promise* object. + +#### About +Created and maintained by Dmitry Prokhorov. Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). \ No newline at end of file diff --git a/docs/en/5.5/rhoconnectjs/reference.md b/docs/en/5.5/rhoconnectjs/reference.md new file mode 100644 index 00000000..800a5c21 --- /dev/null +++ b/docs/en/5.5/rhoconnectjs/reference.md @@ -0,0 +1,415 @@ +# RhoConnect.js API Reference + +RhoConnect.js API is implemented as public fields of a global *RhoConnect* object. Those are methods and *ERRORS* hash. + +If you have properties in the class, list and define them here. + +## login + +Returns a jQuery promise object. + +Authenticates the RhoConnect application on the server. On success, the done handler is called. On failure, the fail handler is called with the following arguments: + + * `errCode` - The error code value from RhoConnect.ERRORS. + * `errorMessage` - More detailed error message if available. + +The syntax and parameters are as follows. + + :::ruby + RhoConnect.login(username, password, doDataReset) + + + + + + + + + + + + + + +
                                                                              usernameThe user name to authenticate with.
                                                                              passwordThe password to authenticate with.
                                                                              doDataReset(optional) Boolean. If true, do a database reset before login. Default value is false.
                                                                              + +### Example + + function loginRhoConnect(username, password) { + persistence.store.rhoconnect.config(persistence); + return $.Deferred(function(dfr){ + // login with username, password, and a DB reset + RhoConnect.login(username, password, + new RhoConnect.SyncNotification(), true /*do db init*/).done(function(){ + // Init DB for the user on success + initRhoconnect(username, false).done(function(){ + dfr.resolve(); + }).fail(function(errCode, err){ + alert('DB init error: ' +errCode); + dfr.reject(errCode, err); + }); + }).fail(function(errCode, err){ + //alert('RhoConnect login error: ' +errCode); + dfr.reject(errCode, err); + }); + }).promise(); + } + +## init + +Performs rhoconnect.js and data API initialization. + +Returns a jQuery promise object. On success, the done handler is called. On failure, the fail handler is called with the following arguments: + + * `errCode` - The error code value from RhoConnect.ERRORS. + * `errorMessage` - More detailed error message if available. + +The syntax and parameters are as follows. + + :::ruby + RhoConnect.init(modelDefinitions, dataApiType, syncProgressCallback) + + + + + + + + + + + + + + +
                                                                              modelDefinitionsModel definitions array. See Getting Started for a sample.
                                                                              dataApiType(optional) - A string value: 'extjs', 'persistencejs', or 'custom' or null.

                                                                              + 'extjs' - Do initialize ExtJS/SenchaTouch data API to use as application data storage.
                                                                              + 'persistencejs' - Do initialize Persistence.js data API to use as application data storage.
                                                                              + 'custom' or null - Don't initialize any data API, perform data API initialization in custom code. +
                                                                              syncProgressCallback(optional) Progress update callback function to use. Receives the argument notificationBody, which is a hash with the following fields. + + + + + + + + + + + + + + + + + + + + + + + +
                                                                              sourceNameThe name of model just synchronized.
                                                                              totalCountThe total *objects* count for the *model*.
                                                                              processedCountThe number of *objects* that have been processed so far for a *model* may be *0* if all objects have already been processed.
                                                                              statusIs undefined while *inProgress* value is *true*. When finished it is a string value:
                                                                              + "ok" - Synchronization of exact model has been performed without errors.
                                                                              + "error" - Errors happened during synchronization process. +
                                                                              errorCodeCode of synchronization error. Is undefined if no errors happened. Look at RhoConnect.ERRORS description for details.
                                                                              errorMessageSynchronization error message. Is undefined if no errors happened.
                                                                              +
                                                                              + +### Example + + // RhoConnect.js initialization + function initRhoconnect(username, doReset) { + return RhoConnect.init(modelDefinitions, 'persistencejs', doReset); + } + +modelDefinitions is a hash, such as: + + var modelDefinitions = [ + { + name: 'User', + fields: [ + {name: 'username', type: 'string'}, + {name: 'email', type: 'string'}, + {name: 'first_name', type: 'string'}, + {name: 'last_name', type: 'string'}, + {name: 'title', type: 'string'}, + {name: 'company', type: 'string'}, + {name: 'created_at', type: 'string'}, + {name: 'updated_at', type: 'string'} + ] + }, + //... + +## logout + +Disconnects the RhoConnect application from the server. + +Returns a jQuery promise object. On success, the done handler is called. On failure, the fail handler is called with the following arguments: + + * `errCode` - The error code value from RhoConnect.ERRORS. + * `errorMessage` - More detailed error message if available. + +The syntax is as follows. + + :::ruby + RhoConnect.logout() + +## isLoggedIn + +Returns true if the application is logged in on the server. + + :::ruby + RhoConnect.isLoggedIn() + +## syncAllSources + +Synchronizes that application data with the RhoConnect server. + +Returns a jQuery promise object. On success, the done handler is called. On failure, the fail handler is called with the following arguments: + + * `errCode` - The error code value from RhoConnect.ERRORS. + * `errorMessage` - More detailed error message if available. + +The syntax is as follows. + + :::ruby + RhoConnect.syncAllSources() + +### Example + + function sync(){ + RhoConnect.syncAllSources().done(function(){ + alert('sync successful'); + }).fail(function(errCode, err){ + alert('Data sync error: ' +errCode); + }); + } + +## dataAccessObjects + +Returns the hash of data access objects which are data API specific. The returned hash contains: + + * `key` - model name. + * `value` - An instance of one of the following objects. + - [Ext.data.Store](http://dev.sencha.com/deploy/touch/docs/) - for 'extjs' type of data API + - [model](http://persistencejs.org/objects) - for 'persistencejs' type of data API + +The syntax is as follows. + + :::ruby + RhoConnect.dataAccessObjects() + +### Example + + function pull_data(model) { + // passed a model name, returns hash of data access objects. + var store = RhoConnect.dataAccessObjects()[model]; + + current_model = model; + persistence.loadFromRhoConnect(function() { + storeLoaded(); + }); + +## setModelNotification + +Set the handler for the exact model synchronization notification. + + :::ruby + RhoConnect.setModelNotification(modelName, callback, removeAfterFire) + + + + + + + + + + + + + + +
                                                                              modelNameName of the model to listen for notifications.
                                                                              callbackHandler function. Receives the only argument of notificationBody, which is a hash with the following fields. + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                              sourceNameThe name of the model just synchronized.
                                                                              totalCountThe total number of objects for the model.
                                                                              processedCountThe number of objects that have been processed so far for a model. 0 if all the objects have already been processed.
                                                                              statusIs undefined while inProgress is True. When finished, it is a string value.
                                                                              + "ok" if the synchronization of the exact model has been performed without errors.
                                                                              + "error" if errors happened during the synchronization process.
                                                                              errorCodeCode of synchronization error. Undefined if no errors happened. Look at the RhoConnect.ERRORS description for details.
                                                                              errorMessageSynchronization error message. Undefined if no errors happened.
                                                                              +
                                                                              removeAfterFireClear notification subscription after notification event if true. The same if handler function returns true.
                                                                              + +## clearModelNotification + +Resets the handler for the model synchronization notification. + + :::ruby + RhoConnect.clearModelNotification(modelName) + + + + + + +
                                                                              modelNameName of the model to reset the handler.
                                                                              + +## setAllNotification + +Sets the handler for all models synchronization notifications. + + :::ruby + RhoConnect.setAllNotification(callback, removeAfterFire) + + + + + + + + + + +
                                                                              callbackHandler function. Receives the only argument of notificationBody, which is a hash with the following fields. + + + + + + + + + + + + + + + +
                                                                              inProgressBoolean value. True if synchronization is still in progress, undefined if synchronization is finished.
                                                                              statusUndefined while the inProgress value is true. When synchronization is finished, it is a string value.
                                                                              + "complete" - Synchronization of all models have been performed without errors.
                                                                              + "error" - Errors happened during synchronization process. +
                                                                              errorCodeCode of the synchronization error. Undefined if no errors happened. Look at RhoConnect.ERRORS description for details.
                                                                              errorMessageSynchronization error message. Undefined if no errors happened.
                                                                              +
                                                                              removeAfterFireClear notification subscription after notification event if true. The same if handler function returns true.
                                                                              + +## clearAllNotification + +Reset handler for all models synchronization notifications. + + :::ruby + RhoConnect.clearAllNotification() + +## setObjectsNotification + +Set handler for all object change notifications. + + :::ruby + RhoConnect.setObjectsNotification(callback, removeAfterFire) + + + + + + + + + + +
                                                                              callbackHandler function. Receives the only argument of notificationBody, which is a hash with fields. + + + + + + + + + + + + + + + +
                                                                              updatedArray of hashes for updated objects. Every hash object has form of {objectId: objId, sourceId: srcId}, where:
                                                                              + objectId - The id of the updated object.
                                                                              + modelName - The name of the object model. +
                                                                              createdArray of hashes for created objects. Every hash object has form of {objectId: objId, sourceId: srcId}, where:
                                                                              + objectId - The id of the updated object.
                                                                              + modelName - The name of the object model. +
                                                                              deletedArray of hashes for deleted objects. Every hash object has form of {objectId: objId, sourceId: srcId}, where:
                                                                              + objectId - The id of the updated object.
                                                                              + modelName - The name of the object model. +
                                                                              +
                                                                              removeAfterFireClear notification subscription after notification event if true. The same if handler function returns true.
                                                                              + +## clearObjectsNotification + +Reset the handler for all object change notifications. + + :::ruby + RhoConnect.clearObjectsNotification() + +## addObjectNotify + +Subscribe an object for changes notification. + + :::ruby + RhoConnect.addObjectNotify(modelName, objectId) + + + + + + + + + + +
                                                                              modelNameThe name of the object model.
                                                                              objectIdThe id of the object.
                                                                              + +## clearObjectsNotify + +Unsubscribe all objects from changes notification. + + :::ruby + RhoConnect.clearObjectsNotify() + +## RhoConnect.ERRORS + +RhoConnect.ERRORS are defined as: + + * ERR\_NONE: 'No error' + * ERR\_NETWORK: 'Network error' + * ERR\_REMOTESERVER: 'Remote server access error' + * ERR\_RUNTIME: 'Runtime error' + * ERR\_UNEXPECTEDSERVERRESPONSE: 'Unexpected server response' + * ERR\_DIFFDOMAINSINSYNCSRC: 'Different synchronization domain error' + * ERR\_NOSERVERRESPONSE: 'No server response' + * ERR\_CLIENTISNOTLOGGEDIN: 'Client not logged in' + * ERR\_CUSTOMSYNCSERVER: 'Custom sync server' + * ERR\_UNATHORIZED: 'Unauthorized access' + * ERR\_CANCELBYUSER: 'Canceled by user' + * ERR\_SYNCVERSION: 'Synchronization version error' + * ERR\_GEOLOCATION: 'Geolocation error' diff --git a/docs/en/5.5/toc.rb b/docs/en/5.5/toc.rb new file mode 100644 index 00000000..1ef48889 --- /dev/null +++ b/docs/en/5.5/toc.rb @@ -0,0 +1,256 @@ + +section 'getting-started', 'Introduction','Mobile Guides' do + topic 'en/5.5/guide/welcome', 'Welcome to RhoMobile Suite' + topic 'en/5.5/guide/rhoArchitecture', 'Supported Platforms' + topic 'en/5.5/guide/devskills', 'Developer Skills' + topic 'en/5.5/guide/devenvironment', 'Developer Environments' + topic 'en/5.5/guide/appdesign', 'App Architecture' + topic 'en/5.5/guide/uichoices', 'UI Architecture' + topic 'en/5.5/guide/kitchensink', 'KitchenSink Application' + topic 'en/5.5/guide/apiusage', '2.2 Migration Guide' + topic 'en/5.5/guide/api_js', 'RhoMobile JavaScript Usage' + topic 'en/5.5/guide/api_ruby', 'RhoMobile Ruby Usage' + topic 'en/5.5/guide/licensing', 'Licensing' +end + +section 'rhodescommonapi-reference', 'API Reference','Mobile API Docs' do + topic 'en/5.5/guide/apisummary', 'RhoMobile API Summary' + topic 'en/5.5/api/Application', 'Application' + topic 'en/5.5/api/audiocapture', 'AudioCapture' + topic 'en/5.5/api/barcode', 'Barcode' + topic 'en/5.5/api/battery', 'Battery' + topic 'en/2.2.0/rhodesapi/bluetoothmanager-api', 'BluetoothManager' + topic 'en/2.2.0/rhodesapi/bluetoothsession-api', 'BluetoothSession' + topic 'en/5.5/api/camera', 'Camera' + topic 'en/5.5/api/cardreader', 'CardReader' + topic 'en/2.2.0/rhoelements/comm', 'Comm' + topic 'en/5.5/api/Config', 'Config' + # topic 'en/2.2.0/rhoelements/contact', 'Contact' + topic 'en/5.5/api/Database', 'Database' + topic 'en/5.5/api/device', 'Device' + topic 'en/5.5/api/geolocation', 'Geolocation' + topic 'en/5.5/api/Intent', 'Intent' + topic 'en/5.5/api/keycapture', 'KeyCapture' + topic 'en/5.5/api/keystate', 'KeyState' + topic 'en/5.5/api/Log', 'Log' + topic 'en/2.2.0/rhodesapi/mapview-api', 'MapView' + topic 'en/5.5/api/mediaplayer', 'Mediaplayer' + topic 'en/5.5/api/NativeMenubar', 'NativeMenubar' + topic 'en/5.5/api/NativeTabbar', 'NativeTabbar' + topic 'en/5.5/api/NativeToolbar', 'NativeToolbar' + topic 'en/5.5/api/Navbar', 'Navbar' + topic 'en/2.2.0/rhodesapi/NdefMessage-api', 'NdefMessage' + topic 'en/2.2.0/rhodesapi/NdefRecord-api', 'NdefRecord' + topic 'en/5.5/api/Network', 'Network' + topic 'en/2.2.0/rhodesapi/NFCManager-api', 'NFCManager' + topic 'en/2.2.0/rhodesapi/NFCTag-api', 'NFCTag' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology_IsoDep-api', 'NFCTagTechnology_IsoDep' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology_MifareClassic-api', 'NFCTagTechnology_MifareClassic' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology_MifareUltralight-api', 'NFCTagTechnology_MifareUltralight' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology_Ndef-api', 'NFCTagTechnology_Ndef' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology_NdefFormatable-api', 'NFCTagTechnology_NdefFormatable' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology_NfcA-api', 'NFCTagTechnology_NfcA' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology_NfcB-api', 'NFCTagTechnology_NfcB' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology_NfcF-api', 'NFCTagTechnology_NfcF' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology_NfcV-api', 'NFCTagTechnology_NfcV' + topic 'en/2.2.0/rhodesapi/NFCTagTechnology-api', 'NFCTagTechnology' + topic 'en/5.5/api/Notification', 'Notification' + topic 'en/5.5/api/Orm', 'ORM JavaScript' + topic 'en/5.5/api/rhom-api', 'ORM Ruby' + topic 'en/5.5/api/OrmModel', 'ORM Model JavaScript' + topic 'en/5.5/api/printing', 'Printer' + # topic 'en/5.5/api/printingepson', 'Printing Epson' + topic 'en/5.5/api/printingzebra', 'Printer Zebra' + topic 'en/5.5/api/push', 'Push' + topic 'en/5.5/api/RhoConnectClient', 'RhoConnectClient' + topic 'en/2.2.0/rhodesapi/rhocontact-api', 'RhoContact' + topic 'en/2.2.0/rhodesapi/rhocontroller-api', 'RhoController' + topic 'en/2.2.0/rhodesapi/rhoerror-api', 'RhoError' + topic 'en/2.2.0/rhodesapi/rhoevent-api', 'RhoEvent' + topic 'en/5.5/api/File', 'RhoFile' + topic 'en/2.2.0/rhodesapi/rhomsource-api', 'RhomSource' + topic 'en/2.2.0/rhodesapi/rhoprofiler-api', 'RhoProfiler' + topic 'en/2.2.0/rhodesapi/rhoutils-api', 'RhoUtils' + topic 'en/5.5/api/screenorientation', 'ScreenOrientation' + topic 'en/5.5/api/sensor', 'Sensor' + topic 'en/5.5/api/smartcradle', 'SmartCradle' + topic 'en/5.5/api/signalindicators', 'SignalIndicators' + topic 'en/5.5/api/signature', 'Signature' + topic 'en/2.2.0/rhodesapi/signaturecapture-api', 'SignatureCapture (Inline)' + topic 'en/5.5/api/system', 'System' + topic 'en/5.5/api/Timer', 'Timer' + # topic 'en/5.5/api/videocapture', 'Video Capture' + # topic 'en/5.5/api/websocket', 'WebSocket' + topic 'en/5.5/api/webview', 'WebView' +end + +section 'rhomob-setup', 'Dev Environment Setup','Mobile Guides' do + topic 'en/5.5/guide/rhomobile-install', 'RhoMobile Suite Install' + topic 'en/5.5/guide/nativesdksetup', 'Native SDK Setup' + topic 'en/5.5/guide/nonrhostudio', 'Developing Without RhoStudio' + topic 'en/5.5/guide/visualstudio', 'Developing with Visual Studio' +end + +section 'rhomob-apps', 'Developing Apps','Mobile Guides' do + topic 'en/5.5/guide/creating_a_project', 'Starting a New Project' + topic 'en/5.5/guide/runtime_config', 'Runtime Configuration' + topic 'en/5.5/guide/build_config', 'Buildtime Configuration' + topic 'en/5.5/guide/viewport', 'Viewport Configuration' + topic 'en/5.5/guide/build_ios', 'Build for iOS' + topic 'en/5.5/guide/build_android', 'Build for Android' + topic 'en/5.5/guide/build_wm', 'Build for Windows Mobile' + topic 'en/5.5/guide/build_wp8', 'Build for Windows Phone 8' + topic 'en/5.5/guide/build_win', 'Build for Windows' + topic 'en/5.5/guide/using_emulators', 'Using Native Emulators' + topic 'en/5.5/guide/app_icon_splash', 'Application Icon & Splash Screen' + topic 'en/5.5/guide/css-framework', 'CSS Frameworks' + topic 'en/5.5/guide/webapps', 'RhoMobile for Web Apps' + topic 'en/5.5/guide/webcontainer', 'Custom Web App Container' + topic 'en/5.5/guide/app_upgrade', 'Upgrading Your App' + topic 'en/5.5/guide/live-update', 'Live Update' +end + +section 'rhomob-data', 'Data Handling','Mobile Guides' do + topic 'en/5.5/guide/local_database', 'Local Database and Rhom' + topic 'en/5.5/guide/rhom_ruby', 'Using Rhom with Ruby' + topic 'en/5.5/guide/rhom_js', 'Using Rhom with JavaScript' + topic 'en/5.5/guide/rhom_backbone', 'Using Rhom with Backbone.JS' + topic 'en/5.5/guide/rhom_angular', 'Using Rhom with Angular JS' + topic 'en/5.5/guide/synchronization', 'Synchronization' + topic 'en/5.5/guide/web_services', 'Web Services & AJAX' +end + +section 'rhomob-dev', 'Device Capabilities','Mobile Guides' do + topic 'en/5.5/guide/barcode', 'Barcode' + topic 'en/5.5/guide/bluetooth', 'Bluetooth' + topic 'en/5.5/guide/camera', 'Camera' + topic 'en/5.5/guide/pim', 'Contacts & Calendar' + topic 'en/5.5/guide/controlling_webview_behavior', 'Controlling Webview Behavior' + topic 'en/5.5/guide/device_hardware_key_handling', 'Device Notifications & Keylight' + topic 'en/5.5/guide/device_information_and_abilities', 'Detecting Device Abilities' + topic 'en/5.5/guide/hardware_accleration', 'Hardware Acceleration' + topic 'en/5.5/guide/html5', 'Html5 Tags' + topic 'en/5.5/guide/handling_local_files', 'File System' + topic 'en/5.5/guide/geolocation', 'Geolocation' + topic 'en/5.5/guide/intent', 'Intents' + topic 'en/5.5/guide/localization', 'Localization' + topic 'en/5.5/guide/maps', 'Mapping' + topic 'en/5.5/guide/media', 'Media & Ringtones' + topic 'en/5.5/guide/native_ui_elements', 'Native UI Components' + topic 'en/5.5/guide/interfacing_with_the_network', 'Network Interfacing' + topic 'en/2.2.0/rhodes/nfc', 'NFC' + topic 'en/5.5/guide/screen_orientation', 'Orientation and Responsive Design' + topic 'en/5.5/guide/printing', 'Printing' + topic 'en/5.5/guide/push_notifications', 'Push Notifications' + topic 'en/5.5/guide/device_sensors', 'Sensors' + topic 'en/5.5/guide/signature', 'Signature' + topic 'en/5.5/guide/urlschemes', 'URL Schemes' +end + +section 'rhomob-test', 'Testing & Debugging','Mobile Guides' do + topic 'en/5.5/guide/debugging_ruby', 'Debugging Ruby' + topic 'en/5.5/guide/debugging_js', 'Debugging JavaScript' + topic 'en/5.5/guide/logging', 'Logging' + topic 'en/5.5/guide/testing', 'Testing' + topic 'en/5.5/guide/profiling', 'Performance Profiling' + +end + +section 'rhomob-ext', 'Extending','Mobile Guides' do + topic 'en/5.5/guide/native_extensions', 'Extending the Rhodes Framework' + topic 'en/5.5/guide/ruby_extensions', 'Ruby Native Extensions' + topic 'en/5.5/guide/rho_ruby', 'Rhomobile Ruby' + topic 'en/5.5/guide/view_extensions', 'View Extensions' +end + +section 'rhoconnect-reference', 'Getting Started','RhoConnect Guides' do + topic 'en/5.5/rhoconnect/introduction', 'Introduction' + topic 'en/5.5/rhoconnect/install', 'Installation' + topic 'en/5.5/rhoconnect/migration', 'Migrating to RhoConnect 5.0' + topic 'en/5.5/rhoconnect/command-line', 'App Generator and Command Line' + topic 'en/5.5/rhoconnect/supported-platforms', 'Supported Platforms' + topic 'en/5.5/rhoconnect/rhoconnect-calculator', 'RhoConnect Calculator' +end + +section 'rhoconnect-source-adapter-reference', 'Source Adapters','RhoConnect Guides' do + topic 'en/5.5/rhoconnect/source-adapters-intro', 'Introduction' + topic 'en/5.5/rhoconnect/source-adapters', 'Source Adapters (Ruby)' + topic 'en/5.5/rhoconnect/source-adapters-js', 'Source Adapters (JavaScript)' + topic 'en/5.5/rhoconnect/authentication', 'Adding Device Authentication' + topic 'en/5.5/rhoconnect/testing', 'Testing and Debugging' + topic 'en/5.5/rhoconnect/blob-sync', 'Binary Objects and Blob Sync' + topic 'en/5.5/rhoconnect/async-jobs', 'Adapter Jobs with Resque' + topic 'en/5.5/rhoconnect/metadata', 'Dynamic Views with Metadata' + topic 'en/5.5/rhoconnect/data-partitioning', 'Data Partitioning & Pass-Through' +end + +section 'rhoconnect-ruby-api-reference', 'Source Adapter Ruby APIs','RhoConnect Guides' do + topic 'en/5.5/rhoconnectapi/source-adapter-controller-api-ruby', 'Source Adapter Controller API' + topic 'en/5.5/rhoconnectapi/source-adapter-model-api-ruby', 'Source Adapter Model API' + topic 'en/5.5/rhoconnectapi/source-adapter-store-api-ruby', 'Source Adapter Store API' + topic 'en/5.5/rhoconnectapi/test-api-ruby', 'Source Adapter Test API' +end + +section 'rhoconnect-js-api-reference', 'Source Adapter JS APIs','RhoConnect Guides' do + topic 'en/5.5/rhoconnectapi/source-adapter-controller-api-js', 'Source Adapter Controller API' + topic 'en/5.5/rhoconnectapi/source-adapter-model-api-js', 'Source Adapter Model API' + topic 'en/5.5/rhoconnectapi/source-adapter-request-api-js', 'Source Request API' + topic 'en/5.5/rhoconnectapi/source-adapter-response-api-js', 'Source Response API' + topic 'en/5.5/rhoconnectapi/source-adapter-store-api-js', 'Source Adapter Store API' + topic 'en/5.5/rhoconnectapi/source-adapter-exception-api-js', 'Source Adapter Exception API' +end + +section 'rhoconnect-plugin-reference', 'Plugins','RhoConnect Guides' do + topic 'en/5.5/rhoconnect/plugin-intro', 'Introduction' + topic 'en/5.5/rhoconnect/rails-plugin', 'Rails Plugin' + topic 'en/5.5/rhoconnect/net-plugin', '.Net Plugin' + topic 'en/5.5/rhoconnect/java-plugin', 'Java Plugin' +end + +section 'rhoconnect-push-reference', 'Push Sync','RhoConnect Guides' do + topic 'en/5.5/rhoconnect/push', 'Introduction to Push' + topic 'en/5.5/rhoconnect/push-client-setup-rps', 'Setup for RhoConnect Push Service' + topic 'en/5.5/rhoconnect/push-client-setup-android', 'Setup for Android' + topic 'en/5.5/rhoconnect/push-client-setup-ios', 'Setup for iOS' + topic 'en/5.5/rhoconnect/push-client-setup', 'Finishing Setup for all Clients' + topic 'en/5.5/rhoconnect/push-backend-setup', 'Setup on Backend' + topic 'en/5.5/rhoconnect/push-testing', 'Testing Push' +end + +section 'rhoconnect-administration', 'Administration','RhoConnect Guides' do + topic 'en/5.5/rhoconnect/settings', 'RhoConnect Settings' + topic 'en/5.5/rhoconnect/web-console', 'Admin Web Interface' +topic 'en/hosted/guide/licensing-rhoconnect', 'Licensing your RhoConnect App' + topic 'en/5.5/rhoconnect/benchmarks', 'Rhoconnect Benchmarking' + topic 'en/5.5/rhoconnect/benchmarks-running', 'Running Rhoconnect Benchmarks' + topic 'en/5.5/rhoconnect/stats-middleware', 'Collecting Runtime Stats' +end + +section 'rhoconnect-deployment', 'Deployment','RhoConnect Guides' do + topic 'en/5.5/rhoconnect/preparing-production', 'Preparing for Production' + # topic 'en/5.5/rhoconnect/hosting-rhohub', 'Hosting on RhoHub' + topic 'en/5.5/rhoconnect/deploying', 'Deploying RhoConnect' + topic 'en/5.5/rhoconnect/rhoconnect-redis-stack', 'High Availability Deployment on AWS' +end + +section 'rhoconnect-advanced', 'Advanced Topics','RhoConnect Guides' do + topic 'en/5.5/rhoconnect/bulk-sync', 'Big Datasets and Bulk Sync' + topic 'en/5.5/rhoconnect/extending-rhoconnect-server', 'Extending Rhoconnect App with custom routes' + topic 'en/5.5/rhoconnect/cud-conflicts', 'Resolving Conflicts' +end + +section 'rhoconnect-nonrhodes-client-reference', 'Clients','RhoConnect Guides' do + topic 'en/5.5/rhoconnect/client', 'Using RhoConnect without Rhodes' + topic 'en/5.5/rhoconnect/rest-api', 'RhoConnect REST API' + topic 'en/5.5/rhoconnect/client-objc', 'RhoConnect Client for iOS' + topic 'en/5.5/rhoconnect/client-java', 'RhoConnect without Rhodes: Android Java' + topic 'en/5.5/rhoconnectjs/introduction', 'RhoConnect.JS Client' + topic 'en/5.5/rhoconnectjs/getting-started', 'RhoConnect.JS Getting Started' + topic 'en/5.5/rhoconnectjs/reference', 'RhoConnect.JS API Reference' + topic 'en/5.5/rhoconnectjs/creating-app', 'RhoConnect.JS Creating an App' +end + +section 'rhoconnect-adapters-reference', 'Vendor Adapters','RhoConnect Guides' do + topic 'en/5.5/rhoconnect/adapters-intro', 'Introduction' + topic 'en/5.5/rhoconnect/adapters-crm', 'CRM adapters' +end \ No newline at end of file diff --git a/docs/en/5.5/tutorial/emberjs.md b/docs/en/5.5/tutorial/emberjs.md new file mode 100644 index 00000000..b0bec579 --- /dev/null +++ b/docs/en/5.5/tutorial/emberjs.md @@ -0,0 +1,28 @@ +# EmberJS Tutorial + +In this tutorial we will be walking through using Ember.JS with your RhoMobile Application. EmberJS is one of many JavaScript MVC based frameworks that allow you to build very responsive mobile applications. Along with the [EmberJS website](http://emberjs.com/guides/), there are many resources out on the Internet that cover EmberJS in great detail. This tutorial will cover some of the very basics of the framework to get you started using it with RhoMobile. We will be a very simple application to perform CRUD operations on a model representing our Products model. + +As you work through the tutorial you will: + +* Create a basic Hello Ember JS App +* Create a Single Page App using Ember JS to include CRUD views for a Data Model +* Integrate Rhom with Ember JS through an adapter to persist the data + +##Working with the Tutorial +The tutorial relies on the use of Git versioning system for source code management. You don't need to know anything about Git to follow the tutorial. But you will need to make sure your environment is setup with Git (this is included by default when you install RhomMobile Suite). + +You'll need Git, which you can get from the [Git site](). + +Clone the rhotut-emberjs repository located at Github by running the following command: + + git clone https://github.com/rhomobile/rhotut-emberjs.git + +This command creates the rhotut-emberjs directory in your current directory. + +Change your current directory to rhotut-emberjs: + + cd rhotut-emberjs + +The tutorial instructions, from now on, assume you are running all commands from the `rhotut-emberjs` directory. + +You can choose to use RhoStudio for editing the files or your own text editor of choice. In the beginning of the tutorial we will just be using a browser and then will be using RhoStudio to build our RhoMobile application. For a browser it is recommended that you use Google Chrome as well as install the Ember JS Chrome add on that we will explain later. \ No newline at end of file diff --git a/docs/en/5.5/tutorial/emberjs.step-0.md b/docs/en/5.5/tutorial/emberjs.step-0.md new file mode 100644 index 00000000..360716b3 --- /dev/null +++ b/docs/en/5.5/tutorial/emberjs.step-0.md @@ -0,0 +1,115 @@ +# EmberJS Tutorial + +Let's get started by resetting our environment to the starting point of our project. As you go through the steps in this tutorial you will easily be able to reset your environment by typing in a special git command that will change the file contents to be equal to what the code should look like when you are done with this step. You will also be able to easily see the differences between each step that was made. + +1) In your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-0 + +2) Now take the `index.html` file that is found in the `public` folder and drag it into your browser + + +Not very exciting, but if you type in the input box you will see the Hello message change automatically. +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+10.35.12+AM.jpg) + +## The HTML +Let's explain what is going on here by first taking a look at `index.html` + + :::js + + + + + + RhoMobile Ember + + + + + + + + + + + + + + + + + + + + + +## The JavaScript +Since this is a JavaScript based application let's first take a look at the JavaScript Files we are referencing. + +To use EmberJS, we will be including the following libraries. + :::js + + + + + +* jquery - is being used by Ember and our app for DOM access +* handlebars - is required by Ember JS as it's templating engine +* ember - is the core Ember JS library +* ember-data - is being will be used for our data models and to tie in with Rhom (this is actually not required at this stage and will be explained later) + +Bootstrap is not required but is just being used for layout control and styling + :::js + + +Then we will be using a file to hold some of our application specific code + :::js + + +And inside of `app.js` we see one very simple line of code. + :::js + App = Ember.Application.create(); + +## The CSS +We have included two styling libraries that we will be using to make this app a bit more appealing. These are non-impactful to this tutorial and you could have easily chosen to use your own CSS or styling libraries + + :::js + + + +## The App +There is much more to an Ember application then what we have produced so far but let's explain the first fundamental thing going on here: + + :::js + + +The ` + +This view assumes that it will be backed by an array of models, that we will define an explain later. It uses the Handlebars `{{each}}` script block to iterate through each instance. Inside the `{{each}}` block, the model will have attributes: `name`, `brand` and `qty`, that will be displayed inside each `
                                                                            • ` tag. + +Now if we refresh our browser we will see that nothing happens. There is still some work that needs to be done which leads us to the next concept; Routes + +## Creating a route +Ember.js considers the URL as the center of your application and will parse it to figure out which part of the application should be activated. A side effect of that is that you must tell Ember.js which URLs your application will react to; there are two concepts that the Router in Ember.js knows about: routes and resources. + +A route is just what you would expect: you tell the router that the application knows about a particular URL and Ember.js takes care of the rest. Creating a top-level route is straightforward: + + :::js + App.Router.map(function() { + this.route("welcome"); + }); + +This creates a route named "welcome" that will load a template with the same name and be handled by App.WelcomeRoute and App.WelcomeController whenever you visit /welcome. If you do not define WelcomeRoute or WelcomeController in your code, Ember.js will generate them for you automatically, so you can create routes with simple views very easily. + +The other construct is what Ember.js calls a "resource", which is nothing more than a route that can have sub-routes. Let's say we want to have a "/products" route that shows a list of products and we also want to edit the details of a particular product at "/products/1234". We will add the code for the edit later, so let's just start by defining the resource for the `products` route by adding the following code in the `app.js file: + + :::js + App.Router.map(function() { + this.resource('products', {path: '/'}, function(){ + + }); + }); + +Based on [Ember naming conventions](http://emberjs.com/guides/concepts/naming-conventions/) navigating to the default url for the app will look for a template that is has an id of 'products': which we created a view for above ` + +You will notice that we removed the `input` and the `

                                                                              ` section and added the `{{outlet}}`. This is where the views will be rendered. Refreshing the browser will now display the `products` view that we defined above. + +Well you only see the `Products` text being displayed because there is no data. Let's add some test data so we can see how this view will look. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+2.41.10+PM.jpg) + +## Adding Data Fixtures + +Let's go back to the `js/models/product.js` file and add the following: + :::js + App.Product.FIXTURES = [ + { + id: 1, + name: '328i', + brand: 'BMW', + qty: 5, + isavailable: true + }, + { + id: 2, + name: '528i', + brand: 'BMW', + qty: 3, + isavailable: true + }, + { + id: 3, + name: '728i', + brand: 'BMW', + qty: 0, + isavailable: false + }, + ]; + +## Associating model to route +In Ember, every route has an associated model. This model is set by implementing a route's model hook. Let's keep our code tidy and create a `js/routes` folder and then create a file for our Product routes called `product.js` + + :::js + App.ProductsIndexRoute = Ember.Route.extend({ + model: function () { + return App.Product.FIXTURES + } + }); + +If we refresh the page at this point nothing will have changed since we haven't loaded the newly created files into our index.html file. Let's ad the necessary code to load these into our `/public/js/index.html`. + + :::html + + + +Ember's naming conventions come into play again here. Recall that we defined our view as `data-template-name="products/index"`. To ember this is really `product.index` and it will automatically look for a corresponding `ProductsIndexRoute` and `ProductIndexController` definitions and use them if they are there. Notice that camel casing and appending of `Route` and `Controller`. This is a double edge sword in that if you mistype you application won't work, but can be very useful once you get the hang of it since it saves you from writing a lot of code. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+2.44.10+PM.jpg) + +Refreshing the browser should now show the fixture data in the list and we can see the template repeat for each instance of the model. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+2.49.26+PM.jpg) + +In the next step, we will add the ability to create new records. diff --git a/docs/en/5.5/tutorial/emberjs.step-2.md b/docs/en/5.5/tutorial/emberjs.step-2.md new file mode 100644 index 00000000..3f9b92f5 --- /dev/null +++ b/docs/en/5.5/tutorial/emberjs.step-2.md @@ -0,0 +1,181 @@ +# EmberJS Tutorial + +In this step of the tutorial we will add a new view for creating records and as well as defining a controller to hook in the actions from the form. + +To reset your workspace to where the last step left off, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-1 + + +To jump ahead and complete this section, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-2 + +## Defining a 'partial' +Our application will allow for creating of new products as well as editing existing ones. Since we would like to share the same form and not have to create duplicate templates to maintain, we have decided to create what is called a partial. This is denoted by using the underscore prefixing the name : `_productForm` + +`public/index.html` + :::js + + +And then our `productnew` template will reference the `productForm` partial we just defined: + + :::js + + +When this view is used it will replace the `{{partial "productForm"}}` section with the contents of the productForm template. We will show how the Edit view will use this in the next step of the tutorial + +## Add route for New +We then will add a route for the view so that browsing to `productnew` will show this page + + +`public/js/app.js` + :::js + App.Router.map(function() { + // put your routes here + this.resource('products', {path: '/'}, function(){ + this.resource('productnew'); + }); + }); + +## Helper functions +We can now go back to our Products list template and add a button that will load this view + +`public/index.html` + :::js + + +Keeping with the Ember naming conventions this controller will be for the `productnew` view and will likewise be called `ProductnewController`. It is of type `Ember.ObjectController` because it will be bound to our product model. Inside this method we pass in an object that defines it's behavior. + +### actions +The actions section of the parameter defines what actions will be available to this controller. This will allow us to easily tie a button to some JS that needs to run. In this controller, we have a Save button that needs to save the model we just created in the form. From the form we reference the `save` action like: + +`public/index.html - _productForm template created above` + :::js + + +Clicking this button will cause the `save` action code to be triggered where we get the data from the form and then create a new record using `this.store.createRecord` which has the first parameter representing the model name: `product`, followed by a JavaScript object that contains the attribute name and corresponding value pairs. Once the object is created, we call the `.save()` method to save the new record. + +## Saving Records +At this point when we are saying saving, deleting, etc it is in the Ember SPA sense - where it is saved for the current session. We have not tied any persistance to these models so it neither saves it in Rhom or on a backend. If you refresh the web page you will not see any new or updated data. + +We will get into this concept in great detail later in the tutorial. This will involve the concept of `Adapters`. Adapters are built to store the model data somewhere through an interface you define called an `Adapter`. Later in the tutorial we will create one for saving the records to the Rhom database. Ember also comes with a RESTAdapter that allows you to save the data on a backend using REST APIs. For this step in the tutorial we will be using the `FixtureAdapter` that is also built in. It will allow us to `save` to the Fixture object we created earlier. + +Let's start by changing the `public/js/models/product.js` file and add the following line: + + :::js + App.ApplicationAdapter = DS.FixtureAdapter.extend(); + +This tells our application that we want the models to use this adapter when modifying a record. + +Then in the `public/js/routes/product.js` file instead of returning App.Product.Fixtures, we actually want to utilize the store method and get the list of products from the Ember Data Store. This will allow us to change the `Adapter` later to something else and not have to change this code. + +`public/js/routes/product.js` + :::js + App.ProductsIndexRoute = Ember.Route.extend({ + model: function () { + return this.store.find('product'); + } + + }); + +Now when we create new records they will be added to our Fixture array and be displayed in the list. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+3.55.23+PM.jpg) + +NOTE: Here is where the Ember inspector comes in handy. From the screen-shot above you can see that I can actually see the data that the view is using to display the records. + +In the next step of the tutorial we will show how to Edit records. \ No newline at end of file diff --git a/docs/en/5.5/tutorial/emberjs.step-3.md b/docs/en/5.5/tutorial/emberjs.step-3.md new file mode 100644 index 00000000..e4b9a784 --- /dev/null +++ b/docs/en/5.5/tutorial/emberjs.step-3.md @@ -0,0 +1,120 @@ +# EmberJS Tutorial + +In this step of the tutorial we will re-use the partial view we created before and add defining a controller to hook in the actions to update the record. + +To reset your workspace to where the last step left off, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-2 + + +To jump ahead and complete this section, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-3 + +## Re-Using the Create Record view 'partial' +In the previous step in the tutorial, we created a New product page that used the partial view called: `_productForm`. So creating a new page to handle product updates will be very easy. We simply create a new template called `productedit` and reference the partial using: `{{partial "productForm"}}` + +`public/index.html` + :::js + + +Notice that we also have `Edit {{name}}` - this will show the name of the current product that we are editing. It will do this automatically, because we will be binding this form to the same product model + +## Add a route for Edit +We then will add a route for this view so it can be used later. Notice in this case we define the url to contain a variable called `:product_id`. This defines that the url scheme to edit a product will look something like `#productedit/1234` where `1234` will the id of the record. + + +`public/js/app.js` + :::js + App.Router.map(function() { + // put your routes here + this.resource('products', {path: '/'}, function(){ + this.resource('productnew'); + this.resource('productedit', { path: ':product_id' }); + }); + }); + +## Using the edit route +We can now go back to our Products list template and wrap the product item in the list with a link to this view: + +`public/index.html` + :::js + + +Notice that the `{{link-to}}` helper function references `productedit` and also includes another parameter called `this`. The `this` will be replaced by the current model record's id from the data store. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+4.16.58+PM.jpg) + +If we look in the Web Inspector we will see that the `href` is now pointing to `#/1` for our first item in the list. The `1` corresponds to the id that our data store has for this record. Recall that this is coming from the `App.Product.FIXTURES` object right now. + +## Binding the route to the model +Before we attempt to run this, we still have to bind the route to the model, so that the view will have a reference to a particular record. + +Add the following to: +`public/js/routes/product.js` + :::js + App.ProductsEditRoute = Ember.Route.extend({ + model: function(params) { + return this.store.findBy('id',params.product_id); + + } + }); + +Remember that the url will be appended with a parameter called `product_id` as we defined in the `App.Router` above. So when the ProductsEditRoute is called, it will retrieve the `params.product_id` and then use the `this.store.findBy()` method to get a reference to that record. This record will now be bound through the `model` object to the form. + +## Adding a controller +Like with the New page, we have to add a controller for the Edit page so we can perform actions like updating the record. Open up the `public/js/controllers/product.js` and paste the following code: + +`public/js/controllers/product.js` + :::js + App.ProducteditController = Ember.ObjectController.extend({ + actions: { + save: function () { + var isavailable = $('#isavailable').is(':checked'); + + this.set('isavailable',isavailable); + this.get('model').save(); + this.transitionTo('products'); + } + } + }); + +Keeping with the Ember naming conventions this controller will be for the `productedit` view and will therefore be called `ProducteditController`. + +### actions +Recall that this view is using the same partial that the ProductnewController is, therefore we have to define a `save` action to account for the user clicking on the `save button`: + +`public/index.html - _productForm template` + :::js + + +Since the view has a checkbox control we have to read the current value from the page using jQuery and then set the attribute using `this.set()` method. Otherwise we would just have to execute `this.get.('model').save()` method. + +You should now be able to update the models' data. Notice that when you change the name of the product, it automatically changes the `Edit {{name}}` section on the form. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+4.37.40+PM.jpg) + +In the next step of the tutorial, we will add delete capabilities. \ No newline at end of file diff --git a/docs/en/5.5/tutorial/emberjs.step-4.md b/docs/en/5.5/tutorial/emberjs.step-4.md new file mode 100644 index 00000000..77645963 --- /dev/null +++ b/docs/en/5.5/tutorial/emberjs.step-4.md @@ -0,0 +1,94 @@ +# EmberJS Tutorial + +In this step of the tutorial we will add a delete record view and defining a controller to hook in the actions to delete the record. + +To reset your workspace to where the last step left off, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-3 + + +To jump ahead and complete this section, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-4 + +## Adding a delete view +Like in the other pages, we will be adding a new view for prompting the user before deleting. Add the following template to the `index.html` page: + +`public/index.html` + :::js + + +Notice that again we will be binding this template to a model and will display some of the models attributes like `{{brand}}` and `{{name}}`. We also hook the `Cancel` button back to the `products` link. And like the Edit and New template we have an action button, but this time will be calling the `delete` action, which we will explain shortly. + +## Add a route for Delete +We then update our `App.Router` to include this new reference. Notice that this time, for the sake of the tutorial, we show a different way to specify the url scheme. For delete, the url will be something like `#/1234/delete`. + +`public/js/app.js` + :::js + App.Router.map(function() { + // put your routes here + this.resource('products', {path: '/'}, function(){ + this.resource('productnew'); + this.resource('productedit', { path: ':product_id' }); + this.resource('productdelete', { path: '/:product_id/delete' }); + }); + }); + +## Using the edit route +We can now go back to our Products list template and add a button in the list to link to this `productdelete` route: + +`public/index.html - products/index template` + :::js + ... +

                                                                            • + {{#link-to 'productdelete' this}} + {{/link-to}} + {{#link-to 'productedit' this}} + {{qty}} + {{name}} - {{brand}} + {{/link-to}} +
                                                                            • + ... + +Notice that the `{{link-to}}` helper function references `productdelete` and also includes another parameter called `this`. The `this` will be replaced by the current model record's id from the data store. + +If we look in the Web Inspector we will see that the `href` is now pointing to `#/3/delete` for our third item in the list. The `3` corresponds to the id that our data store has for this record. Recall that this is coming from the `App.Product.FIXTURES` object right now. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+4.53.23+PM.jpg) + +And clicking in the delete button will navigate to the delete template we just created. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+4.52.35+PM.jpg) + +## Adding a controller +Like with the New and Edit pages, we have to add a controller for the Delete page so we can perform the delete action. Open up the `public/js/controllers/product.js` and paste the following code: + +`public/js/controllers/product.js` + :::js + App.ProductdeleteController = Ember.ObjectController.extend({ + actions: { + delete: function () { + var product = this.get('model'); + product.deleteRecord(); + product.save(); + this.transitionTo('products'); + } + } + }); + +Keeping with the Ember naming conventions this controller will be for the `productdelete` view and will therefore be called `ProductdeleteController`. + +The `delete` action uses the `deleteRecord()` and `.save()` methods to remove the record reference from the Ember Data store. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+5.00.48+PM.jpg) + +You have now successfully created a Ember JS CRUD app for a data model. In the next step of the tutorial, we will add some actions to the products list to update the quantity without even changing the view. \ No newline at end of file diff --git a/docs/en/5.5/tutorial/emberjs.step-5.md b/docs/en/5.5/tutorial/emberjs.step-5.md new file mode 100644 index 00000000..efdc9d2b --- /dev/null +++ b/docs/en/5.5/tutorial/emberjs.step-5.md @@ -0,0 +1,63 @@ +# EmberJS Tutorial + +In this step of the tutorial we will update the quantity attribute of the record right from the list without having to change the view. + +To reset your workspace to where the last step left off, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-4 + + +To jump ahead and complete this section, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-5 + +## Adding Up/Down Buttons +Let's add two new buttons to the `
                                                                            • ` tag in the products list that we will create actions for: + +`public/index.html` + + :::js +
                                                                            • + {{#link-to 'productdelete' this}}{{/link-to}} + {{#link-to 'productedit' this}} + {{qty}} + {{name}} - {{brand}} + {{/link-to}} + + +
                                                                            • + +We are basically pointing to a `up` and `down` action that we will need to create. Notice that this is not a `{{link-to}}` because we do not wan't to change views, but what we do want is to actually update the models qty that the data store has. We will have to wire these actions into the the `App.ProductsIndexRoute` object and pass in the reference to the model via the `this` object. + +## Adding Actions +We will now add the actions to the `ProductsIndexRoute`. + +`public/js/routes/product.js` + :::js + App.ProductsIndexRoute = Ember.Route.extend({ + model: function () { + return this.store.find('product'); + }, + actions: { + up: function(m) { + m.set('qty',parseInt(m.get('qty')) + 1); + m.save(); + }, + down: function(m) { + m.set('qty',parseInt(m.get('qty')) - 1); + m.save(); + } + } + + }); + +The `up` action will contain a reference to the model via the passed in parameter `m`. We can then set the qty attribute using `m.set('qty',newQty)`, likewise for the `down` action, followed by a `m.save()` call to save the updates to the store. + +If you click on the item to bring up the edit view, you should see the new value represented. Also if you have installed Ember Chrome Inspector you can also look at the data tab. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-18+at+6.21.51+PM.jpg) + + +So far we have created a model, defined routes, views and controllers to deliver a basic application that performs CRUD operations on data. This data however is non-persistent and any changes made in this application will be reset when reloading the page. + +In the next step in the tutorial we will be bringing this application into RhoMobile and create a Ember Adapter that will automatically handle keeping the Ember model data persistent in Rhom. This will be very useful if your user scenario requires being disconnected from your backend or if you plan on using RhoConnect for data synchronization. If you plan on keeping all of your data on your backend, then you will need to plug in some other adapter like the RestAdapter. We will not cover these topics in this tutorial as you can find these on the Internet. \ No newline at end of file diff --git a/docs/en/5.5/tutorial/emberjs.step-6.md b/docs/en/5.5/tutorial/emberjs.step-6.md new file mode 100644 index 00000000..b868f4b5 --- /dev/null +++ b/docs/en/5.5/tutorial/emberjs.step-6.md @@ -0,0 +1,308 @@ +# EmberJS Tutorial + +In this step of the tutorial we will bring this application into RhoMobile and create a Rhom Adapter that can be used for any Ember-Rhom application. + +To reset your workspace to where the last step left off, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-5 + + +To jump ahead and complete this section, in your `rhotut-emberjs` directory, type the following command: + + git checkout -f step-6 + +## Creating the RhoMobile App +Open up RhoStudio and create a new RhoMobile Application + +1. File / New Project +2. Select `RhoMobile Application` +3. Enter a name for the project and click `Finish` +4. After the project is built - replace the contents of the `Public` folder with the contents of the `Public` folder we have been using so far. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-19+at+10.12.36+AM.jpg) + +## Running the Ember App in RhoMobile +Now, change the `start_path` setting in the `rhoconfig.txt` file so that it will use `/public/index.html' Ember application we have been creating. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-19+at+10.19.33+AM.jpg) + +Create a `Run Configuration` for this project. + +1. Run / Run Configurations +2. Click New Launch Configuration / RhoMobile Application +3. Select your project in the `Project Name` field +4. Select `RhoSimulator` for the `Simulator Type` field +5. Click `Run` + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-19+at+10.22.45+AM.jpg) + +You will now see the Ember application running inside of the RhoSimulator + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-19+at+10.25.32+AM.jpg) + +## Defining the Rhom Model +In order to use the Rhom Adapter that we will build, we first must define the model using the RhoMobile ORM JavaScript APIs: + +`public/js/models/product.js` + :::js + Rho.ORM.addModel(function(model){ + model.modelName("Product"); + }); + +The key here is to use the same exact name as we did when we defined the model in Ember: `App.Product`. You will notice that in the Rhom definition we did not define any fields. This is because we are using a `PropertyBag` definition (aka: Schema-less). This will allow us to add any attribute we want later by simply changing the model definition in Ember: + + :::js + App.Product = DS.Model.extend({ + name: DS.attr('string'), + brand: DS.attr('string'), + qty: DS.attr('number'), + isavailable: DS.attr('boolean'), + myNewField: DS.attr('string') + }); + +## Rhom Adapter +Create a new folder called `adapters` and copy the following code into a file called `rhom.js`. This will be the Ember Adapter for keeping the Ember data persistent using Rhomobile's Rhom. + +`public/js/adapters/rhom.js` + :::js + DS.RhomAdapter = DS.Adapter.extend(Ember.Evented, { + + extractVars: function(rhomRecord) { + data = rhomRecord.vars(); + //need to convert bool since Rhom stores as string + // ember bind-attr works only with bools + for (var key in data) { + if(data[key] == 'true'){ + data[key] = true; + } + if(data[key] == 'false'){ + data[key] = false; + } + } + return data; + }, + + objectToId: function(record) { + record["id"] = record.object; + return Ember.copy(record); + }, + + find: function(store, type, id) { + var record = Rho.ORM.getModel(this.model).find( + 'first', + { + conditions: {object: id} + } + ); + var result = record.vars(); + result["id"] = result.object; + return Ember.RSVP.resolve(result); + }, + + findAll: function(store, type) { + var records = Rho.ORM.getModel(this.model).find('all'); + var results = records.map(this.extractVars); + var results = results.map(this.objectToId); + var promise = new Ember.RSVP.Promise(function(resolve, reject){ + // succeed + resolve(results); + // or reject + reject([]); + }); + return promise; + }, + + createRecord: function(store, type, record) { + var json = record.toJSON(); + thisRecord = Rho.ORM.getModel(this.model).create(record.toJSON()); + json.id = thisRecord.get('object'); + return Ember.RSVP.resolve(json); + }, + + updateRecord: function(store, type, record) { + var result = Rho.ORM.getModel(this.model).find('first', {conditions: {object: record.get('id')}}); + result.updateAttributes(record.toJSON()); + return Ember.RSVP.resolve(); + }, + + deleteRecord: function(store, type, record) { + var result = Rho.ORM.getModel(this.model).find('first', {conditions: {object: record.get('id')}}); + result.destroy(); + return Ember.RSVP.resolve(); + } + }); + +Before we forget let's also update our `index.html` to include this new file in the list of JavaScript references. Be sure to place the adapter before the reference to the `models/product.js` file: + +`public/index.html` + :::js + + + + + +[Ember DS.Adapter](http://emberjs.com/api/data/classes/DS.Adapter.html) is a base class that we will override. These adapters require the minimum methods: + +* find() +* createRecord() +* updateRecord() +* deleteRecord() + +We will also include a method to find all records (for our product index page) as well as two helper functions that the RhomAdapter will use. + +* findAll() +* extractVars() +* objectToId() + +### find() +The `find()` method will be called when Ember attempts to retrieve a reference to a record of the model. The id of the record will be passed to this method. + + :::js + find: function(store, type, id) { + +We will use this `id` to look up the record in Rhom, using [RhoMobile ORM JavaScript APIs](../../api/Orm). The model name will be available in this method through the `this.model` variable and we will use the `.getModel()` Rhom method to get a reference to that model. The model needs to be defined in Rhom using the same name as we defined our Ember model in order for this to work (as we did in this beginning of this page). Since Rhom uses the `object` property as its unique id for the model, we will look up the record by checking for `object` = `id`. + + :::js + var record = Rho.ORM.getModel(this.model).find( + 'first', + { + conditions: {object: id} + } + ); +Once a record is found we have to return an object that matches how it was defined in Ember, ex: + + :::js + { + id: 1, + name: '328i', + brand: 'BMW', + qty: 5, + isavailable: true + } + +We accomplish this by calling the `.vars()` Rhom method that converts it to an object and then add the property `id` to this object, since that is what Ember expects: + + :::js + var result = record.vars(); + result["id"] = result.object; + return Ember.RSVP.resolve(result); + +### createRecord() +The `createRecord()` method in the adapter needs to create a record in Rhom and then return the `id` of the record that was created. This is accomplished using the `.create()` Rhom method and passing in the object as a JSON object. We then set the `id` field of the Rhom unique id field `object` and return the `json` object. + + :::js + createRecord: function(store, type, record) { + var json = record.toJSON(); + thisRecord = Rho.ORM.getModel(this.model).create(record.toJSON()); + json.id = thisRecord.get('object'); + return Ember.RSVP.resolve(json); + }, + +### updateRecord() +The `updateRecord()` method in the adapter looks very similar to the `createRecord()` method. Instead of creating a record we will first find the record and then use the `updateAttributes()` Rhom method for updating the attributes of the object by just passing in the full object (all fields will be updated). + + :::js + updateRecord: function(store, type, record) { + var result = Rho.ORM.getModel(this.model).find('first', {conditions: {object: record.get('id')}}); + result.updateAttributes(record.toJSON()); + return Ember.RSVP.resolve(); + }, + +### deleteRecord() +The `deleteRecord()` method in the adapter will find a reference to the record and then using the `.destroy()` Rhom method to remove the record from the Rhom database. + + :::js + deleteRecord: function(store, type, record) { + var result = Rho.ORM.getModel(this.model).find('first', {conditions: {object: record.get('id')}}); + result.destroy(); + return Ember.RSVP.resolve(); + } + +### findAll() +The `findAll()` method will need to return an array of objects that will look similar to our fixture array we used in the beginning of this tutorial. It relies on some slight massaging of the record set, using some helper functions we will explain next, before returning the results. + + :::js + findAll: function(store, type) { + var records = Rho.ORM.getModel(this.model).find('all'); + var results = records.map(this.extractVars); + var results = results.map(this.objectToId); + var promise = new Ember.RSVP.Promise(function(resolve, reject){ + // succeed + resolve(results); + // or reject + reject([]); + }); + return promise; + }, + +### extractVars() +The `extractVars()` method in the adapter will convert the Rhom record into a structure JavaScript object like we did in the `createRecord()` method. Since Rhom stores everything as strings we need to perform converting of boolean types to a true boolean JavaScript type. Otherwise Ember's data binding will not work correctly. + + :::js + extractVars: function(rhomRecord) { + data = rhomRecord.vars(); + //need to convert bool since Rhom stores as string + // ember bind-attr works only with bools + for (var key in data) { + if(data[key] == 'true'){ + data[key] = true; + } + if(data[key] == 'false'){ + data[key] = false; + } + } + return data; + }, + +### objectToId() +The `objectToId()` method simply always ensures that the Rhom `object` field is being used as the `id` field that Ember Data will be using. + + :::js + objectToId: function(record) { + record["id"] = record.object; + return Ember.copy(record); + }, + +## Enabling the Rhom Adapter +Now that we have the adapter built and the Rhom model defined, we just need to change our Adapter definition for our `Product` model: + +`public/js/models/product.js` + :::js + //App.ApplicationAdapter = DS.FixtureAdapter.extend(); + + App.ProductAdapter = DS.RhomAdapter.extend({ + model: "Product" + }); + +You can see that again, Ember naming conventions kick in: `App.ProductAdapter` is automatically recognized as the Adapter for the model `Product`. This is how we would be able to use the same adapter for multiple models in our project, if we had them. + +## Enabling RhoMobile JavaScript API's +In order to use the Rhom JS APIs that we used in our adapter, we need to add reference to the RhoMobile JS file: `rhoapi-modules.js` that gets built when we build the application. This file will automatically be created and placed in the `/public/api` folder. It needs to be included before the `jquery` library: + +`public/index.html` + :::js + + + + + + + + + +**NOTE: If you are going to be using the JS ORM API, you'll also need to include this line in any files that will be using it: ``** + +## Persistent Data +Now we should have all of the pieces we need to keep our data persistent using Rhom as the storage mechanism though the Ember `RhomDataAdapter`. If you relaunch the application, you will first see that there are no products in the list: + + +Well, this is normal. Recall that we are now using Rhom as the storage, so the initial loading of the app will not have any record in the database. Create some new records and then relaunch the app and you will see that updates to data will be maintained. + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-19+at+10.43.08+AM.jpg) + +And if we look at the RhoSimulatr Web Inspector and inspect an element in the product list page. We can see that the URL scheme is still working and is using the Rhom Object id numbers in the URL, ex: + + :::js + .... + +![](https://s3.amazonaws.com/rhodocs-images/rhotut-emberjs/Screen+Shot+2013-11-19+at+10.47.24+AM.jpg) \ No newline at end of file diff --git a/docs/en/5.5/tutorial/nocode.1.md b/docs/en/5.5/tutorial/nocode.1.md new file mode 100644 index 00000000..f966d131 --- /dev/null +++ b/docs/en/5.5/tutorial/nocode.1.md @@ -0,0 +1,5 @@ +# No Code tut + +Step1 + +## Section 1 \ No newline at end of file diff --git a/docs/en/5.5/tutorial/nocode.2.md b/docs/en/5.5/tutorial/nocode.2.md new file mode 100644 index 00000000..06d1c467 --- /dev/null +++ b/docs/en/5.5/tutorial/nocode.2.md @@ -0,0 +1,5 @@ +# No Code tut + +Step2 + +## Section 1 \ No newline at end of file diff --git a/docs/en/5.5/tutorial/nocode.3.md b/docs/en/5.5/tutorial/nocode.3.md new file mode 100644 index 00000000..47b67085 --- /dev/null +++ b/docs/en/5.5/tutorial/nocode.3.md @@ -0,0 +1,5 @@ +# No Code tut + +Step3 + +## Section 1 \ No newline at end of file diff --git a/docs/en/5.5/tutorial/nocode.md b/docs/en/5.5/tutorial/nocode.md new file mode 100644 index 00000000..f3308194 --- /dev/null +++ b/docs/en/5.5/tutorial/nocode.md @@ -0,0 +1,6 @@ +# No Code tut + +This example tutorial does not have any tie into Git or code + +## Section 1 +Here is some text \ No newline at end of file diff --git a/docs/en/edge/guide/apisummary.md b/docs/en/edge/guide/apisummary.md index 6739f84c..69bea5ab 100644 --- a/docs/en/edge/guide/apisummary.md +++ b/docs/en/edge/guide/apisummary.md @@ -1,15 +1,11 @@ # RhoMobile API Summary -Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recommended for all new projects. If you're moving a 2.x app to 5.x, please consult the [2.x migration guide](apiusage). +Below is a list of the new common APIs for RhoMobile Suite 5.5, which are recommended for all new projects. If you're moving a 2.x app to 5.x, please consult the [2.x migration guide](apiusage). -## 5.3 APIs +## 5.5 APIs

                                                                              - - API/platform is supported; no license required -

                                                                              -

                                                                              - - - API/platform is supported; paid subscription required for production use + - API/platform is supported

                                                                              @@ -38,13 +34,13 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -70,7 +66,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -83,35 +79,35 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + - + Barcode - - - - - + + + + + @@ -120,11 +116,11 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm Battery - - - - - + + + + + @@ -135,7 +131,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -148,7 +144,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -161,7 +157,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -174,7 +170,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -185,34 +181,34 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm CardReader - + - - + + - + Config - + @@ -224,9 +220,9 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm Config * - - - + + + @@ -236,10 +232,10 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm Contact - - - - + + + + @@ -251,7 +247,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -263,25 +259,25 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + - + @@ -289,20 +285,20 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + - + @@ -328,7 +324,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -339,35 +335,35 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm KeyCapture - - - - - + + + + + - + KeyState - - - + + + @@ -380,7 +376,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -393,7 +389,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -406,25 +402,25 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + - + @@ -432,7 +428,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -445,7 +441,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -458,7 +454,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -510,19 +506,19 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + - + @@ -731,7 +727,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -744,7 +740,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -755,9 +751,9 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm Printer - - - + + + @@ -768,9 +764,9 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm Printer Zebra - - - + + + @@ -783,20 +779,20 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + - + @@ -836,7 +832,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -849,7 +845,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -862,7 +858,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -875,7 +871,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -888,7 +884,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -901,7 +897,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -914,7 +910,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -927,7 +923,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -940,7 +936,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -953,7 +949,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -966,7 +962,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -977,11 +973,11 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm SignalIndicators - - - - - + + + + + @@ -990,11 +986,11 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm Signature - - - - - + + + + + @@ -1004,10 +1000,10 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm SignatureCapture (inline) * - - - - + + + + @@ -1017,25 +1013,25 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + - + @@ -1043,25 +1039,25 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + - + @@ -1069,7 +1065,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -1082,20 +1078,20 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + --> - + @@ -1134,7 +1130,7 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm - + @@ -1143,15 +1139,13 @@ Below is a list of the new common APIs for RhoMobile Suite 5.3, which are recomm -**These API classes are implemented in RhoMobile Suite 2.2 but are not yet included in the new Common API class set for RhoMobile Suite 5.3. They use the older 2.2 format and support Ruby only except as noted.* +**These API classes are implemented in RhoMobile Suite 2.2 but are not yet included in the new Common API class set for RhoMobile Suite 5.5. They use the older 2.2 format and support Ruby only except as noted.* -**NOTE: When using 2.2 APIs in RhoMobile 5.3, the [2.2 API compatibility matrix](../../2.2.0/rhoelements/apicompatibility) applies.** +**NOTE: When using 2.2 APIs in RhoMobile 5.5, the [2.2 API compatibility matrix](../../2.2.0/rhoelements/apicompatibility) applies.** -## Licensing -APIs in the table above that are indicated with the icon require silver- or gold-level licensing for use in production. For details, please refer to the [Licensing Guide](licensing). ### JavaScript APIs -To use the JavaScript APIs in RhoElements 2.2, **you must add the `public/js/rho_javascript_api.js` file to the .html, .erb, or .js file that's calling the JavaScript method**. This file is created at build time as part of the application package and can coexist with RhoMobile 5.3 JavaScript API file `rhoapi-modules.js`. However, it has been altered from the version built using 2.2, and must be regenerated to allow it to properly coexist with other files of your 5.3 app. +To use the JavaScript APIs in RhoElements 2.2, **you must add the `public/js/rho_javascript_api.js` file to the .html, .erb, or .js file that's calling the JavaScript method**. This file is created at build time as part of the application package and can coexist with RhoMobile 5.5 JavaScript API file `rhoapi-modules.js`. However, it has been altered from the version built using 2.2, and must be regenerated to allow it to properly coexist with other files of your 5.5 app. ### JavaScript ORM @@ -1185,7 +1179,7 @@ Toward the goal of supplying a Common API format for both JavaScript and Ruby, t The 2.2 RhoElement APIs are supported only on Zebra WebKit, which is still available on Windows Mobile/CE and Android platforms. The APIs for 5.x support the stock Android WebKit by default. ### Rhodes 2.2 APIs -2.2 Rhodes APIs that were not replaced by an equivalent RhoMobile 5.3 API (ex: Camera) are supported on all platforms that were supported previously. Ruby APIs will behave exactly as they did before. Note that some of the Rhodes 2.2 APIs provided JavaScript support but used a different version of the RhoMobile JavaScript API library: `rho_javascript_api.js` +2.2 Rhodes APIs that were not replaced by an equivalent RhoMobile 5.5 API (ex: Camera) are supported on all platforms that were supported previously. Ruby APIs will behave exactly as they did before. Note that some of the Rhodes 2.2 APIs provided JavaScript support but used a different version of the RhoMobile JavaScript API library: `rho_javascript_api.js` To generate this file you must enable JavaScript by putting `rho-javascript` into extensions in your build.yml. diff --git a/docs/en/edge/guide/apiusage.md b/docs/en/edge/guide/apiusage.md index 8f4dbdda..15b91857 100644 --- a/docs/en/edge/guide/apiusage.md +++ b/docs/en/edge/guide/apiusage.md @@ -1,27 +1,27 @@ -# Migrating Your RhoMobile App to v5.3 +# Migrating Your RhoMobile App to v5.4 RhoMobile Suite 5.x and higher offers a set of common APIs to access device, system and framework capabilities from your JavaScript and Ruby code. ## RhoConnect Client -In RhoMobile Suite 5.3, the [RhoConnectClient API](../api/rhoconnectclient) is accessed through an extension. To use the RhoConnect Client, you must specify `rhoconnect-client` in the extensions section of your application's `build.yml` (as below). If you are using RhoConnect, you should also consult the [RhoConnect Migration Guide](../rhoconnect/migration) for details about migrating your RhoConnect application. +In RhoMobile Suite 5.4, the [RhoConnectClient API](../api/rhoconnectclient) is accessed through an extension. To use the RhoConnect Client, you must specify `rhoconnect-client` in the extensions section of your application's `build.yml` (as below). If you are using RhoConnect, you should also consult the [RhoConnect Migration Guide](../rhoconnect/migration) for details about migrating your RhoConnect application. :::ruby extensions: ["rhoconnect-client"] ## Android WebKit -RhoMobile Suite 5.3 now uses the stock Android WebKit included with the Android SDK you're building with as the default. Version 5.x RhoElement APIs will work only with the stock WebKit. However, [pre-5.x RhoElement APIs](#using-22-apis) **must be used with the Zebra WebKit for Android**. +RhoMobile Suite 5.4 uses the stock Android WebKit included with the Android SDK you're building with as the default. Version 5.x RhoElement APIs will work only with the stock WebKit. However, [pre-5.x RhoElement APIs](#using-22-apis) **must be used with the Zebra WebKit for Android**. ## Shared Runtime RhoMobile Suite 2.0 included the RhoElements Shared Runtime, a pre-built RhoMobile application that provided application configuration options for the Zebra WebKit and RhoElements API extensions. This allowed HTML/JS applications to run without requiring the developer to build a separate a RhoMobile application. -Since the RhoMobile suite 5.3 no longer includes a pre-built shared runtime, it is recommended that you build a simple RhoMobile application to point to your HTML application. This will allow you to optimize the application by including only the extensions and capabilities used by your application. +Since the RhoMobile suite 5.4 no longer includes a pre-built shared runtime, it is recommended that you build a simple RhoMobile application to point to your HTML application. This will allow you to optimize the application by including only the extensions and capabilities used by your application. ## JavaScript Licensing -RhoMobile Suite 5.3 increases the number of APIs with JavaScript access from prior versions. In addition, JavaScript licensing restrictions associated with some APIs and the Zebra WebKit are removed, and are now in sync with those of Ruby. Licensing restrictions are now at the API class level rather than the language level. For example, use of the Camera API is now free on JavaScript *and* Ruby. [Read more about licensing](licensing). +RhoMobile Suite 5.4 increases the number of APIs with JavaScript access from prior versions. In addition, JavaScript licensing restrictions associated with some APIs and the Zebra WebKit are removed, and are now in sync with those of Ruby. Licensing restrictions are now at the API class level rather than the language level. For example, use of the Camera API is now free on JavaScript *and* Ruby. [Read more about licensing](licensing). ## API Platform Support -It is the intention for all APIs to work across all supported platforms. In RhoMobile Suite 2.2, support for platforms was indicated using an [API compatibility matrix](../../2.2.0/rhoelements/apicompatibility) at the API class level. Version 5.3 contains fewer exceptions, and the platforms that are supported will be indicated at the individual API property or method level. Please [refer to the API Summary](apisummary) for an overview. +It is the intention for all APIs to work across all supported platforms. In RhoMobile Suite 2.2, support for platforms was indicated using an [API compatibility matrix](../../2.2.0/rhoelements/apicompatibility) at the API class level. Version 5.4 contains fewer exceptions, and the platforms that are supported will be indicated at the individual API property or method level. Please [refer to the API Summary](apisummary) for an overview. ## Replaced APIs New APIs that have replaced those previously available will be highlighted in the menus and descriptions of the API reference documentation, as below: @@ -326,9 +326,9 @@ Same as Webview class in 2.2. Also C ## Using 2.2 APIs -Below is a list of API classes available in RhoMobile Suite 2.2 and have not yet have been incorporated in the new Common API class set for RhoMobile Suite 5.3. These APIs are still available in the 2.2 format. The following API classes will be incorporated into furture versions of the RhoMobile Suite so as to supply a common API format for in both JavaScript and Ruby. +Below is a list of API classes available in RhoMobile Suite 2.2 and have not yet have been incorporated in the new Common API class set for RhoMobile Suite 5.4. These APIs are still available in the 2.2 format. The following API classes will be incorporated into furture versions of the RhoMobile Suite so as to supply a common API format for in both JavaScript and Ruby. -**NOTE: When using 2.2 APIs in RhoMobile 5.3, the [2.2 API compatibility matrix](../../2.2.0/rhoelements/apicompatibility) still applies.** +**NOTE: When using 2.2 APIs in RhoMobile 5.4, the [2.2 API compatibility matrix](../../2.2.0/rhoelements/apicompatibility) still applies.** * [Mapview](../../2.2.0/rhodesapi/mapview-api) * [Contacts](../../2.2.0/rhodesapi/rhocontact-api) @@ -353,17 +353,17 @@ Below is a list of API classes available in RhoMobile Suite 2.2 and have not yet * [Reboot](../../2.2.0/rhoelements/reboot) ### RhoElements 2.2 APIs -The 2.2 RhoElement APIs are supported on Zebra WebKit only. This WebKit is still available on Windows Mobile/CE and some Android platforms, but the default for 5.3 is the stock Android WebKit. +The 2.2 RhoElement APIs are supported on Zebra WebKit only. This WebKit is still available on Windows Mobile/CE and some Android platforms, but the default for 5.4 is the stock Android WebKit. ### Rhodes 2.2 APIs -2.2 Rhodes APIs that were not replaced by an equivalent RhoMobile 5.3 API (ex: Camera) are supported on all platforms that were supported previously. Ruby APIs will behave exactly as they did before. Note that some of the Rhodes 2.2 APIs provided JavaScript support, but used a different version of the RhoMobile JavaScript API library: `rho_javascript_api.js`. +2.2 Rhodes APIs that were not replaced by an equivalent RhoMobile 5.4 API (ex: Camera) are supported on all platforms that were supported previously. Ruby APIs will behave exactly as they did before. Note that some of the Rhodes 2.2 APIs provided JavaScript support, but used a different version of the RhoMobile JavaScript API library: `rho_javascript_api.js`. To generate this file, you must enable JavaScript by including `rho-javascript` in the extensions section of your `build.yml` file. :::yaml extensions: ["rho-javascript"] -To use the JavaScript API, **you must add the `public/js/rho_javascript_api.js` file to the .html, .erb, or .js file that's calling the JavaScript method**. This file is created at build time as part of the application package and can coexist with RhoMobile 5.3 the JavaScript API file `rhoapi-modules.js`. However, it has been altered from the version built using 2.2, and must be regenerated to allow it to properly coexist with other files of your 5.3 app. +To use the JavaScript API, **you must add the `public/js/rho_javascript_api.js` file to the .html, .erb, or .js file that's calling the JavaScript method**. This file is created at build time as part of the application package and can coexist with RhoMobile 5.4 the JavaScript API file `rhoapi-modules.js`. However, it has been altered from the version built using 2.2, and must be regenerated to allow it to properly coexist with other files of your 5.4 app. ### JavaScript ORM @@ -375,7 +375,7 @@ If you're using the JavaScript ORM API, include this line in any files that will ## Backward Compatibility ### RhoElements Meta Tags -Meta tags that are specific to RhoElements should continue to function in a RhoMobile 5.3 application, as long as its `build.yml` contains the following: +Meta tags that are specific to RhoElements should continue to function in a RhoMobile 5.4 application, as long as its `build.yml` contains the following: :::yaml app_type: 'rhoelements' @@ -392,7 +392,7 @@ Use instead: Rho.Barcode.enable(); ### RhoElements JavaScript APIs -JavaScript APIs that are specific to RhoElements should continue to function in a RhoMobile 5.3 application, as long as its `build.yml` contains the following: +JavaScript APIs that are specific to RhoElements should continue to function in a RhoMobile 5.4 application, as long as its `build.yml` contains the following: :::yaml app_type: 'rhoelements' @@ -405,27 +405,27 @@ Old format: scanner.enable() // should still work New format: - Rho.Barcode.enable() // the current 5.3 equivalent + Rho.Barcode.enable() // the current 5.4 equivalent ### Parameter ordering -In a few rare cases, an API in version 2.2 has the same naming as in 5.3, but the ordering of parameters may have changed. For example: +In a few rare cases, an API in version 2.2 has the same naming as in 5.4, but the ordering of parameters may have changed. For example: :::ruby # In RhoMobile 2.2 Params are callback, paramHash - # This will fail in a 5.3 application + # This will fail in a 5.4 application Rho::Barcode.enable(url_for(:action => :barcode_callback), {:camera => 'front'}) - # In RhoMobile 5.3 Params are now paramHash, callback + # In RhoMobile 5.4 Params are now paramHash, callback Rho::Barcode.enable( {:camera => 'front'},url_for(:action => :barcode_callback)) -In all new 5.3 API classes, callbacks are now specified as the last parameter. +In all new 5.4 API classes, callbacks are now specified as the last parameter. -**NOTE: The benefit of converting these APIs to the current 5.3 methods includes support for additional combinations of supported operating systems and platforms. There also are several [new ways of accessing](api_js) these APIs through instance objects and special common methods that were not implemented previously.** +**NOTE: The benefit of converting these APIs to the current 5.4 methods includes support for additional combinations of supported operating systems and platforms. There also are several [new ways of accessing](api_js) these APIs through instance objects and special common methods that were not implemented previously.** ### API behavior on Page change -In version 2.2, some APIs by default will reset the device they control when navigating between app pages. In 5.3, the devices are not reset between page navigations, but is left in the previous state. Therefore, it will be up to the application to control behavior on page load. +In version 2.2, some APIs by default will reset the device they control when navigating between app pages. In 5.4, the devices are not reset between page navigations, but is left in the previous state. Therefore, it will be up to the application to control behavior on page load. -For example, if a 2.2 application activates the barcode scanner on Page1 with a callbackhandler, navigating to a page with no scanner will disable it. Depending on the desired behavior, an equivalent 5.3 app must handle the setting or disabling of the scanner on page load. +For example, if a 2.2 application activates the barcode scanner on Page1 with a callbackhandler, navigating to a page with no scanner will disable it. Depending on the desired behavior, an equivalent 5.4 app must handle the setting or disabling of the scanner on page load. ## Removed APIs The following APIs are no longer included in the RhoMobile Suite: diff --git a/docs/en/edge/guide/build_config.md b/docs/en/edge/guide/build_config.md index cd9cd1f6..29fd6efc 100644 --- a/docs/en/edge/guide/build_config.md +++ b/docs/en/edge/guide/build_config.md @@ -193,7 +193,7 @@ The following are some non-default settings that you may add to the build.yml in   js: yes
                                                                                css: yes
                                                                                exclude_dirs: ["jqmobile", "jqtouch", "jquery"] - NOTE: The jqmobile, jqtouch, and jquery folders must be excluded when obfuscation is enabled, because the obfuscated versions of these libraries are there already. + NOTE: Add to exclude_dirs all javascript libraries that are obfuscated already. If JavaScript or CSS code obfuscation is not required, then just omit js or css line accordingly. obfuscate:
                                                                              @@ -209,14 +209,13 @@ The following are some non-default settings that you may add to the build.yml in   js: true
                                                                                css: true
                                                                                exclude_dirs: ["jqmobile", "jqtouch", "jquery"] - NOTE: The jqmobile, jqtouch, and jquery folders must be excluded when minification is enabled. + NOTE: Add to exclude_dirs all javascript libraries that are minimized already. If JavaScript or CSS code minification is not wanted, then just omit js or css line accordingly. minify:
                                                                                js: false
                                                                                css: false
                                                                              -   exclude_dirs: ["jqmobile", "jqtouch", "jquery"] diff --git a/docs/en/edge/guide/creating_a_project.md b/docs/en/edge/guide/creating_a_project.md index 9398a532..974ccb96 100644 --- a/docs/en/edge/guide/creating_a_project.md +++ b/docs/en/edge/guide/creating_a_project.md @@ -116,9 +116,6 @@ Holds the stylesheets for your app's pages.
                                                                              `/public/images`
                                                                              Image files for toolbars, lists, 'OK' and 'Back' buttons, etc.
                                                                              -`/public/jqmobile`
                                                                              -Files for [JQuery Mobile](http://jquerymobile.com), a JavaScript library that helps you build touch-optimized HTML applications for mobile devices.
                                                                              - `/public/jquery`
                                                                              Files for [JQuery](http://jquery.com), a cross-browser JavaScript library for manipulating HTML with an easy-to-use syntax.
                                                                              diff --git a/docs/en/edge/guide/nonrhostudio.md b/docs/en/edge/guide/nonrhostudio.md index 014ab6f6..08b2cacc 100644 --- a/docs/en/edge/guide/nonrhostudio.md +++ b/docs/en/edge/guide/nonrhostudio.md @@ -37,10 +37,17 @@ After you install the gem and your desired SDKs, you need to run: This will prompt you for where you installed the SDKs for the various platforms. The installation script will display its best guess as to where the SDK is. You can then enter a new location, or leave it blank to use the suggestion. If you are not building for a specific platform (for example, you can't build for the iPhone on Windows), you can leave that SDK location blank. ## Generating A Rhodes Application -The first step is to generate the application and base files. First we will generate an application called StoreManager with the following command: +The first step is to generate the application and base files. First we will generate an application called StoreManager. + +For generating the ruby-based application use the following syntax: :::term $ rhodes app storemanager http://localhost:9292/application + +For generating the javascript-based application use the following syntax: + + :::term + $ rhodes jsapp storemanager http://localhost:9292/application This will generate an application directory called "storemanager" with several files. Note also that the third argument above is the URL to the RhoConnect server data source (required if you want to do synchronized data as we describe in the next section). Specifically it will set the rhoconfig.txt file to have the following option: @@ -53,10 +60,13 @@ If you do not need synchronized offline data, you can leave the third argument o The default home screen of the app is defined in the storemanager/app/index.erb file. You can edit the HTML there to create what your app displays. You can link to other HTML files and ERB files from there with standard HTML techniques. ## Generating Models -You can also use the command line to add models and controllers. When the model is generated, Rhodes will also create files for a standard UI for displaying and editing the model. This follows the standard model-view-controller paradigm.Get more details on [project structure](creating_a_project#project-structure). +You can also use the command line to add models and controllers. When the model is generated, Rhodes will also create files for a sample UI for displaying and editing the model. For a ruby-based application this follows the standard model-view-controller paradigm. For a javascript-based application sample UI is built on pure javascript and jquery. You can use any javascript frontend web application framework like Angular, Ember, Backbone etc. Get more details on [project structure](creating_a_project#project-structure). Let's generate a model called "product" and give it some attributes. + +Ruby-based models + :::term $ cd storemanager $ rhodes model product brand,name,price,quantity,sku @@ -68,6 +78,19 @@ Let's generate a model called "product" and give it some attributes. [ADDED] app/Product/product_controller.rb [ADDED] app/Product/product.rb [ADDED] app/test/product_spec.rb + +Javascript-based models + + :::term + $ cd storemanager + $ rhodes jsmodel product brand,name,price,quantity,sku + Generating with jsmodel generator: + [ADDED] app/Product/index.html + [ADDED] app/Product/index.js + [ADDED] app/Product/model.js + [ADDED] app/Product/new.html + [ADDED] app/Product/show.html + [ADDED] app/Product/edit.html > Note: Models created through the command-line-interface will use the [property bag data schema](rhom_ruby#property_bag) by default. To use Fixed Schema instead, have a look at the [fixed schema section](rhom_ruby#fixed_schema) of our [Rhom in Ruby guide](rhom_ruby). diff --git a/docs/en/edge/guide/rhoArchitecture.md b/docs/en/edge/guide/rhoArchitecture.md index 852b3819..c28c0b52 100644 --- a/docs/en/edge/guide/rhoArchitecture.md +++ b/docs/en/edge/guide/rhoArchitecture.md @@ -277,8 +277,6 @@ Memory constraints are important to consider, particularly when targeting the ol * Don't rely too heavily on performance tests for JavaScript and CSS found online unless they're written specifically for mobile devices -* To maximize performance, JQueryMobile is not included in Windows Mobile/CE devices by default - * An active [RhoMobile developer community](https://developer.motorolasolutions.com) offers forums, blogs, webinars and other useful resources to aid in your development efforts @@ -292,8 +290,6 @@ Memory constraints are important to consider, particularly when targeting the ol * **Only local deveopment is supported for Micro Kiosk (MK) devices**. Zebra development options for supported MK devices include [RhoMobile Suite](http://rhomobile.com/) and [Enterprise Browser](http://goo.gl/V9zMxD). The use of [RhoMobile.com](../../hosted/guide/remote-build-guide) is not supported for building apps for MK devices. -* **When using JQM transitions on Windows Mobile or Windows CE devices**, you may notice that the transition animations do not occur. This is due to insufficient processing resources on the device. -
                                                                              ##Deprecated Zebra Devices diff --git a/docs/en/edge/guide/uichoices.md b/docs/en/edge/guide/uichoices.md index 1a064a06..8d0141bb 100644 --- a/docs/en/edge/guide/uichoices.md +++ b/docs/en/edge/guide/uichoices.md @@ -19,58 +19,25 @@ You may use layout.erb to define what CSS and JavaScript libraries are used by y - + - - Test - - - - <% if System::get_property('platform') == 'WP7' %> - - <% end %> - - <% if System::get_property('platform') == 'APPLE' || System::get_property('platform') == 'ANDROID' || ( System::get_property('platform') == 'UNKNOWN' && System::get_property('webview_framework') =~ /^WEBKIT/) %> - - - - <% if System::get_property('platform') == 'APPLE' %> - - <% end %> - - - - - <% end %> - - <% if System::get_property('platform') == 'APPLE' %> - - <% elsif System::get_property('platform') == 'ANDROID' %> - - <% elsif System::get_property('platform') == 'WP7' %> - - <% elsif System::get_property('platform') == 'WINDOWS' %> - - <% elsif System::get_property('webview_framework') =~ /^WEBKIT/ %> - - <% end %> + Test + + + + + + <% if Rho::System.getProperty('platform') == 'APPLE' || Rho::System.getProperty('platform') == 'ANDROID' || + ( Rho::System.getProperty('platform') != 'WINDOWS' && Rho::System.getProperty('webviewFramework') =~ /^WEBKIT/) %> + + <% end %> + - - - data-do-fix-forms="true" - <% end %> > - <%= @content %> + + + <%= @content %> - + ### Customizing Layouts diff --git a/docs/en/edge/guide/welcome.md b/docs/en/edge/guide/welcome.md index 686f3864..e39b1d07 100644 --- a/docs/en/edge/guide/welcome.md +++ b/docs/en/edge/guide/welcome.md @@ -23,10 +23,3 @@ RhoElements is an additional API library set that is accessible to RhoMobile app ## RhoConnect RhoConnect is a server application that either can be hosted on our system or yours and acts as a seamless bridge for your enterprise data to exist both on your back-end and your mobile device. With RhoConnect, you can simultaneously connect your application to many data sources just as easily as you can connect to one data source — including enterprise back-end customer relationship management (CRM) and enterprise resource planning (ERP) systems, web services, databases and much more. - -## Hosted Services -### Remote Build -Package apps for all platforms without installing SDKs locally, including iPhone apps from your Windows PC. RhoMobile's remote build, formerly known as RhoHub, is a cloud based platform that integrates with RhoStudio to provide seamless local coding and building in the cloud to quickly get you up and running. - -### App Management -Zebra offers the latest in app management technology with [Zebra AppGallery](https://developer.motorolasolutions.com/docs/DOC-3035), a marketplace and deployment tool designed to help users find, purchase, distribute and maintain apps in an enterprise with one or many mobile devices. With AppGallery, developers and enterprises can distribute and maintain their own apps or those acquired from the AppGallery marketplace, simplifying app distribution and maintenance like never before. diff --git a/docs/en/edge/toc.rb b/docs/en/edge/toc.rb index bbc2096b..1ef48889 100644 --- a/docs/en/edge/toc.rb +++ b/docs/en/edge/toc.rb @@ -1,58 +1,47 @@ section 'getting-started', 'Introduction','Mobile Guides' do - topic 'en/edge/guide/welcome', 'Welcome to RhoMobile Suite' - topic 'en/edge/guide/rhoArchitecture', 'Supported Platforms' - topic 'en/edge/guide/devskills', 'Developer Skills' - topic 'en/edge/guide/devenvironment', 'Developer Environments' - topic 'en/edge/guide/appdesign', 'App Architecture' - topic 'en/edge/guide/uichoices', 'UI Architecture' - topic 'en/edge/guide/kitchensink', 'KitchenSink Application' - topic 'en/edge/guide/apiusage', '2.2 Migration Guide' - topic 'en/edge/guide/api_js', 'RhoMobile JavaScript Usage' - topic 'en/edge/guide/api_ruby', 'RhoMobile Ruby Usage' - topic 'en/edge/guide/licensing', 'Licensing' + topic 'en/5.5/guide/welcome', 'Welcome to RhoMobile Suite' + topic 'en/5.5/guide/rhoArchitecture', 'Supported Platforms' + topic 'en/5.5/guide/devskills', 'Developer Skills' + topic 'en/5.5/guide/devenvironment', 'Developer Environments' + topic 'en/5.5/guide/appdesign', 'App Architecture' + topic 'en/5.5/guide/uichoices', 'UI Architecture' + topic 'en/5.5/guide/kitchensink', 'KitchenSink Application' + topic 'en/5.5/guide/apiusage', '2.2 Migration Guide' + topic 'en/5.5/guide/api_js', 'RhoMobile JavaScript Usage' + topic 'en/5.5/guide/api_ruby', 'RhoMobile Ruby Usage' + topic 'en/5.5/guide/licensing', 'Licensing' end section 'rhodescommonapi-reference', 'API Reference','Mobile API Docs' do - topic 'en/edge/guide/apisummary', 'RhoMobile API Summary' - topic 'en/2.2.0/rhoelements/addressbar', 'Addressbar' - topic 'en/2.2.0/rhoelements/alarm', 'Alarm' - topic 'en/edge/api/Application', 'Application' - topic 'en/edge/api/audiocapture', 'AudioCapture' - topic 'en/2.2.0/rhoelements/backlight', 'Backlight' - topic 'en/edge/api/barcode', 'Barcode' - topic 'en/edge/api/battery', 'Battery' + topic 'en/5.5/guide/apisummary', 'RhoMobile API Summary' + topic 'en/5.5/api/Application', 'Application' + topic 'en/5.5/api/audiocapture', 'AudioCapture' + topic 'en/5.5/api/barcode', 'Barcode' + topic 'en/5.5/api/battery', 'Battery' topic 'en/2.2.0/rhodesapi/bluetoothmanager-api', 'BluetoothManager' topic 'en/2.2.0/rhodesapi/bluetoothsession-api', 'BluetoothSession' - topic 'en/edge/api/camera', 'Camera' - topic 'en/edge/api/cardreader', 'CardReader' + topic 'en/5.5/api/camera', 'Camera' + topic 'en/5.5/api/cardreader', 'CardReader' topic 'en/2.2.0/rhoelements/comm', 'Comm' - topic 'en/edge/api/Config', 'Config' + topic 'en/5.5/api/Config', 'Config' # topic 'en/2.2.0/rhoelements/contact', 'Contact' - topic 'en/edge/api/Database', 'Database' - topic 'en/edge/api/device', 'Device' - topic 'en/edge/api/geolocation', 'Geolocation' - topic 'en/2.2.0/rhoelements/Gesture', 'Gesture' - topic 'en/2.2.0/rhoelements/hourglass', 'Hourglass' - topic 'en/edge/api/Intent', 'Intent' - topic 'en/edge/api/keycapture', 'KeyCapture' - topic 'en/2.2.0/rhoelements/Keylight', 'Keylight' - topic 'en/edge/api/keystate', 'KeyState' - topic 'en/edge/api/Log', 'Log' + topic 'en/5.5/api/Database', 'Database' + topic 'en/5.5/api/device', 'Device' + topic 'en/5.5/api/geolocation', 'Geolocation' + topic 'en/5.5/api/Intent', 'Intent' + topic 'en/5.5/api/keycapture', 'KeyCapture' + topic 'en/5.5/api/keystate', 'KeyState' + topic 'en/5.5/api/Log', 'Log' topic 'en/2.2.0/rhodesapi/mapview-api', 'MapView' - topic 'en/edge/api/mediaplayer', 'Mediaplayer' - topic 'en/2.2.0/rhoelements/memory', 'Memory' - topic 'en/edge/api/NativeMenubar', 'NativeMenubar' - topic 'en/edge/api/NativeTabbar', 'NativeTabbar' - topic 'en/edge/api/NativeToolbar', 'NativeToolbar' - topic 'en/edge/api/Navbar', 'Navbar' + topic 'en/5.5/api/mediaplayer', 'Mediaplayer' + topic 'en/5.5/api/NativeMenubar', 'NativeMenubar' + topic 'en/5.5/api/NativeTabbar', 'NativeTabbar' + topic 'en/5.5/api/NativeToolbar', 'NativeToolbar' + topic 'en/5.5/api/Navbar', 'Navbar' topic 'en/2.2.0/rhodesapi/NdefMessage-api', 'NdefMessage' topic 'en/2.2.0/rhodesapi/NdefRecord-api', 'NdefRecord' - topic 'en/edge/api/Network', 'Network' - topic 'en/edge/api/Adapter', 'NFC-Adapter (BETA)' - topic 'en/edge/api/Message', 'NFC-Message (BETA)' - topic 'en/edge/api/Record', 'NFC-Record (BETA)' - topic 'en/edge/api/Tag', 'NFC-Tag (BETA)' + topic 'en/5.5/api/Network', 'Network' topic 'en/2.2.0/rhodesapi/NFCManager-api', 'NFCManager' topic 'en/2.2.0/rhodesapi/NFCTag-api', 'NFCTag' topic 'en/2.2.0/rhodesapi/NFCTagTechnology_IsoDep-api', 'NFCTagTechnology_IsoDep' @@ -65,216 +54,203 @@ topic 'en/2.2.0/rhodesapi/NFCTagTechnology_NfcF-api', 'NFCTagTechnology_NfcF' topic 'en/2.2.0/rhodesapi/NFCTagTechnology_NfcV-api', 'NFCTagTechnology_NfcV' topic 'en/2.2.0/rhodesapi/NFCTagTechnology-api', 'NFCTagTechnology' - topic 'en/edge/api/Notification', 'Notification' - topic 'en/edge/api/Notification.Led', 'Notification.Led' - topic 'en/edge/api/Orm', 'ORM JavaScript' - topic 'en/edge/api/rhom-api', 'ORM Ruby' - topic 'en/edge/api/OrmModel', 'ORM Model JavaScript' - topic 'en/edge/api/printing', 'Printer' - # topic 'en/edge/api/printingepson', 'Printing Epson' - topic 'en/edge/api/printingzebra', 'Printer Zebra' - topic 'en/edge/api/push', 'Push' - topic 'en/2.2.0/rhoelements/reboot', 'Reboot' - topic 'en/2.2.0/rhoelements/registry', 'Registry' - topic 'en/2.2.0/rhoelements/rfid', 'RFID' - topic 'en/edge/api/RhoConnectClient', 'RhoConnectClient' + topic 'en/5.5/api/Notification', 'Notification' + topic 'en/5.5/api/Orm', 'ORM JavaScript' + topic 'en/5.5/api/rhom-api', 'ORM Ruby' + topic 'en/5.5/api/OrmModel', 'ORM Model JavaScript' + topic 'en/5.5/api/printing', 'Printer' + # topic 'en/5.5/api/printingepson', 'Printing Epson' + topic 'en/5.5/api/printingzebra', 'Printer Zebra' + topic 'en/5.5/api/push', 'Push' + topic 'en/5.5/api/RhoConnectClient', 'RhoConnectClient' topic 'en/2.2.0/rhodesapi/rhocontact-api', 'RhoContact' topic 'en/2.2.0/rhodesapi/rhocontroller-api', 'RhoController' topic 'en/2.2.0/rhodesapi/rhoerror-api', 'RhoError' topic 'en/2.2.0/rhodesapi/rhoevent-api', 'RhoEvent' - topic 'en/edge/api/File', 'RhoFile' + topic 'en/5.5/api/File', 'RhoFile' topic 'en/2.2.0/rhodesapi/rhomsource-api', 'RhomSource' topic 'en/2.2.0/rhodesapi/rhoprofiler-api', 'RhoProfiler' topic 'en/2.2.0/rhodesapi/rhoutils-api', 'RhoUtils' - topic 'en/edge/api/screenorientation', 'ScreenOrientation' - topic 'en/edge/api/sensor', 'Sensor' - topic 'en/edge/api/smartcradle', 'SmartCradle' - topic 'en/edge/api/signalindicators', 'SignalIndicators' - topic 'en/edge/api/signature', 'Signature' + topic 'en/5.5/api/screenorientation', 'ScreenOrientation' + topic 'en/5.5/api/sensor', 'Sensor' + topic 'en/5.5/api/smartcradle', 'SmartCradle' + topic 'en/5.5/api/signalindicators', 'SignalIndicators' + topic 'en/5.5/api/signature', 'Signature' topic 'en/2.2.0/rhodesapi/signaturecapture-api', 'SignatureCapture (Inline)' - topic 'en/2.2.0/rhoelements/stylus', 'Stylus' - topic 'en/edge/api/system', 'System' - topic 'en/2.2.0/rhoelements/systemTime', 'SystemTime' - topic 'en/edge/api/Timer', 'Timer' - topic 'en/2.2.0/rhoelements/VideoCapture', 'VideoCapture' - topic 'en/2.2.0/rhoelements/volume', 'Volume' - topic 'en/2.2.0/rhoelements/wake', 'Wake' - # topic 'en/edge/api/videocapture', 'Video Capture' - # topic 'en/edge/api/websocket', 'WebSocket' - topic 'en/edge/api/webview', 'WebView' + topic 'en/5.5/api/system', 'System' + topic 'en/5.5/api/Timer', 'Timer' + # topic 'en/5.5/api/videocapture', 'Video Capture' + # topic 'en/5.5/api/websocket', 'WebSocket' + topic 'en/5.5/api/webview', 'WebView' end section 'rhomob-setup', 'Dev Environment Setup','Mobile Guides' do - topic 'en/edge/guide/rhomobile-install', 'RhoMobile Suite Install' - topic 'en/edge/guide/nativesdksetup', 'Native SDK Setup' - topic 'en/edge/guide/nonrhostudio', 'Developing Without RhoStudio' - topic 'en/edge/guide/visualstudio', 'Developing with Visual Studio' + topic 'en/5.5/guide/rhomobile-install', 'RhoMobile Suite Install' + topic 'en/5.5/guide/nativesdksetup', 'Native SDK Setup' + topic 'en/5.5/guide/nonrhostudio', 'Developing Without RhoStudio' + topic 'en/5.5/guide/visualstudio', 'Developing with Visual Studio' end section 'rhomob-apps', 'Developing Apps','Mobile Guides' do - topic 'en/edge/guide/creating_a_project', 'Starting a New Project' - topic 'en/edge/guide/runtime_config', 'Runtime Configuration' - topic 'en/edge/guide/build_config', 'Buildtime Configuration' - topic 'en/edge/guide/viewport', 'Viewport Configuration' - topic 'en/edge/guide/build_ios', 'Build for iOS' - topic 'en/edge/guide/build_android', 'Build for Android' - topic 'en/edge/guide/build_wm', 'Build for Windows Mobile' - topic 'en/edge/guide/build_wp8', 'Build for Windows Phone 8' - topic 'en/edge/guide/build_win', 'Build for Windows' - topic 'en/edge/guide/using_emulators', 'Using Native Emulators' - topic 'en/edge/guide/app_icon_splash', 'Application Icon & Splash Screen' - topic 'en/edge/guide/css-framework', 'CSS Frameworks' - topic 'en/edge/guide/webapps', 'RhoMobile for Web Apps' - topic 'en/edge/guide/webcontainer', 'Custom Web App Container' - topic 'en/edge/guide/app_upgrade', 'Upgrading Your App' - topic 'en/edge/guide/live-update', 'Live Update' + topic 'en/5.5/guide/creating_a_project', 'Starting a New Project' + topic 'en/5.5/guide/runtime_config', 'Runtime Configuration' + topic 'en/5.5/guide/build_config', 'Buildtime Configuration' + topic 'en/5.5/guide/viewport', 'Viewport Configuration' + topic 'en/5.5/guide/build_ios', 'Build for iOS' + topic 'en/5.5/guide/build_android', 'Build for Android' + topic 'en/5.5/guide/build_wm', 'Build for Windows Mobile' + topic 'en/5.5/guide/build_wp8', 'Build for Windows Phone 8' + topic 'en/5.5/guide/build_win', 'Build for Windows' + topic 'en/5.5/guide/using_emulators', 'Using Native Emulators' + topic 'en/5.5/guide/app_icon_splash', 'Application Icon & Splash Screen' + topic 'en/5.5/guide/css-framework', 'CSS Frameworks' + topic 'en/5.5/guide/webapps', 'RhoMobile for Web Apps' + topic 'en/5.5/guide/webcontainer', 'Custom Web App Container' + topic 'en/5.5/guide/app_upgrade', 'Upgrading Your App' + topic 'en/5.5/guide/live-update', 'Live Update' end section 'rhomob-data', 'Data Handling','Mobile Guides' do - topic 'en/edge/guide/local_database', 'Local Database and Rhom' - topic 'en/edge/guide/rhom_ruby', 'Using Rhom with Ruby' - topic 'en/edge/guide/rhom_js', 'Using Rhom with JavaScript' - topic 'en/edge/guide/rhom_backbone', 'Using Rhom with Backbone.JS' - topic 'en/edge/guide/rhom_angular', 'Using Rhom with Angular JS' - topic 'en/edge/guide/synchronization', 'Synchronization' - topic 'en/edge/guide/web_services', 'Web Services & AJAX' + topic 'en/5.5/guide/local_database', 'Local Database and Rhom' + topic 'en/5.5/guide/rhom_ruby', 'Using Rhom with Ruby' + topic 'en/5.5/guide/rhom_js', 'Using Rhom with JavaScript' + topic 'en/5.5/guide/rhom_backbone', 'Using Rhom with Backbone.JS' + topic 'en/5.5/guide/rhom_angular', 'Using Rhom with Angular JS' + topic 'en/5.5/guide/synchronization', 'Synchronization' + topic 'en/5.5/guide/web_services', 'Web Services & AJAX' end section 'rhomob-dev', 'Device Capabilities','Mobile Guides' do - topic 'en/edge/guide/barcode', 'Barcode' - topic 'en/edge/guide/bluetooth', 'Bluetooth' - topic 'en/edge/guide/camera', 'Camera' - topic 'en/edge/guide/pim', 'Contacts & Calendar' - topic 'en/edge/guide/controlling_webview_behavior', 'Controlling Webview Behavior' - topic 'en/edge/guide/device_hardware_key_handling', 'Device Notifications & Keylight' - topic 'en/edge/guide/device_information_and_abilities', 'Detecting Device Abilities' - topic 'en/edge/guide/hardware_accleration', 'Hardware Acceleration' - topic 'en/edge/guide/html5', 'Html5 Tags' - topic 'en/edge/guide/handling_local_files', 'File System' - topic 'en/edge/guide/geolocation', 'Geolocation' - topic 'en/edge/guide/intent', 'Intents' - topic 'en/edge/guide/localization', 'Localization' - topic 'en/edge/guide/maps', 'Mapping' - topic 'en/edge/guide/media', 'Media & Ringtones' - topic 'en/edge/guide/native_ui_elements', 'Native UI Components' - topic 'en/edge/guide/interfacing_with_the_network', 'Network Interfacing' + topic 'en/5.5/guide/barcode', 'Barcode' + topic 'en/5.5/guide/bluetooth', 'Bluetooth' + topic 'en/5.5/guide/camera', 'Camera' + topic 'en/5.5/guide/pim', 'Contacts & Calendar' + topic 'en/5.5/guide/controlling_webview_behavior', 'Controlling Webview Behavior' + topic 'en/5.5/guide/device_hardware_key_handling', 'Device Notifications & Keylight' + topic 'en/5.5/guide/device_information_and_abilities', 'Detecting Device Abilities' + topic 'en/5.5/guide/hardware_accleration', 'Hardware Acceleration' + topic 'en/5.5/guide/html5', 'Html5 Tags' + topic 'en/5.5/guide/handling_local_files', 'File System' + topic 'en/5.5/guide/geolocation', 'Geolocation' + topic 'en/5.5/guide/intent', 'Intents' + topic 'en/5.5/guide/localization', 'Localization' + topic 'en/5.5/guide/maps', 'Mapping' + topic 'en/5.5/guide/media', 'Media & Ringtones' + topic 'en/5.5/guide/native_ui_elements', 'Native UI Components' + topic 'en/5.5/guide/interfacing_with_the_network', 'Network Interfacing' topic 'en/2.2.0/rhodes/nfc', 'NFC' - topic 'en/edge/guide/screen_orientation', 'Orientation and Responsive Design' - topic 'en/edge/guide/printing', 'Printing' - topic 'en/edge/guide/push_notifications', 'Push Notifications' - topic 'en/edge/guide/device_sensors', 'Sensors' - topic 'en/edge/guide/signature', 'Signature' - topic 'en/edge/guide/urlschemes', 'URL Schemes' + topic 'en/5.5/guide/screen_orientation', 'Orientation and Responsive Design' + topic 'en/5.5/guide/printing', 'Printing' + topic 'en/5.5/guide/push_notifications', 'Push Notifications' + topic 'en/5.5/guide/device_sensors', 'Sensors' + topic 'en/5.5/guide/signature', 'Signature' + topic 'en/5.5/guide/urlschemes', 'URL Schemes' end section 'rhomob-test', 'Testing & Debugging','Mobile Guides' do - topic 'en/edge/guide/debugging_ruby', 'Debugging Ruby' - topic 'en/edge/guide/debugging_js', 'Debugging JavaScript' - topic 'en/edge/guide/logging', 'Logging' - topic 'en/edge/guide/testing', 'Testing' - topic 'en/edge/guide/profiling', 'Performance Profiling' + topic 'en/5.5/guide/debugging_ruby', 'Debugging Ruby' + topic 'en/5.5/guide/debugging_js', 'Debugging JavaScript' + topic 'en/5.5/guide/logging', 'Logging' + topic 'en/5.5/guide/testing', 'Testing' + topic 'en/5.5/guide/profiling', 'Performance Profiling' end section 'rhomob-ext', 'Extending','Mobile Guides' do - topic 'en/edge/guide/native_extensions', 'Extending the Rhodes Framework' - topic 'en/edge/guide/ruby_extensions', 'Ruby Native Extensions' - topic 'en/edge/guide/rho_ruby', 'Rhomobile Ruby' - topic 'en/edge/guide/view_extensions', 'View Extensions' + topic 'en/5.5/guide/native_extensions', 'Extending the Rhodes Framework' + topic 'en/5.5/guide/ruby_extensions', 'Ruby Native Extensions' + topic 'en/5.5/guide/rho_ruby', 'Rhomobile Ruby' + topic 'en/5.5/guide/view_extensions', 'View Extensions' end section 'rhoconnect-reference', 'Getting Started','RhoConnect Guides' do - topic 'en/edge/rhoconnect/introduction', 'Introduction' - topic 'en/edge/rhoconnect/install', 'Installation' - topic 'en/edge/rhoconnect/migration', 'Migrating to RhoConnect 5.0' - topic 'en/edge/rhoconnect/command-line', 'App Generator and Command Line' - topic 'en/edge/rhoconnect/supported-platforms', 'Supported Platforms' - topic 'en/edge/rhoconnect/rhoconnect-calculator', 'RhoConnect Calculator' + topic 'en/5.5/rhoconnect/introduction', 'Introduction' + topic 'en/5.5/rhoconnect/install', 'Installation' + topic 'en/5.5/rhoconnect/migration', 'Migrating to RhoConnect 5.0' + topic 'en/5.5/rhoconnect/command-line', 'App Generator and Command Line' + topic 'en/5.5/rhoconnect/supported-platforms', 'Supported Platforms' + topic 'en/5.5/rhoconnect/rhoconnect-calculator', 'RhoConnect Calculator' end section 'rhoconnect-source-adapter-reference', 'Source Adapters','RhoConnect Guides' do - topic 'en/edge/rhoconnect/source-adapters-intro', 'Introduction' - topic 'en/edge/rhoconnect/source-adapters', 'Source Adapters (Ruby)' - topic 'en/edge/rhoconnect/source-adapters-js', 'Source Adapters (JavaScript)' - topic 'en/edge/rhoconnect/authentication', 'Adding Device Authentication' - topic 'en/edge/rhoconnect/testing', 'Testing and Debugging' - topic 'en/edge/rhoconnect/blob-sync', 'Binary Objects and Blob Sync' - topic 'en/edge/rhoconnect/async-jobs', 'Adapter Jobs with Resque' - topic 'en/edge/rhoconnect/metadata', 'Dynamic Views with Metadata' - topic 'en/edge/rhoconnect/data-partitioning', 'Data Partitioning & Pass-Through' + topic 'en/5.5/rhoconnect/source-adapters-intro', 'Introduction' + topic 'en/5.5/rhoconnect/source-adapters', 'Source Adapters (Ruby)' + topic 'en/5.5/rhoconnect/source-adapters-js', 'Source Adapters (JavaScript)' + topic 'en/5.5/rhoconnect/authentication', 'Adding Device Authentication' + topic 'en/5.5/rhoconnect/testing', 'Testing and Debugging' + topic 'en/5.5/rhoconnect/blob-sync', 'Binary Objects and Blob Sync' + topic 'en/5.5/rhoconnect/async-jobs', 'Adapter Jobs with Resque' + topic 'en/5.5/rhoconnect/metadata', 'Dynamic Views with Metadata' + topic 'en/5.5/rhoconnect/data-partitioning', 'Data Partitioning & Pass-Through' end section 'rhoconnect-ruby-api-reference', 'Source Adapter Ruby APIs','RhoConnect Guides' do - topic 'en/edge/rhoconnectapi/source-adapter-controller-api-ruby', 'Source Adapter Controller API' - topic 'en/edge/rhoconnectapi/source-adapter-model-api-ruby', 'Source Adapter Model API' - topic 'en/edge/rhoconnectapi/source-adapter-store-api-ruby', 'Source Adapter Store API' - topic 'en/edge/rhoconnectapi/test-api-ruby', 'Source Adapter Test API' + topic 'en/5.5/rhoconnectapi/source-adapter-controller-api-ruby', 'Source Adapter Controller API' + topic 'en/5.5/rhoconnectapi/source-adapter-model-api-ruby', 'Source Adapter Model API' + topic 'en/5.5/rhoconnectapi/source-adapter-store-api-ruby', 'Source Adapter Store API' + topic 'en/5.5/rhoconnectapi/test-api-ruby', 'Source Adapter Test API' end section 'rhoconnect-js-api-reference', 'Source Adapter JS APIs','RhoConnect Guides' do - topic 'en/edge/rhoconnectapi/source-adapter-controller-api-js', 'Source Adapter Controller API' - topic 'en/edge/rhoconnectapi/source-adapter-model-api-js', 'Source Adapter Model API' - topic 'en/edge/rhoconnectapi/source-adapter-request-api-js', 'Source Request API' - topic 'en/edge/rhoconnectapi/source-adapter-response-api-js', 'Source Response API' - topic 'en/edge/rhoconnectapi/source-adapter-store-api-js', 'Source Adapter Store API' - topic 'en/edge/rhoconnectapi/source-adapter-exception-api-js', 'Source Adapter Exception API' + topic 'en/5.5/rhoconnectapi/source-adapter-controller-api-js', 'Source Adapter Controller API' + topic 'en/5.5/rhoconnectapi/source-adapter-model-api-js', 'Source Adapter Model API' + topic 'en/5.5/rhoconnectapi/source-adapter-request-api-js', 'Source Request API' + topic 'en/5.5/rhoconnectapi/source-adapter-response-api-js', 'Source Response API' + topic 'en/5.5/rhoconnectapi/source-adapter-store-api-js', 'Source Adapter Store API' + topic 'en/5.5/rhoconnectapi/source-adapter-exception-api-js', 'Source Adapter Exception API' end section 'rhoconnect-plugin-reference', 'Plugins','RhoConnect Guides' do - topic 'en/edge/rhoconnect/plugin-intro', 'Introduction' - topic 'en/edge/rhoconnect/rails-plugin', 'Rails Plugin' - topic 'en/edge/rhoconnect/net-plugin', '.Net Plugin' - topic 'en/edge/rhoconnect/java-plugin', 'Java Plugin' + topic 'en/5.5/rhoconnect/plugin-intro', 'Introduction' + topic 'en/5.5/rhoconnect/rails-plugin', 'Rails Plugin' + topic 'en/5.5/rhoconnect/net-plugin', '.Net Plugin' + topic 'en/5.5/rhoconnect/java-plugin', 'Java Plugin' end section 'rhoconnect-push-reference', 'Push Sync','RhoConnect Guides' do - topic 'en/edge/rhoconnect/push', 'Introduction to Push' - topic 'en/edge/rhoconnect/push-client-setup-rps', 'Setup for RhoConnect Push Service' - topic 'en/edge/rhoconnect/push-client-setup-android', 'Setup for Android' - topic 'en/edge/rhoconnect/push-client-setup-ios', 'Setup for iOS' - topic 'en/edge/rhoconnect/push-client-setup', 'Finishing Setup for all Clients' - topic 'en/edge/rhoconnect/push-backend-setup', 'Setup on Backend' - topic 'en/edge/rhoconnect/push-testing', 'Testing Push' + topic 'en/5.5/rhoconnect/push', 'Introduction to Push' + topic 'en/5.5/rhoconnect/push-client-setup-rps', 'Setup for RhoConnect Push Service' + topic 'en/5.5/rhoconnect/push-client-setup-android', 'Setup for Android' + topic 'en/5.5/rhoconnect/push-client-setup-ios', 'Setup for iOS' + topic 'en/5.5/rhoconnect/push-client-setup', 'Finishing Setup for all Clients' + topic 'en/5.5/rhoconnect/push-backend-setup', 'Setup on Backend' + topic 'en/5.5/rhoconnect/push-testing', 'Testing Push' end section 'rhoconnect-administration', 'Administration','RhoConnect Guides' do - topic 'en/edge/rhoconnect/settings', 'RhoConnect Settings' - topic 'en/edge/rhoconnect/web-console', 'Admin Web Interface' + topic 'en/5.5/rhoconnect/settings', 'RhoConnect Settings' + topic 'en/5.5/rhoconnect/web-console', 'Admin Web Interface' topic 'en/hosted/guide/licensing-rhoconnect', 'Licensing your RhoConnect App' - topic 'en/edge/rhoconnect/benchmarks', 'Rhoconnect Benchmarking' - topic 'en/edge/rhoconnect/benchmarks-running', 'Running Rhoconnect Benchmarks' - topic 'en/edge/rhoconnect/stats-middleware', 'Collecting Runtime Stats' + topic 'en/5.5/rhoconnect/benchmarks', 'Rhoconnect Benchmarking' + topic 'en/5.5/rhoconnect/benchmarks-running', 'Running Rhoconnect Benchmarks' + topic 'en/5.5/rhoconnect/stats-middleware', 'Collecting Runtime Stats' end section 'rhoconnect-deployment', 'Deployment','RhoConnect Guides' do - topic 'en/edge/rhoconnect/preparing-production', 'Preparing for Production' - # topic 'en/edge/rhoconnect/hosting-rhohub', 'Hosting on RhoHub' - topic 'en/edge/rhoconnect/deploying', 'Deploying RhoConnect' - topic 'en/edge/rhoconnect/rhoconnect-redis-stack', 'High Availability Deployment on AWS' + topic 'en/5.5/rhoconnect/preparing-production', 'Preparing for Production' + # topic 'en/5.5/rhoconnect/hosting-rhohub', 'Hosting on RhoHub' + topic 'en/5.5/rhoconnect/deploying', 'Deploying RhoConnect' + topic 'en/5.5/rhoconnect/rhoconnect-redis-stack', 'High Availability Deployment on AWS' end section 'rhoconnect-advanced', 'Advanced Topics','RhoConnect Guides' do - topic 'en/edge/rhoconnect/bulk-sync', 'Big Datasets and Bulk Sync' - topic 'en/edge/rhoconnect/extending-rhoconnect-server', 'Extending Rhoconnect App with custom routes' - topic 'en/edge/rhoconnect/cud-conflicts', 'Resolving Conflicts' + topic 'en/5.5/rhoconnect/bulk-sync', 'Big Datasets and Bulk Sync' + topic 'en/5.5/rhoconnect/extending-rhoconnect-server', 'Extending Rhoconnect App with custom routes' + topic 'en/5.5/rhoconnect/cud-conflicts', 'Resolving Conflicts' end section 'rhoconnect-nonrhodes-client-reference', 'Clients','RhoConnect Guides' do - topic 'en/edge/rhoconnect/client', 'Using RhoConnect without Rhodes' - topic 'en/edge/rhoconnect/rest-api', 'RhoConnect REST API' - topic 'en/edge/rhoconnect/client-objc', 'RhoConnect Client for iOS' - topic 'en/edge/rhoconnect/client-java', 'RhoConnect without Rhodes: Android Java' - topic 'en/edge/rhoconnectjs/introduction', 'RhoConnect.JS Client' - topic 'en/edge/rhoconnectjs/getting-started', 'RhoConnect.JS Getting Started' - topic 'en/edge/rhoconnectjs/reference', 'RhoConnect.JS API Reference' - topic 'en/edge/rhoconnectjs/creating-app', 'RhoConnect.JS Creating an App' -end - -section 'rhoconnect-service-reference', 'Hosted Services','RhoConnect Guides' do - topic 'en/edge/rhoconnect/heroku-addon', 'Heroku Addon' + topic 'en/5.5/rhoconnect/client', 'Using RhoConnect without Rhodes' + topic 'en/5.5/rhoconnect/rest-api', 'RhoConnect REST API' + topic 'en/5.5/rhoconnect/client-objc', 'RhoConnect Client for iOS' + topic 'en/5.5/rhoconnect/client-java', 'RhoConnect without Rhodes: Android Java' + topic 'en/5.5/rhoconnectjs/introduction', 'RhoConnect.JS Client' + topic 'en/5.5/rhoconnectjs/getting-started', 'RhoConnect.JS Getting Started' + topic 'en/5.5/rhoconnectjs/reference', 'RhoConnect.JS API Reference' + topic 'en/5.5/rhoconnectjs/creating-app', 'RhoConnect.JS Creating an App' end section 'rhoconnect-adapters-reference', 'Vendor Adapters','RhoConnect Guides' do - topic 'en/edge/rhoconnect/adapters-intro', 'Introduction' - topic 'en/edge/rhoconnect/adapters-crm', 'CRM adapters' + topic 'en/5.5/rhoconnect/adapters-intro', 'Introduction' + topic 'en/5.5/rhoconnect/adapters-crm', 'CRM adapters' end \ No newline at end of file diff --git a/public/images/bg/tau-logo.png b/public/images/bg/tau-logo.png new file mode 100644 index 00000000..cda90057 Binary files /dev/null and b/public/images/bg/tau-logo.png differ diff --git a/public/javascripts/application.js b/public/javascripts/application.js index 13406a14..f4a58258 100644 --- a/public/javascripts/application.js +++ b/public/javascripts/application.js @@ -1,146 +1,143 @@ $(document).ready(function() { - $(".js-pjax").pjax({ - container: "#t_content", - fragment: "#rendered_topic", - timeout: 4000 - }); - // Update the current topic - $("#t_content").live('pjax:end', function(e, xhr, err) { - // Enable previous anchor - var prevAnchor = $('li.active a'); - console.log(prevAnchor); - prevAnchor.removeAttr('onclick'); - prevAnchor.attr('class', 'js-pjax'); - - // Remove style of previous topic - $('ul.nav-list > li.active').removeClass('active'); - - // Update style of current topic - var cur = $('a[href$="' + $(location).attr("pathname") + '"]'); - cur.attr('onclick', 'return false'); - cur.parent().attr('class', 'active'); - $(window).scrollTop(0); - }); - $('.accordion-heading > li').live('click',function(){ - $(this).find('i').toggleClass('icon-chevron-right').toggleClass('icon-chevron-down'); - }); - //Change url to include version - $('#version_select').bind('change', function () { - var ver = $(this).val(); // get selected value - loc = window.location.pathname; - url = loc.replace(/\/(.[^\/]*)\/(.[^\/]*)(.*)/,'$1/'+ver+'$3'); - $.ajax({ - type: "GET", - url: "/exists", - data: { 'doc': url }, - success: function(){ - newurl =window.location.protocol + "//" + window.location.host + "/" + url ; - // console.log('success' + newurl); - window.location = newurl; - }, - error: function(){ - newurl = window.location.protocol + "//" + window.location.host + "/" + loc.replace(/\/(.[^\/]*)\/(.[^\/]*)(.*)/,'$1/'+ver); - // console.log('error' + newurl); - window.location = newurl; - } - }); - - - - return false; - }); - - $('.bxslider').bxSlider({ - video: true, - useCSS: false + $(".js-pjax").pjax({ + container: "#t_content", + fragment: "#rendered_topic", + timeout: 4000 }); + // Update the current topic + $("#t_content").live('pjax:end', function(e, xhr, err) { + // Enable previous anchor + var prevAnchor = $('li.active a'); + console.log(prevAnchor); + prevAnchor.removeAttr('onclick'); + prevAnchor.attr('class', 'js-pjax'); + + // Remove style of previous topic + $('ul.nav-list > li.active').removeClass('active'); + + // Update style of current topic + var cur = $('a[href$="' + $(location).attr("pathname") + '"]'); + cur.attr('onclick', 'return false'); + cur.parent().attr('class', 'active'); + $(window).scrollTop(0); + }); + $('.accordion-heading > li').live('click', function() { + $(this).find('i').toggleClass('icon-chevron-right').toggleClass('icon-chevron-down'); + }); + //Change url to include version + $('#version_select').bind('change', function() { + var ver = $(this).val(); // get selected value + loc = window.location.pathname; + url = loc.replace(/\/(.[^\/]*)\/(.[^\/]*)(.*)/, '$1/' + ver + '$3'); + $.ajax({ + type: "GET", + url: "/exists", + data: { 'doc': url }, + success: function() { + newurl = window.location.protocol + "//" + window.location.host + "/" + url; + // console.log('success' + newurl); + window.location = newurl; + }, + error: function() { + newurl = window.location.protocol + "//" + window.location.host + "/" + loc.replace(/\/(.[^\/]*)\/(.[^\/]*)(.*)/, '$1/' + ver); + // console.log('error' + newurl); + window.location = newurl; + } + }); + + + + return false; + }); + + $('.bxslider').bxSlider({ + video: true, + useCSS: false + }); + + sizeContent(); + $(".apiCheckbox").bind('change', function() { + $('.property').hide(); + $('.method').hide(); + $(".apiCheckbox").each(function(index) { + console.log(index + ": " + this.checked + ":" + this.value); + var cbClass = '.' + this.value; + if (this.checked) { + $(cbClass).show(); + } + }); + }); + $(".apiFilter").bind('change', function() { + + // console.log(this); + if ($(".apiFilter option:selected").text() == "All") { + $("#apiFilterBtn").html(' Show'); + + } + else { + $("#apiFilterBtn").html('' + $(".apiFilter option:selected").text()); + + } + if (this.value == 'all') { + $('.property').show(); + $('.method').show(); + + } + else { + $('.property').hide(); + $('.method').hide(); + // console.log(this.value); + var cbClass = '.' + this.value; + + $(cbClass).show(); + + } - sizeContent(); - $(".apiCheckbox").bind('change', function() { - $('.property').hide(); - $('.method').hide(); - $( ".apiCheckbox" ).each(function( index ) { - console.log( index + ": " + this.checked + ":" + this.value ); - var cbClass = '.' + this.value; - if(this.checked) { - $(cbClass).show(); - } - }); - }); -$(".apiFilter").bind('change', function() { - - // console.log(this); - if ($(".apiFilter option:selected").text() == "All") - { - $("#apiFilterBtn").html(' Show'); - - } - else - { - $("#apiFilterBtn").html('' + $(".apiFilter option:selected").text()); - - } - if (this.value == 'all') - { - $('.property').show(); - $('.method').show(); - - } - else - { - $('.property').hide(); - $('.method').hide(); - // console.log(this.value); - var cbClass = '.' + this.value; - - $(cbClass).show(); - - } - - - }); - - $(".icon-bug").parent().click(function(){ - var url = "http://github.com/rhomobile/rhomobile-docs/issues/new?title=Doc Issue:" + document.title + '&body=' + encodeURIComponent('Bad Link: ' + window.location.href + ' came from: ' + document.referrer); - window.open(url); - - }); - - - //search handler for filtering - $('#facets > .filter').click(function(e){ - var docCatKey = $(this).attr('data-id'); - var docCat = $(this).attr('data-type'); - var sCats = []; - var sVers = []; - - if ($(this).attr('data-selected') == 'true'){ - $(this).attr('data-selected','false'); - } - else{ - $(this).attr('data-selected','true'); - } - $('#facets > span[data-selected="true"][data-type="category"]').each(function() { - // do something - sCats.push($(this).attr('data-id')); - }); - $('#facets > span[data-selected="true"][data-type="version"]').each(function() { - // do something - sVers.push($(this).attr('data-id')); - }); - - - window.location=window.location.protocol + '//' + window.location.host + window.location.pathname + '?q=' + $('#facets').attr('data-query') + '&c=' + sCats.join(",") + '&v=' + sVers.join(","); - }); - - $('#facets > span[data-type="all"]').click(function(e){ - window.location=window.location.protocol + '//' + window.location.host + window.location.pathname + '?q=' + $('#facets').attr('data-query'); - }); - - $("#searchForm").indextank_Ize('http://rd4f.api.searchify.com', 'rhodocs'); + + }); + + $(".icon-bug").parent().click(function() { + //var url = "http://github.com/rhomobile/rhomobile-docs/issues/new?title=Doc Issue:" + document.title + '&body=' + encodeURIComponent('Bad Link: ' + window.location.href + ' came from: ' + document.referrer); + var url = "https://tautechnologies.zendesk.com/hc/en-us/requests/new"; + window.open(url); + + }); + + + //search handler for filtering + $('#facets > .filter').click(function(e) { + var docCatKey = $(this).attr('data-id'); + var docCat = $(this).attr('data-type'); + var sCats = []; + var sVers = []; + + if ($(this).attr('data-selected') == 'true') { + $(this).attr('data-selected', 'false'); + } + else { + $(this).attr('data-selected', 'true'); + } + $('#facets > span[data-selected="true"][data-type="category"]').each(function() { + // do something + sCats.push($(this).attr('data-id')); + }); + $('#facets > span[data-selected="true"][data-type="version"]').each(function() { + // do something + sVers.push($(this).attr('data-id')); + }); + + + window.location = window.location.protocol + '//' + window.location.host + window.location.pathname + '?q=' + $('#facets').attr('data-query') + '&c=' + sCats.join(",") + '&v=' + sVers.join(","); + }); + + $('#facets > span[data-type="all"]').click(function(e) { + window.location = window.location.protocol + '//' + window.location.host + window.location.pathname + '?q=' + $('#facets').attr('data-query'); + }); + + $("#searchForm").indextank_Ize('http://rd4f.api.searchify.com', 'rhodocs'); // let the query box have autocomplete $("#query").indextank_Autocomplete(); - + }); diff --git a/version.rb b/version.rb index 084ea9f1..f0b90032 100644 --- a/version.rb +++ b/version.rb @@ -1,5 +1,5 @@ module Version - CURR_VERSION = '5.4' - PREV_VERSION = '5.3.2' + CURR_VERSION = '5.5' + PREV_VERSION = '5.4' NEXT_VERSION = 'edge' end \ No newline at end of file diff --git a/views/index.erb b/views/index.erb index d3b036ca..c970aeeb 100644 --- a/views/index.erb +++ b/views/index.erb @@ -47,8 +47,8 @@

                                                                              -
                                                                              -
                                                                              + diff --git a/views/layout.erb b/views/layout.erb index 6bfc15b3..b4ec307f 100644 --- a/views/layout.erb +++ b/views/layout.erb @@ -30,7 +30,7 @@