Skip Headers
Oracle® Database Mobile Server Developer's Guide
Release 11.2

Part Number E29740-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
PDF · Mobi · ePub

3 Managing Synchronization on the Mobile Client

The following sections describe the mobile client synchronization APIs available to manage both manual and automatic synchronization programmatically within your application on the mobile client:

3.1 Invoke Manual Synchronization on the Mobile Client

You can modify the client-side application to start the synchronization programmatically. This section describes how to perform the synchronization upload and download phases for the client using the Synchronization APIs.

Note:

Currently, there are no APIs to perform the upload activity on UNIX platforms.

To execute the upload portion of synchronization from the client from within your client application, perform the following steps:

  1. Initialize the synchronization parameters.

  2. Set up the transport parameters.

  3. Initialize the synchronization options and environment, such as user name, password, and selective synchronization.

  4. Perform the synchronization.

Use the following APIs for invoking manual synchronization on your mobile clients:

3.1.1 OSE Synchronization API for Applications on Mobile Clients

OSE synchronization interfaces are available for pure Java clients, native clients and .Net clients. The following sections provide more details:

Note:

Use the OSE classes for all new application development for your mobile clients. These are the classes that are supported for the future.

3.1.1.1 OSE Synchronization Java API

The following sections describe how you can use the OSE Java APIs to build your own client synchronization initiation on mobile clients:

Note:

For more details on these classes, refer to the Oracle Database Mobile Server JavaDoc.
3.1.1.1.1 Overview

The Java interface for mobile client synchronization resides in the oracle.opensync.ose package. The OSE Sync interface is included in the osync_se.jar for the pure Java client.

The Java interface provides for the following functions:

  • Setting client-side user profiles containing data such as user name, password, and server

  • Starting the synchronization process

  • Tracking the progress of the synchronization process

For Win32, Windows Mobile, and Linux clients, the Java interface is implemented using JNI and consists of two files: jsync.jar and msync_java.dll. The pure Java interface is implemented in the osync_se.jar file. To use the JNI synchronization interface, include the jsync.jar file in the CLASSPATH and msync_java.dll file in the PATH. For both mobile clients, common binaries, including these files, are located in the <ORACLE_HOME>\Mobile\Sdk\sqlite directory. Files specific to each client can be in <ORACLE_HOME>\Mobile\Sdk\bdb and <ORACLE_HOME>\Mobile\Sdk\sqlite respectively.

The pure Java library for the Blackberry RIM platform is located in the <ORACLE_HOME>\Mobile\Sdk\<mobile_client>\rim\lib directory; the pure Java library for the Android platform is located in the <ORACLE_HOME>\Mobile\Sdk\<mobile_client>\android\lib directory, where <mobile_client> is either bdb or sqlite depending on the mobile client.

The following are the classes and interface for the Java API for mobile clients:

  • OSESession Class

  • OSEProgressListener Interface

  • OSETransport Interface

  • OSEException Class

3.1.1.1.2 OSESession Class

OSESession enables setting synchronization parameters and options. This class exposes APIs to invoke and control synchronization by using the provided synchronization options.

In a multi-threaded environment, you cannot execute OSESession methods from multiple threads. Each thread should open its own session. The only exception is cancelSync, which can be executed by another thread.

Note:

Synchronization progress is reported through the OSEProgressListener interface, which is set by the OSESession setProgress(OSEProgressListener) method.

The parameters for the constructor are listed in Table 3-1.

Constructors

OSESession( )

OSESession( String user )

OSESession( String user, char[] pwd)

Table 3-1 OSESession Class Constructor

Parameter Description

user

A string containing the name used for authentication by the mobile server.

password

A character array containing the user password.


Public Methods

The public methods and their parameters for the OSESession class are listed in Table 3-2:

Table 3-2 OSESession Class Public Method Parameters

Method Description

void cancelSync( )

Attempts to cancel the synchronization process with a non-blocking call. If successful, throws OSEException with error code OSEExceptionConstants.SYNC_CANCELED.

void close()

Closes any active database connections that the session maintains. This method is called before application exits.

void saveUser()

String getUser()

The saveUser method saves user information, such as users specific information, and the last synchronization user id.

The getUser method retrieves current synchronization client name.

void selectPub(String name)

Provided the publication name, adds the publication to the list of publications to be synchronized selectively. See Section 3.1.1.1.4, "Selective Synchronization" for more information.

void setAppRoot(String appRoot)

String getAppRoot( )

Sets or retrieves the current root directory, as set in the DATA_DIRECTORY parameter, for internal synchronization and database files for the application.

boolean getBackground()

void setBackground(boolean on)

Sets or returns TRUE is a synchronization event is an automatic synchronization; FALSE if not.

void setEncryptionType (int type)

int getEncryptionType( )

Sets or retrieves the current encryption type. Possible types can are as follows:

  • ENC_AES - AES encryption, which is the default.

  • ENC_SSL - SSL over HTTP.

  • ENC_NONE - No encryption.

void setForceRefresh (boolean on)

boolean getForceRefresh( )

Set to wipe out all of the client data and replace it with server data, if true.

Retrieves value of force refresh.

void setSavePassword (boolean on)

boolean getSavePassword()

This is used to set and get the flag for persistently saving the user password. If true, the password is saved.

void setNewPassword(char[] pwd)

Allows clients to modify their password on the server. After a successful synchronization, the client's password on the server is changed to the new password.

void setPassword(char[] pwd)

Provide or modify the mobile client password.

void setProgress (OSEProgressListener p)

Set synchronization progress listener. For more details, see Section 3.1.1.1.3, "OSEProgressListener Interface".

void setProxy(java.lang.String proxy)

java.lang.String getProxy()

Sets or returns the current HTTP proxy, which can be the hostname or IP address of the proxy server. NULL is returned if proxy is not used.

void setSyncApps(boolean on)

boolean getSyncApps()

Sets or retrieves a flag that indicates whether the application client updates should be downloaded during the next synchronization. If set to FALSE, client updates are only uploaded to the server.

setSyncDirection(int)

getSyncDirection( )

Sets or retrieves the current synchronization direction of data for the mobile client. You can indicate whether the client should perform normal synchronization with DIR_SENDRECEIVE, where data is both uploaded and downloaded. Alternatively, if you set the direction for data to be as follows:

  • DIR_SENDRECEIVE: Default. Sets the direction to send and receive.

  • DIR_SEND: Sets the direction to upload client data, but no server data is downloaded.

  • DIR_RECEIVE: Sets the direction to download data from the server, but no client data is uploaded.

This direction setting affects only user data. All mobile server data, such as awknowledgements, will still be uploaded or downloaded as appropriate.

void setSyncNewPub(boolean on)

boolean getSyncNewPub( )

Sets flag for enabling synchronization of new publications. By default, this is set to true and all publications are synchronized. However, if you set this to false, any new subscribed publications on the server are not downloaded to the client.

int getSyncPriority()

public void setSyncPriority(int prio) throws OSEException

Sets or retrieves the synchronization priority. The default is PRIO_DEFAULT, which is OFF. Only high priority table or rows are synchronized when set to PRIO_HIGH.

You can only use fast refresh with a high priority restricting predicate. If you use any other type of refresh, the high priority restricting predicate is ignored.

See Section 1.2.10, "Priority-Based Replication" in the Oracle Database Mobile Server Troubleshooting and Tuning Guide for more information.

void setTransportType(int type)

int getTransportType( )

Sets and retrieves the current transport type, which can be one of the following:

  • TR_HTTP: Default transport.

  • TR_USER: Custom transport.

void setURL (java.lang.String url)

java.lang.String getURL( )

Sets or retrieves the HTTP URL of the mobile server.

void setUseFiles(boolean on)

boolean getUseFiles()

Set flag to switch between using streaming or files to transport synchronization data. If set to true, synchronization stores uploaded and downloaded data in a file; otherwise, data is streamed.

When using files, the ose$in.bin file contains the data received from the server. The ose$out.bin file contains the data sent to the server. These files are located in the <mobileclient_root>\bin directory on Win32, Windows Mobile and Linux platfoms or in the directory specified by the DATA_DIRECTORY on the Android or Blackberry platforms.

Note: streaming requires that the underlying client transport stack implements HTTP 1.1. Thus, if a platform does not support streaming, setUseFiles must be congifigured as TRUE.

void setUseResume(boolean on)

boolean getUseResume()

If setUseResume is set to TRUE, enables the resume feature, which attempts to resume sending and receiving data for a synchronization after a network failure. Requires that setUseFiles is also set to TRUE; otherwise, this method is ignored. The resume feature provides a more reliable transport for synchronizing data with minimal overhead.

void setUserTransport(OSETransport t)

Sets custom user-defined transport for synchronization, which you implement in the OSETransport interface. See Section 3.1.1.1.5, "Custom Transport with the OSETransport Class" for more details.

void sync()

Initiates a manual synchronization from within the application.

void addProgressListener(OSEProgressListener pl)

Add progress listener.

void removeProgressListener(OSEProgressListener pl)

Remove progress listener.

boolean getEncryptDatabases()

Get the current value of encrypt database flag.

void setEncryptDatabases()

Enable database encryption for new databases created during sync.

public void shareConnection(String dbName, Object connObj

dbName is database name. connObj is connection object and has to be a valid connection object for particular type of database as used in OSE plugin. For pure java sync client, it must be an instance of corresponding platform-specific database connection class: net.rim.device.api.database.Database for Blackberry client, android.database.sqlite.SQLiteDatabase for Android client, java.sql.Connection for SE client


Example

The following example sets the user name and password to JOHN/john. The mobile server URL is identified as localhost:88. And a synchronization is initiated with the sync method.

/* set up user name and password */
String user = "JOHN";
String pwd  = "john";

/* create OSESession with user John */
OSESession sess = new OSESession(user, pwd.toCharArray());

/* Identify Mobile Server URL */
sess.setURL("localhost:88");

/* Identify the progress listener, myProgressTracker */
sess.setProgress(myProgressTracker);

/* Initiate Sync */
sess.sync();
3.1.1.1.3 OSEProgressListener Interface

The OSEProgressListener interface enables progress updates to be trapped during synchronization.

Sync calls the progress function to report the current stage and the percent of completion of that stage. The parameters for the progress method are listed in Table 3-3:

Method

void progress (int stage, int val);

Table 3-3 OSEProgress Method Parameters

Parameter Description

stage

This is set to one of the constants listed in Table 3-4.

val

This is the percentage of completion for specific stage.


The names of the constants which report the synchronization progress are listed in Table 3-4.

Table 3-4 OSEProgressListener Interface Constants

Constant Name Progress Type

PREPARE

States that the synchronization engine is preparing local data to be sent to the server. This includes getting locally modified data. For streaming implementations this takes a shorter amount of time.

SEND

States that the synchronization engine is sending data to the network.

RECEIVE

States that the synchronization engine is receiving data from the server.

PROCESS

States that the synchronization engine is applying the newly received data from the server to the local data stores.

IDLE

States that the synchronization engine has completed the synchronization process.

COMPOSE

Not supported yet.

APPLY

Not supported yet.


Example

This simple class implements the OSEProgressListener.

class myProgressTracker implements OSEProgressListener;
 {
  public void progress
     (int state, 
     int val)
    {
      System.out.println( "Status: "+state+"="+ val+"%" );
     } //progress
 }
3.1.1.1.4 Selective Synchronization

Selective sync specifies whether a publication should be synchronized or not for the next session. Set the flag with the selectPub method to indicate whether the publication is to be synchronized on the next execution of the sync method. The default setting is NULL for all publications.

Note:

Automatic synchronization selectively synchronizes only publications that contain automatic publication items.

Table 3-5 lists the name and description of parameter for the selectPub method.

Table 3-5 selectPub Parameters

Name Description

publication_name

The name of the publication which is being synchronized. If the value for the publication_name is NULL, it means all publications in the database, which turns off selective sync.

For more information, see Section 2.4, "Creating Publications Using Oracle Database Mobile Server APIs".


3.1.1.1.5 Custom Transport with the OSETransport Class

You can implement a custom user-defined transport for synchronization with the OSETransport interface. Implement the following methods to connect and disconnect the connection and to open the input and output streams. These methods are used for the transport when you provide your implementation in the setUserTransport method in the OSESession class.

Table 3-6 OSETransport methods

Method Description

void connect()

Open transport connection.

void disconnect()

Closes transport connection and releases its resources.

java.io.OutputStream openOutputStream()

Opens output stream.

java.io.InputStream openInputStream()

Opens input stream.


3.1.1.1.6 Sequences Emulated for SQLite Mobile Clients in Replicated Environment

SQLite only supports sequences in a replicated environment. Sequences partitioned per client are useful for generating unique, non-overlapping values to avoid data conflicts.

Note:

For details on using sequences in Berkeley DB, see Section 2.4.1.8, "Creating Client-Side Sequences for the Downloaded Snapshot".

In order to emulate sequence behavior on SQLite, the Sync Client replicates the partitioned sequence information from the server. The mobile client applications can generate unique column values from the partitioned sequence information, which is replicated for every SQLite database in the C$SEQ_CLIENTS table.

The C$SEQ_CLIENTS table has the following definition:

TABLE C$SEQ_CLIENTS(
  "NAME" VARCHAR2(30) NOT NULL, -- sequence name 
  "CUR_VALUE" NUMBER(10,0),  -- current value, set to NULL on the first sync
  "MAX_VALUE" NUMBER(10,0) NOT NULL,  -- max value
  "MIN_VALUE" NUMBER(10,0) NOT NULL,  -- min value
  "PUB_NAME" VARCHAR2(30) NOT NULL,  -- publication name (for internal use)
  "DB_NAME" VARCHAR2(30),  -- database name (for internal use)
  "INCREMENT_BY" NUMBER(10,0) NOT NULL,  -- increment 
  PRIMARY KEY ("NAME"))
 

To select the next sequence value, users can perform the following:

  1. Select CUR_VALUE or MIN_VALUE if CUR_VALUE is NULL.

  2. Add INCREMENT_BY to the CUR_VALUE.

  3. Update the CUR_VALUE with the CUR_VALUE+INCREMENT_BY for the sequence.

Example 3-1 Emulating Sequences on the Mobile Client

The following Java code example demonstrates this functionality:

/* Advance sequence value using sequence properties replicated from the
     * server using C$SEQ_CLIENTS table
     * @param seq sequence name
     * @return int next sequence value
     * @throws DatabaseException if sequence is not found.
     */
    int advanceSequence(String seq) throws Exception
    {
        int seqNextVal = 0;
        Statement statement = _db.createStatement(
            "SELECT ifnull((cur_value+increment_by),min_value) 
                FROM "+SEQUENCES_TABLE+" WHERE name = ?"); 
        statement.prepare();
        statement.bind(1, seq);
        Cursor cursor = statement.getCursor();                        
        if(cursor.next())
        {
            Row row = cursor.getRow();
            seqNextVal = row.getInteger(0);             
        } else {
            throw new Exception("Sequence not found: " + seq);
        }
        cursor.close();
        statement.close();
        statement = _db.createStatement(
            "UPDATE "+SEQUENCES_TABLE+" SET cur_value = 
                 ifnull((cur_value+increment_by),min_value) WHERE name = ?");
        statement.prepare();
        statement.bind(1, seq);
        statement.execute();
        statement.close();
        
        return seqNextVal;
    }
3.1.1.1.7 OSEException Class

This class signals a non-recoverable error during the synchronization process. The OSEException class constructs a clear object. The parameters for the constructor are listed in Table 3-7, "OSEException Constructor Parameter Description":

Constructors

OSEException(int errCode)

OSEException(int errCode,Object arg)

OSEException(int errCode,Object arg, Throwable cause)

OSEException(int errCode, Object arg1, Object arg2)

OSEException(int errCode, Object arg1, Object arg2, Object arg3)

OSEException(int errCode, Object [] args, Throwable cause)

Table 3-7 OSEException Constructor Parameter Description

Parameter Description

errorCode

Error codes are provided within the OSEExceptionConstants class. Error codes for synchronization are provided in the OSEExceptionConstants class. Some OSEException instances are thrown from OSE APIs. Others are used as causes of the synchronization error messages. The message handler returns an error message.

For a complete list the error messages that can be thrown in OSEException, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.

arg, args, arg1, arg2, arg3

Return variables for information within the error message.

cause

The cause of this throwable or NULL if the cause is nonexistent or unknown.


Public Methods

OSEException class extends BaseException.The methods for getting error code, cause and message are listed in Table 3-8, "BaseException Class Public Methods".

Table 3-8 BaseException Class Public Methods

Method Description

getErrorCode()

Returns exception error code

getMessage()

Returns exception message

getCause()

Returns exception cause

toString()

Returns string representation of this BaseException instance. The string contains information from the whole chain of causes if present (cause of this exception is also often instance of BaseException). For each exception in the chain, it contains error code, error message and additional diagnostic information if present.


For a complete list of the error messages that can be thrown in the OSEException, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.

3.1.1.2 OSE Synchronization APIs For Native Applications

You can initiate and monitor synchronization from a native client application. The OSE synchronization methods for the native interface are defined in ose.h, which is located in <ORACLE_HOME>\Mobile\Sdk\include, and implemented in ose.dll, which is located in the <ORACLE_HOME>\Mobile\Sdk\bin directory.

The following sections describe how to set up and initiate synchronization:

3.1.1.2.1 Overview of Native Synchronization API

For starting synchronization, the application should perform the following:

  1. Invoke the oseOpenSession method to initialize the session and its environment and resources.

  2. Set any session options. Invoke the oseSaveUser method to preserve the last user, URL, proxy and optionally the user password for future synchronization events.

  3. Invoke oseSync method to synchronize, which returns after the synchronization completes, an error occurs, or the user interrupts the process.

    Synchronization progress is reported through the oseProgressFunc interface, which is set by the oseSetProgress method.

  4. If synchronization failed, use the oseGetLastError method to retrieve the error message.

  5. When done with the session, invoke the oseCloseSession method to close the session and release its resources.

3.1.1.2.2 Initializing the Environment With oseOpenSession

The oseOpenSession method initializes the synchronization environment—which is passed to each subsequent call with the oseSess handle.

In a multi-threaded environment, you cannot concurrently use a session from multiple threads, even with the same user. Instead, each thread should open its own session with the oseOpenSession method. The only exception is oseCancelSync, which can be executed by another thread.

Note:

Every time you invoke the oseOpenSession method, you must also clean up with oseCloseSession method. These methods should always be called in pairs. See Section 3.1.1.2.9, "Close the Synchronization Environment Using oseCloseSession" for more information.

Syntax

oseError oseOpenSession(const char *user, const char *pwd, oseSess *sess);

Table 3-9 lists the oseOpenSession parameters.

Table 3-9 oseOpenSession Parameters

Name Description

user

User name for synchronization. If NULL, the last saved user name is provided. If the last user name was not saved, the OSE_ERR_USER_NOT_SPECIFIED error is returned.

pwd

User password. If NULL, the last saved password for this user is provided if it was previously saved. Alternatively, the password can be provided later if the OSE_OPT_PASSWORD option is specified. If, at the time of sync, the password is not provided and was not previously saved, the OSE_ERR_PWD_NOT_SPECIFIED error is returned.

sess

Pointer to a session handle into which the new session is returned. This handle cannot be NULL.


This call initializes the oseSess synchronization environment handle—which holds context information for the synchronization engine—and restores any session options that were saved with the last oseSaveUser method invocation. See Section 3.1.1.2.4, "Saving User Settings With oseSaveUser" for more information on oseSaveUser.

If successful, zero is returned; otherwise, an OSE error code is returned.

3.1.1.2.3 Setting Session Options

You can set certain session options explicitly with the set session methods. Every session option, except OSE_OPT_NEW_PASSWORD, is set for the duration of the session, unless it is explicitly reset with the appropriate set session option method.

When the session is created, the initial value for each option is loaded from the following:

  • The ose.ini file.

  • If it is not set in the ose.ini file, the option value is loaded from the saved options in the internal OSE Meta files. The OSE Meta files save session information that was either set on the previous synchronization or set explicitly with the appropriate set session option method. New values for options set by the user, such as OSE_OPT_URL or OSE_OPT_PROXY, are saved in the internal OSE Meta files during next synchronization.

  • If not set in the ose.ini file or saved as within the OSE Meta files, the default value is taken for each option.

Options are separated into boolean, numeric, and string options:

  • Boolean options are those options that can only be set to OSE_TRUE or OSE_FALSE.

  • Numeric options are set to an integer value.

  • String options are those options that are defined with a character string.

The following sections describe the session options and the methods that can get or set the values for these options:

Boolean and Numeric Session Options

Use the oseSetNumOption and oseGetNumOption methods to set and get the boolean and numeric session options.

oseSetNumOption

oseError oseSetNumOption(oseSess sess, int opt, long val);

Table 3-10 lists the oseSetNumOption parameters.

Returns zero if the option is set successfully. An OSE error code is returned if an invalid option code or an invalid value is specified.

Table 3-10 oseSetNumOption Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

int opt

Option code. See Table 3-12 for a list of all of the options that can bet set by this method.

long val

The option value to set for the session. See Table 3-12 for potential values for this option.


oseGetNumOption

oseError oseGetNumOption(oseSess sess, int opt, long *val);

Table 3-11 lists the oseGetNumOption parameters.

Returns zero if the option is retrieved successfully. An OSE error code is returned if an invalid option code is specified.

Table 3-11 oseGetNumOption Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

int opt

Option code. See Table 3-12 for a list of all of the options that can bet retrieved by this method.

long *val

Pointer to a variable into which to return the option value. The pointer cannot be NULL. See Table 3-12 for potential values for this option.


Table 3-12 lists all boolean and numeric synchronization options and potential values. For all boolean options, the value can only be either OSE_TRUE and OSE_FALSE.

Table 3-12 Numeric and Boolean Session Options

Session Option Description

OSE_OPT_SYNC_DIRECTION

Specifies the synchronization direction with one of the following numeric constants:

  • Bidirectional sync (default): OSE_SYNC_DIR_SENDRECEIVE, value 0.

  • Data is only sent, but not received, OSE_SYNC_DIR_SEND, value 1.

  • Data is only received, but not sent: OSE_SYNC_DIR_RECEIVE, value 2.

OSE_OPT_ENCRYPTION_TYPE

Specifies the encryption type, which indicates how the data is encrypted when transfered over the network.

  • AES encryption: OSE_ENC_TYPE_AES, value 0.

  • HTTPS protocol over secure sockets: OSE_ENC_TYPE_SSL, value 1.

  • No encryption: OSE_ENC_TYPE_NONE, value 2.

OSE_OPT_TRANSPORT_TYPE

Transport type designates the protocol used to transfer data to and from the mobile server.

  • Data is transfered using the HTTP protocol: OSE_TR_TYPE_HTTP, value 0.

  • Data is transfered by the custom transport provided by the application: OSE_TR_TYPE_USER, value 1.

  • Data is transfered manually using File-Based Sync): OSE_TR_TYPE_FILE, value 2.

OSE_OPT_TRANSPORT_DIRECTION

Transport direction. This is used to indicate connected or disconnected (that is, File-Based) sync.

  • Connected synchronization (default). This can be used with either bidirectional or unidirectional synchronization. If synchronization direction is set to OSE_SYNC_DIR_SEND, it specifies send-only synchronization over connected transport, where the data is sent and an acknowledgement is received. OSE_TR_DIR_SENDRECEIVE, value 0.

  • Disconnected synchronization, send-only synchronization. Data is sent without acknowledgement. This can only be used with the OSE_TR_TYPE_FILE transport type. OSE_TR_DIR_SEND, value 1.

  • Disconnected synchronization, receive-only synchronization. This can only be used with the OSE_TR_TYPE_FILE transport type. OSE_TR_DIR_RECEIVE, value 2.

OSE_OPT_SAVE_PASSWORD

Boolean option. Indicates whether the user synchronization password should be saved on the client, which means that it will not need to be explicitly provided for future sessions.

The password is saved in an encrypted form.

OSE_OPT_BACKGROUND

Boolean option. If OSE_OPT_BACKGROUND is set to true, synchronization is more performant and consists solely of DML operations, with no schema updates.

OSE_FALSE is the default, indicating normal synchronization.

OSE_OPT_SYNC_PRIO

Synchronization priority constants:

  • High priority: OSE_PRIO_HIGH, value 0.

  • Normal priority: OSE_PRIO_DEFAULT, value 1.

OSE_OPT_SYNC_APPS

Boolean option. Indicates whether synchronization should download a list of application and client updates that can be installed later.

OSE_TRUE is the default.

Also, see the OSE_OPT_HAS_SOFT_UPDATES option.

OSE_OPT_SYNC_NEW_PUB

Boolean option. Indicates whether new publications can be created during synchronization.

OSE_TRUE is the default.

OSE_OPT_FORCE_REFRESH

Boolean option. Indicates if the synchronization is force-refresh. Ignores client changes and reloads all client data from the mobile server.

OSE_FALSE is the default.

OSE_OPT_USE_FILES

Boolean option. Indicates whether files are used to temporarily store the data either before it is sent or after it is received. If enabled, client changes are first saved into a file named oseOutFile.bin (default), then sent to the mobile server. The received data is saved to another file named oseInFile.bin (default) and then read and transferred to the database from that file. This is used for the resume transport or for protocols where the total data size to be sent needs to be known in advance, such as HTTP 1.0. OSE_FALSE is the default.

The related ose.ini parameter is OSE.FILES.

Also, see the OSE_OPT_RESUME_TRANSPORT option.

OSE_OPT_RESUME_TRANSPORT

Boolean option. Indicates whether the resume protocol should be used on top of the synchronization transport. To use this option, the OSE_OPT_USE_FILES option must be enabled. If not already set, OSE_OPT_USE_FILES will be set implicitly.

The resume protocol is typically used for lengthy synchronization sessions over unstable network connections. It resumes sending and receiving data from the point of a network disconnect, thus avoiding the restart of synchronization from scratch. This option is used only with connected transport (OSE_TR_DIR_SENDRECEIVE).

OSE_FALSE is the default.

Related ose.ini parameter is OSE.RESUME.

OSE_OPT_HAS_SOFT_UPDATES

Boolean read-only option. You can only retrieve the value with the oseGetNumOption method. This option indicates whether any updates are available for the client after the last synchronization. This is used by the mSync tool to specify whether it should launch the update utility to retrieve updates.

Also, see the OSE_OPT_SYNC_APPS option.

OSE_OPT_ENCRYPT_DATABASES

Boolean option. Indicates whether any databases newly created during synchronization should be encrypted. The encryption key for each database is either retrieved from the synchronization keystore or generated based on the user password, if not found in the keystore. Applications can define their own keys for each database before database creation with the keystore APIs.

OSE_FALSE is the default.

The related ose.ini parameter is OSE.ENCRYPTDB.

You can set, get, and remove the encryption key with the oseSetDBKey, oseGetDBKey, and oseRemoveDBKey methods, which are described in Section 3.1.1.2.13, "Set and Retrieve Data Encryption Keys".


String Session Options

Use the oseSetStrOption and oseGetStrOption methods to set and get the string session options. Every string option, except the OSE_OPT_APP_ROOT option, defaults to NULL if not loaded during session initialization.

oseSetStrOption

oseError oseSetStrOption(oseSess sess, int opt, const char *val);

Table 3-13 lists the oseSetStrOption parameters.

Returns zero if the option is set successfully. An OSE error code is returned if an invalid option code or an invalid value is specified.

Table 3-13 oseSetStrOption Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

int opt

Option code. See Table 3-15 for a list of all of the options that can bet set by this method.

const char *val

The option value to set for the session. See Table 3-15 for potential values for this option.


oseGetStrOption and oseGetStrOptionNC

oseError oseGetStrOption(oseSess sess, int opt, char *val, int bufSize);
oseError oseGetStrOptionNC(oseSess sess, int opt, const char **val);

The difference between the two calls is that the oseGetStrOptionNC does not require you to allocate the buffer for the returned string. Instead, a pointer to a string is passed. The string is NULL-terminated, which is how the length is known.

Table 3-14 lists the oseGetStrOption parameters.

Returns zero if the option is set successfully. OSE_ERR_INVALID_STR_OPT error is returned if an invalid option code is specified. OSE_ERR_INVALID_BUFFER error is returned if the buffer provided is too small to store the value and the terminating NULL character.

Table 3-14 oseGetStrOption Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

int opt

Option code. See Table 3-15 for a list of all of the options that can bet retrieved by this method.

char *val

For oseGetStrOption: Pointer to a buffer into which to return the option value. The pointer cannot be NULL.

const char **val

For oseGetStrOptionNC: Pointer to a character pointer into which return the value. The pointer cannot be NULL. The memory for the option value is stored within the OSE engine and is valid until next call to oseGetStrOptionNC.

int bufSize

Size of the buffer.


Table 3-15 lists all string session options and potential values.

Table 3-15 Session String Options

Option Option Description

OSE_OPT_URL

Mobile server URL.

OSE_OPT_PROXY

HTTP proxy, if present, as host:port or host, where the port defaults to 80.

OSE_OPT_NEW_PASSWORD

New password provided to modify the synchronization password during the next synchronization. This option needs to be set each time the password needs to be changed for the session.

OSE_OPT_USER_NAME

Read-only option, used to retrieve the synchronization user name.

OSE_OPT_PASSWORD

Used to set the synchronization password in the current session. This overwrites the password that was originally provided to the oseOpenSession method or retrieved from the OSE configuration files. This is only used to set the synchronization password in the case that a NULL password was passed to the oseOpenSession method.

This password is saved in the OSE Meta files if the OSE_OPT_SAVE_PASSWORD option was enabled.

OSE_OPT_APP_ROOT

Root directory for internal synchronization files. By default, it is the synchronization client installation bin directory.

OSE_OPT_FILE_URL

File URL used for a file-based sync. Specifies the path to the file, which can optionally prefixed by file://.


3.1.1.2.4 Saving User Settings With oseSaveUser

The oseSaveUser method saves the last user, URL, proxy and optionally the user password for future synchronization events into an OSE Meta file. However, the password is saved only if the OSE_OPT_SAVE_PASSWORD option is enabled. These settings are normally saved at the end of each synchronization, if changes are detected. These settings can be used for the current session or used by the oseOpenSession method to initialize the environment when next invoked.

Returns zero if successful and OSE_ERR_INTERNAL_ERROR if an input/output error occured during saving.

Syntax

oseError oseSaveUser(oseSess sess);

Table 3-16 lists the oseSaveUser parameters.

Returns zero if successful. Returns the OSE_ERR_INTERNAL_ERROR error if an input/output error occurs when saving the settings.

Table 3-16 oseSaveUser Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.


This saves or overwrites the user settings into an OSE Meta file on the client side.

Note:

See Section 3.1.1.2.3, "Setting Session Options" for details on the user settings saved.
3.1.1.2.5 Start the Synchronization With the oseSync Method

Starts the synchronization process synchronously.

Returns zero if synchronization is successful. Returns OSE_ERR_INVALID_SESS if session handle was invalid and OSE_ERR_SYNC_CANCELED if synchronization was canceled from another thread by the oseCancelSync method. Other OSE error codes are returned if the synchronization fails.

Syntax

oseError oseSync(oseSess sess);

Table 3-17 lists the oseSync parameters.

Table 3-17 oseSync Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.


3.1.1.2.6 Manage What Publications Are Synchronized With oseSelectPub

Selective sync allows only certain publications to be synchronized. The oseSelectPub method selects a publication for selective sync, which specifies if it is to be synchronized on the next synchronization. Selective sync only works if you have first performed at least one synchronization for the client. Then, a selective sync for the publication occurs at the next invocation of the oseSync method.

The application can select publications needed by repeatedly calling the oseSelectPub method. To revert to the regular (non-selective) synchronization selection, invoke this method with NULL as the publication name.

The default setting is for all publications to be synchronized.

Syntax

oseError oseSelectPub(oseSess sess, const char *pub);

Table 3-18 lists the oseSelectPub parameters.

Returns zero if successful. Returns the OSE_ERR_PUB_NOT_FOUND error if the publication with the provided name was not found.

Table 3-18 oseSelectPub Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

pub

Publication name to select for the next synchronization. NULL deselects all publications and reverts back to a non-selective synchronization.


3.1.1.2.7 See Progress of Synchronization with Progress Listening

You can implement a progress callback function that is called so that you can be notified of the progress of the synchronization operations. If you create and set the progress callback method, the mobile client invokes this callback method at appropriate times while the oseSync method is executing.

The following is the declaration of the progress callback function.

oseError (* oseProgressFunc)(void *ctx, int stage, int val);

When the oseOpenSession invokes the method you declare in oseSetProgress, it provides the following information as input to your method:

  • ctx—A pointer to user-defined state information for the callback. This handle is a pointer to a user-defined structure. Since the oseProgressFunc callback method is user-implemented, it should know how to process the user-defined structure. The user context structure may or may not be initialized by the application before calling the oseSetProgress method.

  • stage—The stage in the synchronization process, which is one of the following values, where these values are defined in ose.h:

    Table 3-19 Description of the Stage Values

    Stage Value Value Description

    OSE_SYNC_STATE_IDLE

    0

    No synchronization occuring.

    OSE_SYNC_STATE_PREPARE

    1

    Preparing data into temporary files. This state only occurs if the OSE_OPT_USE_FILES option is enabled.

    OSE_SYNC_STATE_SEND

    2

    Sending the data to the mobile server.

    OSE_SYNC_STATE_RECEIVE

    3

    Receiving data from the mobile server.

    OSE_SYNC_STATE_PROCESS

    4

    Processing data from temporary file. This state only occurs if the OSE_OPT_USE_FILES option is enabled.


  • val—The percentage completed in the particular stage that synchronization is in from 0 to 100.

After you define the progress callback function, you can initialize it with the mobile client by executing the oseSetProgress method:

oseError oseSetProgress(oseSess sess, void *ctx, oseProgressFunc pf);

You can unregister the progress callback function by executing oseSetProgress method as follows:

oseSetProgress(oseSess, NULL, NULL);

Table 3-20 lists the oseSetProgress parameters.

Table 3-20 oseSetProgress Parameters

Name Description

sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

ctx

A pointer to the session environment settings. This handle is a pointer to a user-defined structure. Since the oseProgressFunc callback method is user-implemented, it should know how to process the user-defined structure. The user context structure may or may not be initialized by the application before calling the oseSetProgress method.

pf

The progress callback function.


3.1.1.2.8 Cancel a synchronization event using oseCancelSync

Cancels the synchronization operation from another thread and returns immediately without waiting for the synchronization operation to abort.

Syntax

oseError oseCancelSync(oseSess sess);

Table 3-21 lists the oseCancelSync parameters.

Returns zero, if successful. Returns OSE_ERR_INVALID_SESS if the oseSess session handle is invalid.

Table 3-21 oseCancelSync Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.


3.1.1.2.9 Close the Synchronization Environment Using oseCloseSession

Clears and performs a cleanup of the synchronization environment and resources. This function must be invoked for every oseOpenSession, even if oseSync has not been executed even once.

Returns zero, if successful. Returns OSE_ERR_INVALID_SESS if the oseSess session handle is invalid.

Syntax

oseError oseCloseSession(oseSess sess);

Table 3-22 lists the oseCloseSession parameters.

Table 3-22 oseCloseSession Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.


3.1.1.2.10 Retrieve Synchronization Error Information with oseGetLastError

Retrieves the extended synchronization error message and code from the last call. This information contains the last OSE error info as well as any internal errors that caused the error.

Syntax

oseError oseGetLastError(oseSess sess, const oseErrorDesc **errDesc);

Table 3-23 lists the oseGetLastError parameters.

Returns zero if successful. Returns the OSE_ERR_INVALID_SESS error if the session handle was invalid. Returns the OSE_ERR_INTERNAL_ERROR error if a system error has occured.

Table 3-23 oseGetLastError Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. This handle can be NULL if trying to retrieve error information from a failed oseOpenSession call.

oseErrorDesc errDesc

A pointer to an oseErrorDesc pointer into which the oseErrorDesc pointer is returned. The pointer cannot be NULL. The structures referenced by this pointer are only valid until the next OSE call.


The oseErrorDesc structure is defined as follows:

typedef struct _oseErrorDesc {
  oseError code;                /* error code */
  const char *type;             /* a string describing the type of error */
  const char *msg;              /* error message */
  struct _oseErrorDesc *cause;  /* underlying cause, if present */
} oseErrorDesc;

If the error has an underlying cause, the oseErrorDesc.cause points to another oseErrorDesc structure, which in turn can have its own cause, and so on. This is useful if the OSE call returns an OSE_ERR_INTERNAL_ERROR, which can be further defined within another oseErrorDesc structure. If the cause is not present, oseErrorDesc.cause is NULL.

Note:

The memory for oseErrorDesc structure is allocated within the mobile client and should not be freed by the application.
3.1.1.2.11 Enable File-Based Synchronization through Native APIs

When you want to use file-based synchronization, you must enable file-based synchronization. Once enabled, then when you initiate manual synchronization, then the synchronization file is created. See Section 5.10, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Mobile Server Administration and Deployment Guide for more details on file-based synchronization.

To enable file-based synchronization programmatically, perform the following:

  1. Ensure that any previous settings of the File-Based Sync properties are set to NULL.

  2. Initialize the session with the oseOpenSession method providing the user name and password for the user that is initializing the synchronization.

  3. Specify File-Based Sync by setting OSE_OPT_TRANSPORT_TYPE to OSE_TR_TYPE_FILE.

  4. Specify the synchronization direction in the OSE_OPT_TRANSPORT_DIRECTION option as follows:

    • OSE_TR_DIR_SEND: Send, which creates the synchronization file.

    • OSE_TR_DIR_RECEIVE: Receive, which takes in a file from the mobile server.

  5. Set the OSE_OPT_FILE_URL to the path and filename of the file.

    • If sending, the path and filename is where the mobile client saves the uploaded data for the mobile server. This file is created with the mobile client transactions destined for the mobile server.

    • If receiving, the path and filename where the data file that was received from the mobile server. This file is loaded and processed within the mobile client.

3.1.1.2.12 Share the Database Connection

Provides a database connection handle from the application to use in the OSE engine, instead of the OSE engine opening its own database connection, which is the default. The connection handle is set for the duration of the session unless explicitly unset by the same call with a NULL connection handle value.

Applications can keep open cursors while invoking synchronization. If the connection is not shared, the OSE engine needs to create its own connection and start a new exclusive transaction; however, SQLite does not support creating exclusive transactions when another connection has open cursors.

Syntax

oseError oseShareConnection(oseSess sess, const char *db, void *connHdl);

Table 3-24 lists the oseShareConnection parameters.

Returns zero, if successful. Returns OSE_ERR_PLUGIN_ERROR if a plugin error has occured, the value of which can be retrieved with the oseGetLastError method.

Table 3-24 oseShareConnection Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

const char *db

Database name for which the connection handle is provided.

void *connHdl

Valid database connection handle for a particular type of database that is used in the OSE plugin. For example, for SQLite and Berkeley DB, the connection handle should be of type sqlite3 *. A NULL value will unshare the connection and the OSE engine opens its own database connection.


3.1.1.2.13 Set and Retrieve Data Encryption Keys

An application can provide its own custom key to encrypt each database instead of using a key generated from the synchronization password. Subsequently, the key in the key store is used by the mobile client to open the database after it is created.

The oseSetDBKey method sets a database encryption key provided by the application in the OSE key store for the database. Applications need to re-execute this call when they re-encrypt the database with a different key, so that OSE engine has the current key to access the database during synchronization.

For more details, see the description for the OSE_OPT_ENCRYPT_DATABASES option in Table 3-12.

Syntax

oseError oseSetDBKey(oseSess sess, const char *db, 
       const void *key, oseSize keyLen); 

Table 3-25 lists the oseSetDBKey parameters.

Returns zero, if successful. Returns the OSE_ERR_INTERNAL_ERROR error if the internal error occured in the key store.

Table 3-25 oseSetDBKey Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

db

Database name for which to set the key.

key

Buffer with the provided key.

keyLen

Length of the provided key.


The oseGetDBKey method retrieves the database encryption key from the OSE key store. For more details, see the description for the OSE_OPT_ENCRYPT_DATABASES option in Table 3-12.

Syntax

oseError oseGetDBKey(oseSess sess, const char *db, void *buf, 
     oseSize bufSize, oseSize *retLen);

Table 3-26 lists the oseGetDBKey parameters.

Returns zero, if successful. Returns the OSE_ERR_INVALID_BUFFER error if the buffer was too small to store the key. Returns the OSE_ERR_INTERNAL_ERROR error if the internal error occured in the key store.

Table 3-26 oseGetDBKey Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

db

Database name for which to retrieve the key.

buf

Buffer to store the key.

bufSize

Size of the buffer that stores the key.

retLen

Actual length of the key. The length will be zero if the key is not found.


The oseRemoveDBKey method removes the database encryption key from the OSE key store. For more details, see the description for the OSE_OPT_ENCRYPT_DATABASES option in Table 3-12.

Syntax

oseError oseRemoveDBKey(oseSess sess, const char *db);

Table 3-27 lists the oseRemoveDBKey parameters.

Returns zero, if successful. Returns the OSE_ERR_INTERNAL_ERROR error if the internal error occured in the key store.

Table 3-27 oseRemoveDBKey Parameters

Name Description

oseSess sess

Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns OSE_ERR_INVALID_SESS if the handle is NULL.

db

Database name from which the key is removed.


3.1.1.3 OSE .Net Synchronization API

The following sections describe how you can use the OSE .Net Synchronization APIs to build your own client synchronization initiation on mobile clients:

Note:

For more details on these classes, refer to the Oracle Database Mobile Server .Net API.
3.1.1.3.1 Overview

The .Net interface for mobile client synchronization resides in the Oracle.OpenSync.OSE namespace and is implemented in Oracle.OpenSync.dll.

The .Net interface provides for the following functions:

  • Setting client-side user profiles containing data.

  • Starting the synchronization process.

  • Tracking the progress of the synchronization process.

3.1.1.3.2 Enumerations Used by OSESession

Table 3-28 lists all enumerations and values that can be used by OSESession APIs.

Table 3-28 Enumerations

Enumeration Members

SyncDirection

Specifies the synchronization direction as follows:

  • SyncDirection.SendReceive: Bidirectional sync (default). Value 0.

  • SyncDirection.Send: Data is only sent, but not received. Value 1.

  • SyncDirection.Receive: Data is only received, but not sent. Value 2.

EncryptionType

Specifies the encryption type, which indicates how the data is encrypted when transfered over the network.

  • EncryptionType.AES: AES encryption. Value 0.

  • EncryptionType.SSL: HTTPS protocol over secure sockets. Value 1.

  • EncryptionType.None: No encryption. Value 2.

TransportType

Transport type designates the protocol used to transfer data to and from the mobile server.

  • TransportType.Http: Data is transfered using the HTTP protocol. Value 0.

  • TransportType.User: Data is transfered by the custom transport provided by the application. Value 1.

  • TransportType.File: Data is transfered manually using File-Based Sync). Value 2.

DataPriority

Synchronization priority:

  • DataPriority.High: High priority. Value 0.

  • DataPriority.Normal: Normal priority. Value 1.

SyncProgressStage

Synchronization stage:

  • SyncProgressStage.Prepare: States that the synchronization engine is preparing local data to be sent to the server in a local file. This includes getting locally modified data. For streaming implementations this takes a shorter amount of time. Only used if OSESession.UseFiles is true.

  • SyncProgressStage.Send: States that the synchronization engine is sending data to the network.

  • SyncProgressStage.Receive: States that the synchronization engine is receiving data from the server.

  • SyncProgressStage.Process: States that the synchronization engine is applying the newly received data from the server to the local data stores. Only used if OSESession.UseFiles is true.

  • SyncProgressStage.Idle: States that the synchronization engine has completed the synchronization process.


3.1.1.3.3 OSESession Class

OSESession enables setting synchronization parameters and options. This class exposes APIs to invoke and control synchronization by using the provided synchronization options.

In a multi-threaded environment, you cannot execute OSESession methods from multiple threads. Each thread should open its own session. The only exception is CancelSync, which can be executed by another thread.

The parameters for the constructor are listed in Table 3-29.

Constructors

OSESession( )

OSESession( String user )

OSESession( String user, char[] pwd)

Table 3-29 OSESession Class Constructor

Parameter Description

user

A string containing the name used for authentication by the mobile server.

password

A character array containing the user password.


Public Methods

The public methods and their parameters for the OSESession class are listed in Table 3-30:

Table 3-30 OSESession Class Public Method Parameters

Method Description

CancelSync( )

Attempts to cancel the synchronization process with a non-blocking call.

Close()

Closes any active database connections that the session maintains. This method is called before application exits.

SaveUser()

The SaveUser method saves session options and user information.

SelectPub(String name)

UnselectPubs()

The SelectPub method provides the publication name, adds the publication to the list of publications to be synchronized selectively.

The UnselectPubs method reverts back to normal synchronization for all publications.

See Section 3.1.1.3.6, "Selective Synchronization" for more information.

event OSEProgressHandler SyncProgress

Set synchronization progress listener with the SyncProgress event. For more details, see Section 3.1.1.3.5, "OSEProgressHandler Interface".

Sync()

Initiates a manual synchronization from within the application.

ShareConnection(string dbName, IntPtr hdl)

UnshareConnection(string dbName)

Provides database connection handle from the application to use in the OSE engine, instead of engine opening its own database connection, which is default. The connection handle is set for the duration of the session unless explicitly unset by calling UnshareConnection().

Parameters include the database name and a connection handle, which has to be a valid native handle for the particular type of database that is used in the OSE plugin. For example, SQLIte and Berkeley DB handle should be of native type sqlite3 *.


OSESession Class Properties

The following documents the properties for the OSESession class.

  • Read-write properties read or write the value of a field with get and set accessors.

  • Read-only properties read the value of a field with the get accessor.

  • Write-only properties set the value of a field with the set accessor.

Boolean properties get or set the value of a field to either true or false.

Table 3-31 lists all properties. Table 3-28 lists all enumerations.

Table 3-31 OSESession Properties

Property Accessors Description

SyncDirection

Read-write

Gets or sets the synchronization direction on the SyncDirection enumeration. The default is SyncDirection.SendReceive.

EncryptionType

Read-write

Gets or sets the encryption type on the EncryptionType enumeration. The default for which is EncryptionType.AES.

TransportType

Read-write

Gets or sets the transport type on the TransportType enumeration. The default for which is TransportType.Http.

SyncPriority

Read-write

Gets or sets the synchronization priority on the DataPriority enumeration. The default for which is DataPriority.Normal.

SavePassword

Read-write

Boolean property. The default is FALSE. Indicates whether the user synchronization password should be saved on the client, which means that it will not need to be explicitly provided for future sessions.

The password is saved in an encrypted form.

Background

Read-write

Boolean property. Indicates whether the next synchronization should be an automatic synchronization.

The default is FALSE, indicating manual synchronization.

SyncApps

Read-write

Boolean property. Indicates whether synchronization should download a list of application and client updates that can be installed later.

The default is TRUE.

SyncNewPub

Read-write

Boolean property. Indicates whether new publications can be created during synchronization.

The default is TRUE.

ForceRefresh

Read-write

Boolean property. Indicates if the synchronization is force-refresh. Ignores client changes and reloads all client data from the mobile server.

The default is FALSE.

UseFiles

Read-write

Boolean property. Indicates whether files are used to temporarily store the data either before it is sent or after it is received. If enabled, client changes are first saved into a file named oseOutFile.bin (default), then sent to the mobile server. The received data is saved to another file named oseInFile.bin (default) and then read and transferred to the database from that file. This is used for the resume transport or for protocols where the total data size to be sent needs to be known in advance, such as HTTP 1.0. The default is FALSE.

The related ose.ini parameter is OSE.FILES.

UseResume

Read-write

Boolean property. Indicates whether the resume protocol should be used on top of the synchronization transport. To use this option, the UseFiles property must be enabled. If not already set, UseFiles will be set implicitly.

The resume protocol is typically used for lengthy synchronization sessions over unstable network connections. It resumes sending and receiving data from the point of a network disconnect, thus avoiding the restart of synchronization from scratch. This property is used only with connected transport (SyncDirection.SendReceive).

The default is FALSE.

Related ose.ini parameter is OSE.RESUME.

URL

Read-write

Mobile server URL property.

Proxy

Read-write

HTTP proxy property, if present, as host:port or host, where the port defaults to 80 if not specified.

NewPassword

Write-only

New password provided to modify the synchronization password during the next synchronization. This option needs to be set each time the password needs to be changed for the session.

User

Read-only

Read-only property, used to retrieve the synchronization user name.

Password

Write-only

Used to set the synchronization password in the current session. This overwrites the password that was originally provided to the oseOpenSession method or retrieved from the OSE configuration files. This is only used to set the synchronization password in the case that a NULL password was passed to the oseOpenSession method.

This password is saved in the OSE Meta files if the SavePassword property was enabled.

AppRoot

Read-write

Root directory for internal synchronization files. By default, it is the synchronization client installation bin directory.


Example

/* Create the OSESession object */
oseSess = new OSESession(user, pwd != NULL ?
   pwd.ToCharArray() : NULL);
 
/* Assign Session options */
if (url != NULL)
  oseSess.URL = url;
if (f)
  oseSess.UseFiles = true;
if (sp)
  oseSess.SavePassword = true;
if (bResume)
  oseSess.UseResume = true;
if (ne)
  oseSess.EncryptionType = EncryptionType.None;
else if (ssl)
  oseSess.EncryptionType = EncryptionType.SSL;

/* Save the session options */
if (!ns)
  oseSess.SaveUser();

/* Assign a progress handler named syncProgress */
oseSess.SyncProgress += new OSEProgressHandler(syncProgress);
 
/* Perform the synchronization */
oseSess.Sync();
3.1.1.3.4 OSEProgressEventArgs Properties

The following documents the properties for the OSEProgressEventArgs class, which are used primarily in the OSEProgressHandler interface.

  • Read-write properties read or write the value of a field with get and set accessors.

  • Read-only properties read the value of a field with the get accessor.

  • Write-only properties set the value of a field with the set accessor.

Table 3-32 lists all properties.

Table 3-32 OSEProgressEventArgs Properties

Property Accessors Description

Stage

Read-only

Gets the synchronization stage from the SyncProgressStage enumeration. The default for which is SyncProgressStage.Idle.

Value

Read-only

Gets the percentage of completion for a specific Stage.


3.1.1.3.5 OSEProgressHandler Interface

The OSEProgressHandler interface enables progress updates to be trapped during synchronization.

Sync calls the a registered progress handler to report the current stage and the percent of completion of that stage, which can be retrieve with the Stage and Value properties, as described in Table 3-31.

Syntax

public delegate void OSEProgressHandler(object sender,
     OSEProgressEventArgs args);

Table 3-33 OSEProgressHandler Parameters

Name Description

object sender

Sender of the event, which is set to the OSESession object to which the handler is attached.

OSEProgressEventArgs args

Progress event arguments that include Stage and Value properties, which are described in Table 3-32.


You can implement your own progress handler by providing the same parameter declaration as in the OSEProgressHandler declaration. The following implements a progress handler called syncProgress, which takes in a sender and an OSEProgressEventArgs structure. It evaluates the Stage and the Value of the OSEProgressEventArgs structure when invoked by the Sync Agent.

static void syncProgress(object sender, OSEProgressEventArgs args)
        {
            if (args.Stage == SyncProgressStage.Idle)
                return;
            
            if (prevVal == -1)
            {
                Console.Write(args.Stage);
                prevVal = 0;
            }
            
            int dots = (args.Value - prevVal) / 2;
            for(int i = 0; i < dots; i++)
                Console.Write('.');
 
            if (args.Value == 100)
            {
                Console.WriteLine();
                prevVal = -1;
            }
            else
                prevVal = args.Value;
        }

Then, you set the progress handler by setting the SyncProgress event, as shown below:

oseSess.SyncProgress += new OSEProgressHandler(syncProgress);
3.1.1.3.6 Selective Synchronization

Selective sync specifies whether a publication should be synchronized or not for the next session. Provide the name of the publication with the SelectPub method to indicate whether the publication is to be synchronized on the next execution of the Sync method. The default setting is NULL for all publications.

Note:

Automatic synchronization selectively synchronizes only publications that contain automatic publication items.

Table 3-34 lists the name and description of parameter for the SelectPub method.

Table 3-34 SelectPub Parameters

Name Description

name

The name of the publication which is being synchronized. If the value for the name is NULL, it means all publications in the database, which turns off selective sync. You can also turn off selective sync with the UnselectPubs method.

For more information, see Section 2.4, "Creating Publications Using Oracle Database Mobile Server APIs".


3.1.1.3.7 OSEException Class

This class signals an error during the synchronization process.

The OSEException read-only properties are listed in Table 3-35.

Table 3-35 OSEException Properties

Parameters Description

ErrorCode

Gets the exception error code. The error code can be one of the OSEErrorCode enumeration values, which are documented in the "OSEException Error Messages" in the Oracle Database Mobile Server Message Reference.

Kind

Gets the exception type name.

InnerException

Use the InnerException property to get underlying cause of the OSEException.


Constructors

OSEException(int errorCode)

OSEException(int errorCode, string errorMessage)

Table 3-36 OSEException Parameter Description

Parameter Description

errorCode

The error code can be one of the OSEErrorCode enumeration values, which are documented in the "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.

errorMessage

A readable text message that provides extra information.


For a complete list of the error messages in the OSEException class, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.

3.1.2 SQLite Synchronization API for .Net Clients

You can initiate and monitor synchronization from an .Net provider application. See the SQLite documentation for information on the .Net provider.

3.1.3 OCAPI Synchronization API for the Mobile Client

Note:

The following OCAPI synchronization APIs are currently supported for the mobile client, but are not the direction recommended for future applications. To develop applications for future support, migrate existing applications to use the Section 3.1.1, "OSE Synchronization API for Applications on Mobile Clients".

The following sections describe the OCAPI synchronization APIs:

3.1.3.1 OCAPI Synchronization APIs For C or C++ Applications

You can initiate and monitor synchronization from a C or C++ client application. The OCAPI synchronization methods for the C/C++ interface are contained in ocapi.h and ocapi.dll, which are located in the <ORACLE_HOME>\Mobile\bin directory.

A C++ example is provided in the <ORACLE_HOME>\Mobile\Sdk\Samples\sync\win32\msync\src directory. The source code is contained in SimpleSync.cpp. The executable—SimpleSync.exe—is in the <ORACLE_HOME>\Mobile\Sdk\Samples\sync\msync\bin directory.

The following sections describe how to set up and initiate synchronization:

3.1.3.1.1 Overview of C/C++ Synchronization API

For starting synchronization, the application should perform the following:

  1. Create, memset, and initialize the ocEnv structure.

  2. Invoke the ocSessionInit() method.

  3. Set any optional fields in the ocEnv structure, such as user name and password. If you want to preserve all optional fields set in the ocEnv structure for future synchronization sessions, then execute the ocSaveUserInfo method.

  4. Optionally, you can set proxy information with the ocSetSyncOption method or specify the synchronization type for each table with the ocSetTableSyncFlag function.

  5. Invoke the ocDoSynchronize() method, which returns after the synchronization completes, an error occurs, or the user interrupts the process. While executing, the ocDoSynchronize function invokes any callback function set in the ocEnv.fnProgress field. The callback function must not call any blocking functions, as this process is not reentrant or threaded.

  6. Once synchronization completes, then invoke the ocSessionTerm() method to clear the ocEnv data structure.

  7. If synchronization failed, then use the ocGetLastError function to retrieve the error message.

For an example, see the SimpleSync.cpp sample code.

3.1.3.1.2 Initializing the Environment With ocSessionInit

The ocSessionInit function initializes the synchronization environment—which is contained in the ocEnv structure or was created with ocSaveUserInfo. For more information, see Section 3.1.3.1.7, "Managing User Settings With ocSaveUserInfo".

Note:

Every time you invoke the ocSessionInit function, you must also clean up with ocSessionTerm. These functions should always be called in pairs. See Section 3.1.3.1.12, "Clear the Synchronization Environment Using ocSessionTerm" for more information.

Syntax

int ocSessionInit( ocEnv env );

Table 3-37 lists the ocSessioninit parameter and its description.

Table 3-37 ocSessionInit Parameters

Name Description

env

An ocEnv class, which contains the synchronization environment.


This call initializes the ocEnv structure—which holds context information for the synchronization engine—and restores any user settings that were saved in the last ocSaveUserInfo call, such as user name and password (See Section 3.1.3.1.7, "Managing User Settings With ocSaveUserInfo"). An ocEnv structure is passed as the input parameter. Perform the following to prepare the ocEnv variable:

  1. Create the ocEnv by allocating a variable the size of ocEnv.

  2. Memset the ocEnv variable before invoking the ocSessionInit function. If you do not perform a memset on the ocEnv variable, then the ocSessionInit function will not perform correctly.

  3. Set all required fields in the ocEnv structure before passing it to ocSessionInit. If you want to save the user preferences for future sessions, then invoke the ocSaveUserInfo method.

For a full description of ocEnv, see Section 3.1.3.1.4, "ocEnv Data Structure".

The following example allocates a new ocEnv, which is then passed into the ocSessionInit call.

env = new ocEnv;
// Reset ocenv
memset( env, 0, sizeof(ocEnv) );
 
// init OCAPI
ocError rc = ocSessionInit(env);
3.1.3.1.3 Managing the C/C++ Data Structures

Two data structures—ocEnv Data Structure and ocTransportEnv Data Structure—are used for certain functions in the Mobile Sync API.

3.1.3.1.4 ocEnv Data Structure

The ocEnv data structure holds internal memory buffers and state information. Before using this structure, the application initializes it by passing it to the ocSessionInit method.

Table 3-38 lists the field name, type, usage, and corresponding description of the ocEnv structure parameters.

  • Required—If the usage is required, then you either set before calling the ocSessionInit function or you have saved these parameters previously with the ocSaveUserInfo function.

  • Optional—If the usage is optional, then optionally set after calling the ocSessionInit function and before the ocDoSynchronize function.

  • Read Only.

Table 3-38 ocEnv Structure Field Parameters

Field Type Usage Description

username

char[32]

Required.

Name of the user to authenticate. This name is limited to 28 characters, because of other parts of the product.

password

char[32]

Required.

User password (clear text). This name is limited to 28 characters, because of other parts of the product.

trType

Enum

Required.

If set to OC_BUILDIN_HTTP, use HTTP built-in transport driver. This is the default.

If set to OC_USER_METHOD, use user provided transport functions.

If set to OC_FILE_TRANSPORT, the synchronization uses file-based sync. See Section 3.1.3.1.14, "Enable File-Based Synchronization through C or C++ APIs".

newPassword

char[32]

Optional.

If first character of this string is not NULL—in otherwords (char) 0—this string is sent to the server to change the user password; the password change is effective on the next synchronization session.

savePassword

Short

Optional.

If set to 1, the password is saved locally and is loaded the next time ocSessionInit is called.

appRoot

char[32]

Optional.

Directory to where the application will be copied. If first character is NULL, then it uses the default directory.

priority

Short

Optional.

0= OFF (default)

1= ON; Only high priority table or rows are synchronized when turned on.

You can only use fast refresh with a high priority restricting predicate. If you use any other type of refresh, the high priority restricting predicate is ignored.

See Section 1.2.10, "Priority-Based Replication" in the Oracle Database Mobile Server Troubleshooting and Tuning Guide for more information.

secure

Short

Optional.

If set to 0, then AES is used on the transport. If set to OC_SSL_ENCRYPTION, use SSL synchronization (SSL-enabled device only).

syncDirection

Enum

Optional.

If set to 0 (OC_SENDRECEIVE), then synchronization is bi-directional (default).If set to OC_SENDONLY, then push changes only to the server. This stops the synchronization after the local changes are collected and sent. User must write own transport method (like floppy bases) when using this method.If set to OC_RECEIVEONLY, then send no changes and only receive update from server. This only performs the receive and allow changes function to local database stages.

exError

ocError

Read-only.

Extended error code - either OS or OKAPI error code.

transportEnv

ocTransportEnv

 

Transport buffer. See Section 3.1.3.1.5, "ocTransportEnv Data Structure".

progressProc

fnProgress

Optional.

If not NULL, points to the callback for progress listening. See Section 3.1.3.1.11, "See Progress of Synchronization with Progress Listening".

totalSendDataLen

Long

 

Reserved

totalRecieveDataLen

Long

 

Reserved

userContext

Void*

Optional.

Can be set to anything by the caller for context information (such as progress dialog handle, renderer object pointer, and so on.

ocContext

Void*

 

Reserved.

logged

Short

 

Reserved.

bufferSize

Long

 

Reserved (for Wireless/Nettech only).

pushOnly

Short

Optional.

If set to 1, then only push changes to the server.

syncApps

Short

Optional.

Set to 1 (by default), performs application deployment.

If set to 0, then no applications will be received from the server.

syncNewPublications

Short

Optional.

If set to 1 (default), receives any new publication created from the server since last synchronization.

If set to 0, only synchronizes existing publications (useful for slow transports like wireless).

updateLog

Short

Optional.

Debug only. If set to 1, logs server-side insert and update row information to the publication client database.

options

Short

Optional.

Debug only. A bitset of the following flags:

  • OCAPI_OPT_SENDMETADATA

    Sends meta-info to the server.

  • or OCAPI_OPT_DEBUG

    Enables debugging messages.

  • OCAPI_OPT_DEBUG_F

    Saves all bytes sent and received for debugging.

  • OCAPI_OPT_NOCOMP

    Disables compression.

  • OCAPI_OPT_ABORT

    If set, OCAPI will try to abort the current synchronization session.

  • OCAPI_OPT_FULLREFRESH

    Forces OCAPI to purge all existing data and do a full refresh.

cancel

Short

 

Caller can set to 1 on next operation. ocDoSynchronize returns with -9032.


The environment structure contains fields that the caller can update to change the way Mobile Sync module works. The following example demonstrates how to set the fields within the ocEnv structure.

typedef struct ocEnv_s {
 // User info
char username[MAX_USERNAME];    // Mobile Sync Client id, limited to 28 characters
char password[MAX_USERNAME];    // Mobile Sync Client password for 
                                // authentication during sync, limited to 28 chars
char newPassword[MAX_USERNAME]; // resetting Mobile Sync Client password 
                                   // on server side if this field is not blank 
short savePassword;           // if set to 1, save password 
char appRoot[MAX_PATHNAME];     // dir path on client device for deploying files
short priority;              // High priority table only or not
short secure;            // if set to 1, data encrypted over the wire 
enum {
OC_SENDRECEIVE = 0,     // full step of synchronize
OC_SENDONLY,     // send phase only
OC_RECEIVEONLY,     // receive phase only
OC_SENDTOFILE,     // send into local file | pdb
OC_RECEIVEFROMFILE     // receive from local file | pdb
}syncDirection;     // synchronize direction

enum {
OC_BUILDIN_HTTP = 0,     // Use build-in HTTP transport method
OC_USER_METHOD     // Use user defined transport method
}trType;           // type of transport

ocError exError;     // extra error code

ocTransportEnv transportEnv;     // transport control information 

                       // GUI related function entry
progressProc fnProgress;     // callback to track progress; this is optional

                 // Values used for Progress Bar. If 0, progress bar won't show.
long totalSendDataLen; // set by Mobile Sync API informing transport total number 
                     // of bytes to send; set before the first fnSend() is called
long totalReceiveDataLen;     // to be set by transport informing Mobile Sync API 
                       // total number of bytes to receive; 
                       // should be set at first fnReceive() call. 
void* userContext;     // user defined context
void* ocContext;       // internal use only
short logged;          // internal use only
long bufferSize;       // send/receive buffer size, default is 0
short pushOnly;        // Push only flag
short syncApps;        // Application deployment flag
short cancel;          // cancel   
} ocEnv;
3.1.3.1.5 ocTransportEnv Data Structure

You can configure the HTTP URL, proxy, proxy port number and other HTTP-specific transport definitions in the ocTrHttp structure. This structure is an HTTP public structure defined in octrhttp.h.

You access the ocTrHttp structure from within the ocTransportEnv data structure, which is provided as part of the ocEnv data structure. The following demonstrates the fields within the ocTransportEnv structure:

typedef struct ocTransportEnv_s {
void* ocTrInfo;            // transport internal context

The ocTrInfo is a pointer that points to the HTTP parameters in the ocTrHttp structure. The following code example retrieves the ocTrInfo pointer to the HTTP parameters and then modifies the URL, proxy, and proxy port number to the input arguments:

ocTrHttp* http_params = (ocTrHttp*)(env->transportEnv.ocTrInfo);
// set server_name
strcpy(http_params->url, argv[3]); 
// set proxy
strcpy(http_params->proxy, argv[4]); 
// set proxy port
http_params->proxyPort = atoi(argv[5])
3.1.3.1.6 Retrieving Publication Information With ocGetPublication

This function gets the publication name on the client from the application name. The user knows only the application name, which happens when the Packaging Wizard is used to package an application before publishing it. If the application needs the publication name in order to interact with the database, then this function is used to retrieve that name, given the application name.

Syntax

ocError ocGetPublication(ocEnv* env, const char* application_name, 
 char* buf, int buf_len);

The parameters for the ocGetPublication function are listed in Table 3-39 below.

Table 3-39 ocGetPublication Parameters

Name Description

ocEnv* env

Pointer to an ocEnv structure buffer to hold the return synchronization environment.

const char* application_name(in)

The name of the application.

char* buf(out)

The buffer where the publication name is returned.

int buf_len(in)

The buffer length, which must be at least 32 bytes.


Return value of 0 indicates that the function has been executed successfully. Any other value is an error code.

The following code example demonstrates how to get the publication name.

void sync()
{
         ocEnv env;
         int rc;

         // Clean up ocenv
         memset(&env 0, sizeof(env) );
         
         // init OCAPI
         rc = ocSessionInit(&env);

         strcpy(env.username, "john");
         strcpy(env.password, "john");

         // We use transportEnv as HTTP paramters
         ocTrHttp* http_params = (ocTrHttp*)(env.transportEnv.ocTrInfo);
         strcpy(http_params->url, "your_host");

         // Do not synchronize applicaton "Sample3"
         char buf[32];
         rc = ocGetPublication(&env, "Sample3", buf, sizeof(buf));
         rc = ocSetTableSyncFlag(&env, buf, NULL, 0);

         // call sync
         rc = ocDoSynchronize(&env);
         if (rc < 0)
                fprintf(stderr, "ocDoSynchronize failed with %d:%d\n", 
                  rc, env.exError);
         else
                printf("Synchronization compeleted\n");
         
         // close OCAPI session
         rc = ocSessionTerm(&env);
         return 0;
}
3.1.3.1.7 Managing User Settings With ocSaveUserInfo

Saves user settings for the ocEnv structure. These settings can be used for the current session or used by the ocSessionInit function to initialize the environment when next invoked.

Syntax

int ocSaveUserInfo( ocEnv *env );

Table 3-40 lists the ocSaveUserInfo parameter and its description.

Table 3-40 ocSaveUserInfo Parameters

Name Description

env

Pointer to the synchronization environment.


This saves or overwrites the user settings into a file or database on the client side. The following information provided in the environment structure is saved:

  • username

  • password

  • savePassword

  • newPassword

  • priority

  • secure

  • pushOnly

  • syncApps

  • syncNewPublications

If you use the HTTP default transport set in the ocTransportEnv structure, then the following is also saved:

  • url

  • useProxy

  • proxy

  • proxyPort

For more information on how to use these fields, see Section 3.1.3.1.3, "Managing the C/C++ Data Structures".

3.1.3.1.8 Manage What Tables Are Synchronized With ocSetTableSyncFlag

Update the table flags for selective sync. Call this for each table to specify whether it should be synchronized (1) or not (0) for the next session. Selective sync only works if you have first performed at least one synchronization for the client. Then, set the flag so that on the next synchronization—that is, on the next invocation of the ocDoSynchronize method—a selective sync occurs.

The default sync_flag setting for ocSetTableSyncFlag is TRUE (1) for all the tables; that is, all tables are flagged to be synchronized. If you want to selectively synchronize specific tables, you must first disable the default setting for all tables and then enable the synchronization for only the specific tables that you want to synchronize.

Syntax

ocSetTableSyncFlag(ocEnv *env, const char* publication_name, 
              const char* table_name, short sync_flag)

Table 3-41 lists the name and description of parameters for the ocSetTableSyncFlag function.

Table 3-41 ocSetTableSyncFlag Parameters

Name Description

env

Pointer to the synchronization environment.

publication_name

The name of the publication which is being synchronized. If the value for the publication_name is NULL, it means all publications in the database. This string is the same as the client_name_template parameter of the Consolidator Manager CreatePublication method. In most cases, you will use NULL for this parameter. For more information, see Section 2.4, "Creating Publications Using Oracle Database Mobile Server APIs".

table_name

This is the name of the snapshot. It is the same as the name of the store, the third parameter of CreatePublicationItem(). For more information, see Section 2.4, "Creating Publications Using Oracle Database Mobile Server APIs".

sync_flag

If the sync_flag is set to 1, you must synchronize the publication. If the sync_flag is set to 0, then do not synchronize. The value for the sync_flag is not stored persistently. Each time before ocDoSynchronize(), you must call ocSetTableSyncFlag().


This function allows client applications to select the way specific tables are synchronized.

Set sync_flag for each table or each publication. If sync_flag = 0, the table is not synchronized.

To synchronize specific tables only, you must perform the following steps:

  1. Disable the default setting, which is set to 1 (TRUE) for all the tables.

    Example:

    ocSetTableSyncFlag(&env, <publication_name>,NULL,0)
    

    Where <publication_name> must be replaced by the actual name of your publication, and where the value NULL is specified to mean all the tables for that publication without exception.

  2. Enable the selective sync for specific tables.

    Example:

    ocSetTableSyncFlag(&env, <publication_name>,<table_name>,1)
    
3.1.3.1.9 Configure Proxy Information

If you are using a firewall and need to configure proxy information, perform the following before you execute the ocDoSynchronize method:

  1. Configure the proxy URL, IP address and/or port number through the ocSaveUserInfo function. See Section 3.1.3.1.7, "Managing User Settings With ocSaveUserInfo" for more information.

  2. If required, configure the proxy user name and password. To configure the proxy user name and password, use the ocSetSyncOption and provide the following:

    ocSetSyncOption( env, "HTTPUSER=<username>;HTTPPASS=<password>");
    

    Note:

    The user name and password are limited to 28 characters.

    Where the ocSetSyncOption syntax is as follows:

    int ocSetSyncOption(ocEnv *env, const char *str);
    

You can set one or more name/value pairs searated by a semi-colon in the string. The previous example shows the HTTPUSER and HTTPPASS name/value pairs. You can also set the URL string as follows: URL=www.myhost.com.

3.1.3.1.10 Start the Synchronization With the ocDoSynchronize Method

Starts the synchronization process.

Syntax

int ocDoSynchronize( ocEnv *env );

Table 3-42 lists the name and description of the ocDoSynchronize parameter.

Table 3-42 ocDoSynchronize Parameters

Name Description

env

Pointer to the synchronization environment.


This starts the synchronization cycle. A round trip synchronization is activated if syncDirection is OC_SENDRECEIVE (default). If syncDirection is OC_SENDONLY or OC_RECEIVEONLY, then the developer must implement a custom transport. If the developer wishes to upload only changes, then set pushonly=1. You cannot only download changes under the existing synchronization architecture.

This method returns when the synchronize completes. A return value of 0 indicates that the function has been executed successfully. If an error occurred, local errors are returned by ocDoSynchronize, which are defined in ocerror.h. For errors returned by the server, see the ol_sync.log error log file, which is written into the working directory of the application. Each line in the error file has the following format:

<type>, <code>, <date>, <message>

Where:

  • <type>: The type of the message, which can either be set to ERROR or SUCCESS.

  • <code>: Error code of the last operation of the synchronization.

  • <date>: Date and timestamp for when the synchronization completes. This is in the format of dd/mm/yyyy hh:mm:ss.

  • <message>: A readable message text.

3.1.3.1.11 See Progress of Synchronization with Progress Listening

If you create and set the progress callback function, the mobile client invokes this callback function at different times while the ocDoSynchronize method is executing. Create the callback function, as follows:

void myProgressProc ( void *env, int stage, int present);

When the ocDoSynchronize invokes your myProgressProc function, it provides the following information as input to your function:

  • env—A pointer to the environment (ocEnv structure) for the synchronization session. This provides the function to retrieve the userContext pointer.

  • stage—A number that denotes the stage in the synchronization process, which is one of the following values, where these values are defined in ocapi.h:

    Table 3-43 Description of the Stage Values

    Stage Value Description

    OC_PREPARE_START

    Start of the prepare stage, which collects all internal data from the database and prepares to send the data to the server.

    OC_PREPARING

    Progress in the prepare stage.

    OC_PREPARE_FINISH

    Prepare stage is completed.

    OC_SEND_START

    Starting to send the data to the server.

    OC_SENDING

    Sending the data.

    OC_SEND_FINISH

    Completed sending the data.

    OC_RECEIVE_START

    Starting to receive data.

    OC_RECEIVING

    Receiving data from the server.

    OC_RECEIVE_FINISH

    Completed receiving data from the server.

    OC_PROCESS_START

    Starting to process received data.

    OC_PROCESSING

    Processing received data.

    OC_PROCESS_FINISH

    Completed processing. Synchronization is finished.

    OC_RETRY_CALL

    Resume synchronization is restarted.

    OC_SYNC_FINISH

    Last callback after the synchronization.


  • present—The percentage completed in the particular stage that synchronization is in from 0 to 100.

If the function is a member of a class, then it must be defined as static.

After you create the callback function, set the function pointer in the ocEnv.fnProgress (Table 3-38) to the address of your callback function. Save this with the ocSaveUserInfo or ocSessionInit methods.

3.1.3.1.12 Clear the Synchronization Environment Using ocSessionTerm

Clears and performs a cleanup of the synchronization environment and buffers. This function must be invoked for every ocSessionInit, even if the ocDoSynchronize function is not performed.

Syntax

int ocSessionTerm( ocEnv *env );

Table 3-44 lists the ocSessionTerm parameter and its description.

Table 3-44 ocSessionTerm Parameters

Name Description

env

Pointer to the environment structure returned by ocSessionInit.


De-initializes all the structures and memory created by the ocSessionInit() call. Users must ensure that they are always called in pairs.

3.1.3.1.13 Retrieve Synchronization Error Message with ocGetLastError

Retrieves the synchronization error message and code.

Syntax

int ocGetLastError( ocEnv *env, char *buf, int buf_size);

Table 3-45 lists the ocGetLastError parameters.

Table 3-45 ocGet Parameters

Name Description

env

Pointer to the environment structure returned by ocSessionInit.

buf

A string with the error message.

buf_size

The size of the error message string.


3.1.3.1.14 Enable File-Based Synchronization through C or C++ APIs

When you want to use file-based synchronization, you must enable file-based synchronization. Once enabled, then when you initiate manual synchronization, then the synchronization file is created. See Section 5.10, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Mobile Server Administration and Deployment Guide for more details on file-based synchronization.

To enable file-based synchronization programmatically with the ocEnv structure, perform the following:

  1. Ensure that any previous settings of the File-Based Sync properties are set to NULL.

  2. Initialize the environment with the ocSessionInit method.

  3. Set the user name and password for the user that is initializing the synchronization.

  4. Specify the synchronization direction and directory and filename for the synchronization file. The synchronization direction is either send, which creates the synchronization file, or receive, which takes in a file from the mobile server. These are configured in the SEND_FILE_PROP and RECEIVE_FILE_PROP properties with the ocSetSyncProperty method.

    • When you set the SEND_FILE_PROP property, specify the filename—including the relative or full path—where you want the mobile client to save the upload data for the mobile server. This file is created with the mobile client transactions destined for the mobile server.

    • When you set the RECEIVE_FILE_PROP property, specify the filename—including the relative or full path—where the data file that was received from the mobile server. This file is loaded and processed within the mobile client.

The following code example sets the direction, filename, user name and password. Notice that the ocEnv structure is memset to zero to ensure that if a previous direction and filename were specified, then these are invalidated for the next file-based synchronization. The SEND_FILE_PROP property is set with the filename and direction, which tells the Sync Client to marshall the mobile client transactions that are to be uploaded to the mobile server into this file. If you were receiving a synchronization file from the mobile server, you would have set the RECEIVE_FILE_PROP property with the location and name of this file.

Finally, the ocEnv structure is provided to the ocDoSynchronize method, which performs the file-based synchronization.

ocEnv env;
memset(&env, 0, sizeof(ocEnv));
ocSessionInit(&env);
strcpy(env.username, "S11U1");
strcpy(env.password, "manager");
ocSetSyncProperty(&env, SEND_FILE_PROP, "C:\\temp\\send1.bin");
ocDoSynchronize(&env);
ocSessionTerm(&env);

3.1.3.2 OCAPI Synchronization API for C#

The OCAPI C# interface for Mobile Sync client-side synchronization resides in the Oracle.DataAccess.Lite package.

The C# interface provides for the following functions:

  • Setting client-side user profiles containing data such as user name, password, and server

  • Starting the synchronization process

  • Tracking the progress of the synchronization process

The C# interface is contained in the Oracle.DataAccess.Lite.dll. The OracleSync class, defined in the OracleSync.cs file, contains the C# API for synchronization.

The following sections describe how to use the C# API:

3.1.3.2.1 Use the OracleSync Class for Synchronization

You use the OracleSync class to initialize and perform synchronization using the C# APIs.

Table 3-46 shows the properties you can set for initializing the environment before invoking synchronization:

Table 3-46 OracleSync Properties

Properties Type Description

UserName

String

The name of the user who is initiating the synchronization.

Password

String

The password for the user who is initiating the synchronization.

ServerURL

String

Mobile Server URL, which is http://<mobile_server_hostname>:<port_number>, replace 'http' with 'https' in case SSL is used. If SSL is not used, 'http://' can be skipped.

ProxyHost

String

The hostname or IP address of the proxy server.

ProxyPort

Integer

The hostname or IP address of the proxy port.

PushOnly

Boolean

Upload changes from the client to the server only, do not download. This is useful when data transfer is one way, client to server. A boolean value which makes synchronization push only. TRUE sets PushOnly to on; FALSE is the default value.

HighPriority

Boolean

FALSE turns high priority to OFF, which is the default.

TRUE turns high priority to ON; Only high priority table or rows are synchronized when set to TRUE.

You can only use fast refresh with a high priority restricting predicate. If you use any other type of refresh, the high priority restricting predicate is ignored.

See Section 1.2.10, "Priority-Based Replication" in the Oracle Database Mobile Server Troubleshooting and Tuning Guide for more information.

Option

Option

Set one or more of the appropriate synchronization options with an OR statement from the SyncOption enumeration. Provide a bitset of the following flags:

  • FORCE_REFRESH

    Forces a purge of all existing data and do a full refresh.

Secure

Boolean

Should not be used. To use an SSL connection, prefix the ServerURL property with https://.


The synchronization public methods of the OracleSync class are described in Table 3-47.

Table 3-47 OracleSync Public Methods

Method Description

void save()

This saves the user name, password, URL, proxy, and proxy-port settings for the OracleSync class. The next time that the OracleSync class is created, it is pre-loaded automatically with these saved settings. The password is not saved.

void Synchronize ()

Starts a synchronization session and blocks that thread until synchronization is complete.

void Close ()

Closes and performs clean-up for the synchronization session.

void SetCancel()

Set cancel during any synchronization. The synchronization returns.

String GetLogFileName()

Used to retrieve the error log filename. For details, see Section 3.1.3.2.5, "Exception Handling and Reading Log Files".

void SetTableSyncFlag (string pubName, string tableName, bool flag)

Used for setting selective sync. For details, see Section 3.1.3.2.10, "Manage What Tables Are Synchronized With Selective Sync".

int SetSyncProperty (string prop, string val)

Used to set Synchronization properties. The types of Synchronization properties that you can set are as follows:

  • HTTP_USER_PROP —HTTP authentication user name.

  • HTTP_PASS_PROP — HTTP authentication password.

int GetSyncProperty (string prop, out string val)

Used to retrieve Synchronization property settings. See the SetSyncProperty description for details.


To create the OracleSync class in preparation for the synchronization, perform the following:

  1. Instantiate the OracleSync object.

  2. Set relevant properties, such as user name, password and URL. The user name and password are limited to 28 characters each.

  3. If you want to preserve all OracleSync properties, except for the password, then execute the Save method. The format of the Save method is as follows:

    void Save()
    
  4. Perform the synchronization with the Synchronize method. The format of the Synchronize method is as follows:

    void Synchronize()
    

    Note:

    A DataException is thrown if synchronization fails. Also, you must close all database connections before doing a synchronization.
  5. Close the OracleSync object when finished. The Close method is as follows:

    void Close()
    

The following code demonstrates these methods by setting the properties off of user entries on a GUI screen:

// Instantiate the object
OracleSync m_sync = new OracleSync();

// Set the appropriate sync options
m_sync.UserName  = userName.Text;
m_sync.Password  = password.Text;
m_sync.ServerURL = url.Text;
 
if (enableProxy.Checked == true)
{
  m_sync.ProxyHost = proxyHost.Text;
  m_sync.ProxyPort = 80;
 
  try {m_sync.ProxyPort = System.Convert.ToInt32 (proxyPort.Text);}
  catch (System.ArgumentNullException) {}
}
if (forceRefresh.Checked == true)
{
 m_sync.Option = SyncOption.FORCE_REFRESH;
}
// save the options before synchronization
m_sync.Save();
//Synchronize
m_sync.Synchronize();
//Close the OracleSync object
m_sync.Close();
m_sync = NULL;
3.1.3.2.2 Using the OracleEngine to Synchronize

You can synchronize with the same engine that performs the synchronization for the msync tool. You can actually launch the GUI to have the user enter information and click Synchronize or you can enter the information programmatically and synchronize without launching the GUI.

3.1.3.2.3 Launch the MSYNC Tool for User Input

You can launch the msync tool, so that the user can modify settings and initialize the synchronization, by executing the following:

OracleEngine.Synchronize(false)

Providing the false as the input parameter tells the engine that you are not providing the input parameters, but to bring up the msync GUI for the user to input the information.

3.1.3.2.4 Set the Environment and Synchronize With the OracleEngine

You can set the information and call for a synchronization through the OracleEngine class without bringing up the GUI.

If you accept the default synchronization settings, provide true as the input parameter to automatically synchronize, as follows:

OracleEngine.Synchronize(true)

You can execute the synchronize method with three input parameters that define a specific server: the server name, user name and password.

OracleEngine.Synchronize("S11U1", "manager", "myserver.mydomain.com")

Alternatively, you can configure a string that contains the options listed in Table 3-48 with a single String input parameter and synchronize, as follows:

OracleEngine.Synchronize(args)

In the above example, the String args input parameter is a combination of the options in Table 3-48.

String args = "S11U1/manager@myserver.mydomain.com /save /ssl /force"

Include as many of the options that you wish to enable in the String.

Table 3-48 Command Line Options

Option Description

username/password@server[:port][@proxy:port]

Automatically synchronize to the specified server.

/a

Automatically synchronize to saved preferred server.

/save

Save user info and exit.

/proxy:(proxy_server)[:port]

Connect by specific proxy server and port.

/ssl

Synchronize with SSL encryption.

/force

Force refresh.

/noapp:(application_name)

Do not synchronize specific application data. Synchronize with other applications.

/nopub:(publication_name)

Do not synchronize specific publication data. Synchronize with other publications.

/notable:(table_name)/notable:(db_name).(table_name)

Do not synchronize specific table data. Synchronize with other tables.

/onlyapp:(application_name)

Synchronize only specific application data. Do not synchronize with other applications.

/onlypub:(publication_name)

Synchronize only specific publication data. Do not synchronize with other publications.

/onlytable:(table_name)/onlytable:(odbc_name). (table_name)

Synchronize only specific table data. Do not synchronize with other tables.

/hp

Enable high priority data synchronization.


3.1.3.2.5 Exception Handling and Reading Log Files

For any synchronization error or database error that occurs during synchronization, then the Oracle.DataAccess.Lite.OracleException is thrown. The OracleException object contains the error code and error messages.

If an error occurs during synchronization, you can view errors returned by the server in the error log file. To retreve the error log filename, execute the GetLogFileName method. Then, open and evaluate the log file, which is written into the working directory for the application. The syntax for the GetLogFileName method is as follows:

static String GetLogFileName();

Each line in the error file has the following format:

<type>, <code>, <date>, <message>

Where:

  • <type>: The type of the message, which can either be set to ERROR or SUCCESS.

  • <code>: Error code of the last operation of the synchronization.

  • <date>: Date and timestamp for when the synchronization completes. This is in the format of dd/mm/yyyy hh:mm:ss.

  • <message>: A readable message text.

The following code example shows how to retrieve the filename:

String file = OracleSync.GetLogFileName();
3.1.3.2.6 Monitor Synchronization Progress With the SyncEventHandler

To monitor the progress of the synchronization process, the SetEventHandler and SyncEventHandler methods and the SyncEventArgs object of the OracleSync class enable the user to create an event handler to return a progress report on the state of the synchronization.

The SyncEventArgs object is generated in the OracleSync object during the Synchronize method.

The following sections describe and show how to use the object and the methods to monitor the synchronization stage and progress:

3.1.3.2.7 Using the SyncEventArgs Object

The SyncEventArgs is an object that contains the state or the synchronization.

The following is the definition for the object:

public class SyncEventArgs : EventArgs
{
 public readonly int stage;
 public readonly int percentage;
 // Synchronization progress stages
 //
 public const int SYNC_PREPARE_START  = 0;
 public const int SYNC_PREPARING      = 1;
 public const int SYNC_PREPARE_FINISH = 2;
 public const int SYNC_SEND_START     = 3;
 public const int SYNC_SENDING        = 4;
 public const int SYNC_SEND_FINISH    = 5;
 public const int SYNC_RECEIVE_START  = 6;
 public const int SYNC_RECEIVING      = 7;
 public const int SYNC_RECEIVE_FINISH = 8;
 public const int SYNC_PROCESS_START  = 9;
 public const int SYNC_PROCESSING     = 10;
 public const int SYNC_PROCESS_FINISH = 11;
}

Note:

Some codes are returned from the OCI layer. If you receive a status code not listed here, see Table 3-43.

There are two parameters, as follows:

Table 3-49 SyncEventArgs Parameters

Parameter Description

stage

The stage in which the synchronization is acting on the mobile client. The possible stages are as follows:

  • SYNC_PREPARE_START

  • SYNC_PREPARING

  • SYNC_PREPARE_FINISH

  • SYNC_SEND_START

  • SYNC_SENDING

  • SYNC_SEND_FINISH

  • SYNC_RECEIVE_START

  • SYNC_RECEIVING

  • SYNC_RECEIVE_FINISH

  • SYNC_PROCESS_START

  • SYNC_PROCESSING

  • SYNC_PROCESS_FINISH

percentage

The percentage of completion for this stage.


The following code demonstrates how you can determine the state and percentage of the synchronization from the SyncEventArgs. For each state group indicated in the args.stage parameter, it modifies a display to show the state and the percentage of completion by invoking the moveProgressBarDelegate method, as follows:

private void DisplayProgress (object sender, SyncEventArgs args)
{
 switch (args.stage)
 {
  case SyncEventArgs.SYNC_PREPARE_START:
  case SyncEventArgs.SYNC_PREPARING:
  case SyncEventArgs.SYNC_PREPARE_FINISH:
  this.Invoke(new moveProgressBarDelegate(moveProgressBar), 
        prepareBar, args.percentage );
  break;
  case SyncEventArgs.SYNC_SEND_START:
  case SyncEventArgs.SYNC_SENDING:
  case SyncEventArgs.SYNC_SEND_FINISH:
  this.Invoke(new moveProgressBarDelegate(moveProgressBar), 
        sendBar, args.percentage);
  break;
  case SyncEventArgs.SYNC_RECEIVE_START:
  case SyncEventArgs.SYNC_RECEIVING:
  case SyncEventArgs.SYNC_RECEIVE_FINISH:
  this.Invoke(new moveProgressBarDelegate(moveProgressBar), 
        receiveBar, args.percentage);
  break;
  case SyncEventArgs.SYNC_PROCESS_START:
  case SyncEventArgs.SYNC_PROCESSING:
  case SyncEventArgs.SYNC_PROCESS_FINISH:
  this.Invoke(new moveProgressBarDelegate(moveProgressBar), 
        processBar, args.percentage);
  break;
 }
}
3.1.3.2.8 Executing the SetEventHandler Method

Before you can determine the state, you must create the event handler that monitors the synchronization progress. This is performed by executing the SetEventHandler method and providing a new SyncEventHandler object for it to track.

The following is the definition for the method:

public void SetEventHandler (SyncEventHandler handler, bool add);

The parameters for the SetEventHandler method are described in Table 3-50.

Table 3-50 SetEventHandler Method Parameters

Parameter Description

object sender

The SyncEventHandler object that is created for this event handler.

boolean add

This boolean, if true, registers the SyncEventHandler object. If false, it de-registers the event handler.


The following code demonstrates how to create a new SyncEventHandler and delegates the SyncEventHandler method to the DisplayProgress method, which is the application implemented callback method that processes the state and percentage.

The SetEventHandler takes in the SyncEventHandler delegate, which is assigned as DisplayProgress, and whether to monitor the progress with a TRUE or to not monitor the progress with FALSE. Then the Synchronize method is called to initiate the synchronization.

//Create the SyncEventHandler and put it in the event handler
m_sync.SetEventHandler (new 
        OracleSync.SyncEventHandler (DisplayProgress), true);
//Perform the synchronize
 m_sync.Synchronize();
//Once the synchronization is complete, remove this SyncEventHandler
 m_sync.SetEventHandler (new 
        OracleSync.SyncEventHandler (DisplayProgress), false);
3.1.3.2.9 Creating the SyncEventHandler Object

The SyncEventHandler object is the event handler. It is also a delegate method. The following is the definition for the method:

delegate void SyncEventHandler (object sender, SyncEventArgs args);

In the application implementation, create the delegate method with the same arguments and how you want the delegated method to handle the event. In our example, the DisplayProgress method is defined as follows:

void DisplayProgress (object sender, SyncEventArgs args)

It has the same arguments as the delegate definition, and is defined as the delegate when the SyncEventHandler is created, as shown in the code below:

m_sync.SetEventHandler (new 
        OracleSync.SyncEventHandler (DisplayProgress), true);

The SyncEventHandler object, and thus the DisplayProgress method, takes in two parameters, as shown in Table 3-51.

Table 3-51 SetEventHandler Method Parameters

Parameter Description

object sender

The SyncEventHandler object that is created for this event handler.

SyncEventArgs args

The SyncEventArgs object that monitors the state and progress of the synchronization.


On each synchronization event—such as send complete, receive complete, synchronization complete—the OracleSync object raises the SyncEventHandler event and invokes the DisplayProgress method with the SyncEventArgs object.

3.1.3.2.10 Manage What Tables Are Synchronized With Selective Sync

Update the table flags for selective sync. Call this for each table to specify whether it should be synchronized(1) or not (0) for the next session. Selective sync only works if you have first performed at least one synchronization for the client. Then, set the flag so that on the next synchronize—that is, before the next invocation of the Synchronize method—a selective sync occurs.

The default setting is TRUE (1) for all the tables; that is, all tables are flagged to be synchronized. If you want to selectively synchronize specific tables, you must first disable the default setting for all tables and then enable the synchronization for only the specific tables that you want to synchronize.

Syntax

void SetTableSyncFlag (string pubName, string tableName, bool sync_flag)

Table 3-52 lists the name and description of parameters for the setTableSyncFlag function.

Table 3-52 setSyncFlag Parameters

Name Description

pubName

The name of the publication which is being synchronized. If the value for the pubName is NULL, it means all publications in the database. This string is the same as the client name supplied to the Consolidator Manager when creating the publication. In most cases, you will use NULL for this parameter. For more information, see Section 2.4, "Creating Publications Using Oracle Database Mobile Server APIs".

tableName

This is the name of the snapshot. It is the same as the name of the store, the third parameter of createPublicationItem(). For more information, see Section 2.4, "Creating Publications Using Oracle Database Mobile Server APIs".

sync_flag

If the sync_flag is set to TRUE, you must synchronize the publication. If the sync_flag is set to FALSE, then do not synchronize. The value for the sync_flag is not stored persistently. Each time before Synchronize(), you must call SetTableSyncFlag().


This function allows client applications to select the way specific tables are synchronized.

Set sync_flag for each table or each publication. If sync_flag = FALSE, the table is not synchronized. To synchronize specific tables only, you must perform the following steps:

  1. Disable the default setting by setting it to FALSE (0). By default, the setting is set to TRUE (1) for all the tables. Setting them all to FALSE then enables you to select which tables are to be synchronized, which is performed in step 2.

    Example:

    SetTableSyncFlag(<publication_name>,NULL,0)
    

    Where <pubName> must be replaced by the actual name of your publication, and where the value NULL is specified to mean all the tables for that publication without exception.

  2. Enable the selective sync for specific tables.

    Example:

    SetTableSyncFlag(<publication_name>,<table_name>,1)
    

Alternatively, see the following code snippet on how to enable the selective sync flag for every table except the Orders.TEST table.

m_sync.SetTableSyncFlag("","",(short)1); //turn on sync flag for all the tables
m_sync.SetTableSyncFlag("","Orders.TEST",(short)0); 
                     //turn off sync flag for Orders.TEST
3.1.3.2.11 Enable File-Based Synchronization through C# APIs

When you want to use file-based synchronization, you must enable file-based synchronization. Once enabled, then when synchronization occurs—either through automatic or manual synchronization—then the synchronization file is created. See Section 5.10, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Mobile Server Administration and Deployment Guide for more details on file-based synchronization.

To enable file-based synchronization programmatically with the OracleSync class, specify the following:

  1. Instantiate the OracleSync class and set the user name and password.

  2. Specify the synchronization direction and directory and filename for the synchronization file with the SetSyncProperty method of the OracleSync class. The synchronization direction is either send, which creates the synchronization file, or receive, which takes in a file from the mobile server. These are configured in the SEND_FILE_PROP and RECEIVE_FILE_PROP properties with the SetSyncProperty method.

    • When you set the RECEIVE_FILE_PROP property with the filename and directory, the intended file is uploaded and processed within the mobile client.

    • When you set the SEND_FILE_PROP property with the filename and directory, the intended file is created with the mobile client transactions destined for the mobile server.

Note:

You can retrieve the filename with the GetSyncProperty method.

The SetSyncProperty and GetSyncProperty methods are as follows:

int SetSyncProperty (string prop, string val)
int GetSyncProperty (string prop, out string val)
  • For SetSyncProperty, provide the property and the filename for setting the direction of the file-based synchronization and the destination/origination filename.

  • For GetSyncProperty, provide the direction property and receive the filename in the OUT value.

The following code example sets the direction, filename, user name and password in the SetSyncProperty method. In this example, the SEND_FILE_PROP property is set with the filename and direction, which tells the Sync Client to marshall the mobile client transactions that are to be uploaded to the mobile server into this file. If you were receiving a synchronization file from the mobile server, you would have set the RECEIVE_FILE_PROP property with the location and name of this file.

Finally, perform the synchronization with the Synchronize method.

OracleSync m_sync = new OracleSync();
m_sync.UserName = "S11U1";
m_sync.Password = "manager";
m_sync.SetSyncProperty(OracleSync.SEND_FILE_PROP,"C:\\temp\\send1.bin");
m_sync.Synchronize();

3.1.3.3 mSync, OCAPI, and mSyncCom API

For more information, refer to the Oracle Database Mobile Server API Specification.

3.2 Manage Automatic Synchronization on the Mobile Client

The following APIs are used to manage automatic synchronization on the Mobile cllient:

3.2.1 OSE APIs for Managing Automatic Synchronization

Note:

Use the OSE classes for all new application development for your mobile clients. These are the classes that will be supported for the future.

Automatic synchronization is enabled by default if a publication is enabled for automated synchronization. However, you may programmatically turn on and off automatic synchronization on the mobile client using the Sync Control API.

Use the start or stop methods to start or stop the Sync Agent. The user may want to stop the Sync Agent for many reasons, such as aborting an automatic synchronization that may be running longer than desired, freeing up system resources, or de-fragmenting or backing up a client database.

Note:

There is also a GUI for starting, stopping the automatic synchronization process from the mobile server. See Section 5.5.2, "Start, Stop, or Get Status for Automatic Synchronization" in the Oracle Database Mobile Server Administration and Deployment Guide for more details.

The following are the different methods of managing automatic synchronization and the Sync Agent:

  • Pause/Resume—Pause and resume all Sync Agent activities without stopping the process or freeing any resources, which would occur if you stopped or disabled the Sync Agent. Pause and resume are the most efficient method for suspending the Sync Agent and all automatic synchronization events, since it does not stop the process or free any resources.

    By default, if you are using the mSync GUI or sync API to initiate a manual synchronization, the underlying code pauses and resumes the automatic synchronization for you, as described below:

    1. Pause the automatic synchronization with the Sync Control API.

    2. Initiate the manual synchronization with the programmatic API.

    3. Resume the automatic synchronization with the Sync Control API.

    In some circumstances pausing syncagent might not be immediate if syncagent is currently running automatic synchronization task and cancellation cannot occur in the moment for various reasons. If syncagent cannot pause and you want the manual synchronization to start immediately, you can kill syncagent (for native clients). This can be done either by calling API in program or forcibly ending it with autosync.exe manually on Windows or with autosync manually on Linux.

    To kill syncagent by calling API, you can call bgControlAgent (bgSess, BG_CTRL_STOP, BG_CTRL_OPT_TERMINATE) in C, BGSession.kill() in java.

    To kill syncagent with autosync.exe on Windows or autosync on Linux, you can try to stop syncagent and it takes time, then the "Stop" button will change to "End" and you can kill it by pressing this button. Or the process syncagent.exe on Windows or syncagent on Linux can be manually terminated. After the manual synchronization is finished successfully, syncagent is started regardless whether it was running before or not. If the manual synchronization fails, syncagent is resumed - that is, it is only started if it was running before manual synchronization.

  • Start/Stop—Stop the Sync Agent, which includes stopping the process and freeing all resources, until a start operation is executed or the client is restarted. If the start operation is not executed, the Sync Agent is automatically resumed when the client restarts.

  • Enable/Disable—Disabling the Sync Agent stops the Sync Agent until an enable operation is executed. Even restarting the client will not re-enable the Sync Agent. Thus, in a disabled state, no automatic synchronization events will occur.

The following control APIs can be used to manage automatic synchronization:

3.2.1.1 JAVA APIs for the Sync Agent and Automatic Synchronization

The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:

Note:

For more details on these classes, refer to the Oracle Database Mobile Server JavaDoc.
3.2.1.1.1 Overview

Once automatic synchronization for the mobile client is enabled, you can manage it either locally through the Sync Agent APIs or remotely through the Mobile Manager UI controls. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is started, Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.

The Java interface for controlling the Sync Agent and automatic synchronization resides in the oracle.opensync.syncagent package.

The Java interface provides for the following functions:

  • Tracking the progress of the automatic synchronization process.

  • Retrieve the status of the Sync Agent.

  • Specify custom handlers for events that occur in automatic synchronization.

The following are the classes and interface for the Java API for controlling the Sync Agent and automatic synchronization:

  • BGSession Class

  • BGAgentStatus Class

  • BGSyncStatus Class

  • BGMessageHandler Interface

3.2.1.1.2 BGSession Class

BGSession is the main class for controlling automatic synchronization through the Sync Agent, as follows:

  • Start, stop, pause, resume, enable or disable automatic synchronization.

  • Retrieve automatic synchronization status information.

  • Specify message handlers for retrieving information about automatic synchronization events.

Note:

In a multi-threaded environment a single BGSession should not be used from multiple threads. Each thread should open its own session.

Constructor

BGSession( )

Public Methods

The public methods and their parameters for the BGSession class are listed in Table 3-53:

Table 3-53 BGSession Class Public Method Parameters

Method Description

void addMessageHandler (BGMessageHandler h)

void removeMessageHandler (BGMessageHandler h)

Adds or removes a custom message handler to the Sync Agent. See Section 3.2.1.1.5, "BGMessageHandler Interface" for more information.

boolean agentEnabled()

Returns TRUE if the Sync Agent is enabled; otherwise, FALSE.

void close()

Closes the session and release all the resources used by the session.

void enableAgent(boolean on)

TRUE enables the Sync Agent; FALSE disables the Sync Agent.

BGAgentStatus getAgentStatus()

Retrieves the current Sync Agent status. See Section 3.2.1.1.3, "BGAgentStatus Object" for more details on the status information returned.

int getAgentStatusCode()

Retrieves the current Sync Agent status code, which are described in Table 3-56, "Sync Agent Status Codes".

BGSyncStatus getSyncStatus()

Get current status of automatic synchronization managed by the Sync Agent. See Table 3-55 for more details on the status information returned.

void pause()

Pauses the Sync Agent.

If the agent is aready paused or being paused, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be paused before returning. Use the waitForStatus method to wait for the Sync Agent.

void resume()

Resumes the Sync Agent.

If the agent is already resumed or resuming, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be resumed before returning. Use the waitForStatus method to wait for the Sync Agent.

void showUI()

Starts up the Sync Agent UI.

void start()

Start the Sync Agent.

If the agent is already running, starting, or resuming, this call is ignored. If the agent is paused, this call resumes the Sync Agent. This call is asynchronous and does not wait for the Sync Agent to be started before returning. Use the waitForStatus method to wait for the Sync Agent.

void stop()

Stop the Sync Agent.

If the agent is already stopped or stopping, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be stopped before returning. Use the waitForStatus method to wait for the Sync Agent.

void waitForStatus (int statusCode)

boolean waitForStatus (int statusCode, long timeOut)

Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.

  • The parameter can be one of the following: RUNNING, PAUSED or STOPPED.

  • The timeOut parameter is the maximum time to wait for in milliseconds. Unlimited time if no timeout provided.

Returns TRUE if the agent has reached specified status; FALSE if the timeout has occurred.

BGException getFatalError()

If sync agent is in DEFUNCT state, retrieve the error information that caused the bad internal state. See Table 3-56, "Sync Agent Status Codes" for description of DEFUNCT.


Example

The following example demonstrates how to start the Sync Agent, retrieve status of the Sync Agent and add a message handler for the session:

// Create the BGSession object
 BGSession sess = new BGSession();
      try {
          //Start the Sync Agent, which enables all automatic synchronization
          //events
          sess.start();
          //Wait until the Sync Agent successfully starts
          sess.waitForStatus(BGAgentStatus.RUNNING);
          //Retrieve the status of the Sync Agent
          BGAgentStatus s = sess.getAgentStatus();
          //Print out the user that is using automatic synchronization
          System.out.println("User name: " + s.clientId);
          //Add a message handler
          sess.addMessageHandler(new myMessageHandler());
          ...
      }
      finally {
          //When finished, close the session to release all resources
          sess.close();
      }
3.2.1.1.3 BGAgentStatus Object

The BGAgentStatus object represents the current status of the Sync Agent.

Public Methods

The methods for the BGAgentStatus are listed in Table 3-54.

Table 3-54 BGAgentStatus Class Public Method

Method Description

static java.lang.String statusName(int statusCode)

Get language-specific name of a given status code. When you provide one of the status codes shown in Table 3-56, the appropriate name is returned. Translation dependent on the device language settings


Fields

BGAgentStatus provides status information on the Sync Agent. Table 3-55 lists and describes the status information fields within the BGAgentStatus class.

Table 3-55 BGAgentStatus Class Fields

Parameters Description

java.lang.String appName

The name of the application or process that is executing the Sync Agent. On some platforms, such as Android, it is possible to execute the Sync Agent within an application process.

int batteryPower

Remaining percentage of battery life, if relevant.

java.lang.String clientId

Sync user name.

java.lang.String networkName

Name of the network currently used for synchronization, evaluated by Sync Agent.

int networkSpeed

Network bandwidth in bits per second.

int processId

Process id of the process that is executing the Sync Agent, if relevant for a given platform.

int statusCode

Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 3-56, "Sync Agent Status Codes".


The BGAgentStatus object defines the Sync Agent status codes, which are as follows:

Table 3-56 Sync Agent Status Codes

Status Code Status Name Description

0

STOPPED

Sync Agent application is not running.

1

START_PENDING

Sync Agent is in the process of starting.

2

RUNNING

Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active.

3

PAUSE_PENDING

Sync Agent is in the process of being paused.

4

PAUSED

Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed.

5

RESUME_PENDING

Sync Agent is in the process of resuming.

6

STOP_PENDING

Sync Agent is in the process of stopping.

7

DEFUNCT

Sync Agent encountered fatal error and is in a bad internal state. Sync Agent's environment needs to be cleaned up and restarted.


Example

The following provides an example of retrieving and processing the Sync Agent status:

/* retrieve the Sync Agent status */
BGAgentStatus as = bgSess.getAgentStatus();
/* Print Sync Agent status */
 System.out.println("Agent Status:          " +
    BGAgentStatus.statusName(as.statusCode));
if (as.statusCode == BGAgentStatus.STOPPED) return;
/* Identify the client id, process id and name */
System.out.println("Client ID:             " + as.clientId);
System.out.println("Process Name:          " + as.appName);
System.out.println("Process ID:            " + as.processId);
/* network name and speed */
if (as.networkSpeed > 0) {
   System.out.println("Network Name:          " + as.networkName);
   System.out.println("Network Speed:         " + as.networkSpeed + " bps");
}
else System.out.println("Network is not present");
/* battery power */
if (as.batteryPower > 0) 
   System.out.println("Battery Power:         " + as.batteryPower + "%");
else
   System.out.println("Battery is not present");
3.2.1.1.4 BGSyncStatus Object

Current status of automatic synchronization. If automatic synchronization is in progress, startTime will have a non-zero value and endTime will be zero.

Fields

BGSyncStatus provides status information on automatic synchronization in the fields listed in Table 3-57.

Table 3-57 BGSyncStatus Class Fields

Parameters Description

long endTime

End time of the last synchronization in milliseconds since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronzation is currently in progress or has not yet run.

java.lang.Throwable lastError

Exception object thrown during the last synchronization. Returns NULL if the last synchronization was successful or no synchronization has completed yet.

int prio

Priority of the current or last synchronization.

int progressStage

Progress stage of synchronization if it is in progress.

int progressVal

Progress value in percentage of synchronization, if it is in progress.

java.lang.String[] pubs

Array of names of publications synchronized currently or during last synchronization.

long startTime

Start time of current or last synchronization, in milliseconds, since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronization has not yet started or the last synchronization time is unknown.


Example

The following provides an example of retrieving and processing the synchronization status:

/* Retrieve the synchronization status */
BGSyncStatus ss = bgSess.getSyncStatus();

/* start time */
if (ss.startTime == 0) return;
System.out.println("Sync Started:          " + time2str(ss.startTime));
/* end time */
if (ss.endTime != 0) 
  System.out.println("Sync Finished:         " + time2str(ss.endTime));
/* number of publications synchronized */
if (ss.pubs != NULL && ss.pubs.length != 0) {
  System.out.print("Publications synced:   ");
  for(int i = 0; i < ss.pubs.length; i++) {
    System.out.print(ss.pubs[i]);
    if (i == ss.pubs.length - 1)
       System.out.println();
    else
       System.out.print(", ");
 }
}
/* synchronization priority */
System.out.println("Sync Priority:         " + 
    (ss.prio == OSESession.PRIO_HIGH ? "High" : "Normal"));
/* synchronization result */
System.out.print("Sync Result:           ");
if (ss.lastError == NULL)
  System.out.println("Success");
else
  System.out.println("Failure: " + ss.lastError.toString());
3.2.1.1.5 BGMessageHandler Interface

The BGMessageHandler interface enables the Sync Agent and automatic synchronization message and error data to be trapped during synchronization.

Sync calls the handleLogMessage method with a parameter message of type LogMessage to report the current state and any errors for the Sync Agent or automatic synchronization. Within the handleLogMessage method, you can perform the appropriate action for the errors returned in the LogMessage structure.

For a complete description of the LogMessage class, see Section 3.2.1.1.6, "LogMessage Class".

Example

This example demonstrates how to implement the BGMessageHandler.

class myMessageHandler implements BGMessageHandler;
 {
 public void handleLogMessage(message)
 {
  private PrintStream ps = 
     new PrintStream(new FileOutputStream(FILE_NAME, false));

  ps.println("Time: " + new Date(message.time));
  ps.println("Type: " + (message.type == LogMessage.INFO ? "INFO" :
    (message.type == LogMessage.WARNING ? "WARNING" : "ERROR")));
  ps.println("Id: " + message.id);
  if (message.text != NULL)
    ps.println("Text: " + message.text);
  if (message.cause != NULL)
    ps.println("Cause: " + message.cause);
 }
}
3.2.1.1.6 LogMessage Class

The LogMessage class contains error message information passed to handlers when an event occurs within the application. It exists in the oracle.opensync.util package.

Table 3-58 LogMessage Class

Name Description

java.lang.Throwable cause

For error messages, optional cause of the error, which can be NULL.

If the error has an underlying cause, the cause could potentially point to several secondary messages through iterative java.lang.Throwable objects. This is useful if OSE returns an internal error. If cause is not present, NULL is returned.

static int ERROR

Error message number.

int id

Application-specific message number.

static int INFO

Informational message number.

static int NUM_TYPES

 

java.lang.String source

Name of the application that created the message.

java.lang.String text

Message text.

long time

Message creation time. Number in milliseconds since the epoch.

int type

Message type: INFO, WARNING or ERROR.

static int WARNING

Warning message.


Example

The following demonstrates how to print out the error information in the LogMessage class:

private void printMsg(PrintStream ps, LogMessage m)
{
 ps.println("Time: " + new Date(m.time));
 ps.println("Type: " + (m.type == LogMessage.INFO ? "INFO" :
   (m.type == LogMessage.WARNING ? "WARNING" : "ERROR")));
ps.println("Id: " + m.id);
if (m.text != NULL)
   ps.println("Text: " + m.text);
if (m.cause != NULL)
   ps.println("Cause: " + m.cause);
ps.println();}
3.2.1.1.7 BGException Class

This class signals a non-recoverable error during the synchronization process. The BGException() class constructs a clear object. The parameters for the constructor are listed in Table 3-59:

Constructors

BGException(int errCode)

BGException(int errCode, java.lang.Object arg)

BGException(int errCode, java.lang.Object[] args, java.lang.Throwable cause)

BGException(int errCode, java.lang.Object arg1, java.lang.Object arg2)

BGException(int errCode, java.lang.Object arg1, java.lang.Object arg2, java.lang.Object arg3)

BGException(int errCode, java.lang.Object arg, java.lang.Throwable cause)

BGException(int errCode, java.lang.Throwable cause)

Table 3-59 BGException Constructor Parameter Description

Parameter Description

errCode

Error codes are provided within the BGExceptionConstants class. Error codes for automatic synchronization are provided in the BGExceptionConstants class. Some BGException instances are thrown from Sync Control APIs. Others are used as causes of the automatic synchronization error messages.

The message handler returns an error message. For a complete list of the error messages that can be thrown in BGException, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.

arg, args, arg1, arg2, arg3

Return variables for information within the error message.

cause

The cause of this throwable or NULL if the cause is nonexistent or unknown.


BGException class extends BaseException class. The methods for getting cause and message are listed in Table 3-8, "BaseException Class Public Methods".

For a complete list of the error messages that can be thrown in the BGException, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.

3.2.1.2 Native APIs for the Sync Agent and Automatic Synchronization

The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:

3.2.1.2.1 Overview

Once automatic synchronization for the mobile client is enabled, you can manage it locally through the Sync Agent APIs and remotely through the Mobile Manager UI controls. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is paused, the Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.

The native interface for controlling the Sync Agent and automatic synchronization are defined in the <ORACLE_HOME>\Mobile\Sdk\include\bgsync.h file and implemented in <ORACLE_HOME>\Mobile\Sdk\bin\bgsync.dll.

The native interface provides for the following functions:

  • Start, stop, pause, resume, enable or disable automatic synchronization.

  • Retrieve automatic synchronization status information.

  • Specify message handlers for retrieving information about automatic synchronization events.

3.2.1.2.2 Initializing the Environment

The bgOpenSession method initializes the automatic synchronization environment—which is passed to each subsequent call with the bgSess handle.

In a multi-threaded environment, you cannot concurrently use a session from multiple threads, even with the same user. Instead, each thread should open its own session with the bgOpenSession method.

Note:

Every time you invoke the bgOpenSession method, you must also clean up with bgCloseSession method. These methods should always be called in pairs. See Section 3.2.1.2.6, "Close the Synchronization Environment" for more information.

Syntax

bgError bgOpenSession(bgSess *sess);

Table 3-60 lists the bgOpenSession parameters.

Table 3-60 bgOpenSession Parameters

Name Description

bgSess sess

Pointer to a session handle into which the new session is returned. Returns BG_ERR_INVALID_SESS if the handle is NULL.


This call initializes the bgSess automatic synchronization environment handle—which holds context information for the synchronization engine.

Returns zero if successful. Returns BG_ERR_INTERNAL if a system error has occured.

3.2.1.2.3 Synchronization Status

You can retrieve the status of automatic synchronization events or of the Sync Agent. The following sections describe the methods for retrieving the status:

Retrieve Sync Agent Status

Get the Sync Agent operational status with the bgGetAgentStatus method.

Syntax

bgError bgGetAgentStatus(bgSess sess, bgAgentStatus *s);

Table 3-61 lists the bgGetAgentStatus parameters.

Table 3-61 bgGetAgentStatus Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns BG_ERR_INVALID_SESS if the handle is NULL.

bgAgentStatus *s

Pointer to the Sync Agent status structure in which the status is returned. This pointer cannot be NULL. Note that the memory for the pointer fields is maintained by the Sync Agent and should not be freed by the application. See Table 3-62 for details on the returned bgAgentStatus structure.


Returns zero if the agent has reached specified status. Returns BG_ERR_INVALID_SESSION if the session handle is invalid. Returns BG_ERR_INTERNAL if a system error has occured.

The bgAgentStatus Structure

The bgAgentStatus structure provides status information on the Sync Agent.

Syntax

typedef struct _bgAgentStatus {
  ose1B statusCode;
  oseBool isExternal;
  oseU2B _reserved; /**< for alignment */
  const char *clientId;
  const char *processName;
  const char *networkName;
  ose4B processId;
  ose4B networkSpeed;
  ose4B batteryPower;
} bgAgentStatus;

Table 3-62 lists and describes the status information fields.

Table 3-62 bgAgentStatus Fields

Parameters Description

statusCode

Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 3-63.

isExternal

A boolean value that if OSE_TRUE, the Sync Agent was started in a separate process.

clientId

Sync user name.

processName

Name of the process within which the Sync Agent is currently running.

networkName

Name of the network currently used for synchronization, evaluated by Sync Agent.

processId

Process id of the process that is executing the Sync Agent, if relevant for a given platform.

networkSpeed

Network bandwidth in bits per second.

batteryPower

Remaining percentage of battery life, if relevant.


Table 3-63 lists the Sync Agent status codes:

Table 3-63 Sync Agent Status Codes

Code Status Name Description

0

BG_STATUS_STOPPED

Sync Agent application is not running.

1

BG_STATUS_START_PENDING

Sync Agent is in the process of starting.

2

BG_STATUS_RUNNING

Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active.

3

BG_STATUS_PAUSE_PENDING

Sync Agent is in the process of being paused.

4

BG_STATUS_PAUSED

Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed.

5

BG_STATUS_RESUME_PENDING

Sync Agent is in the process of resuming.

6

BG_STATUS_STOP_PENDING

Sync Agent is in the process of stopping.


Retrieve Status of the Current Automatic Synchronization Event

Get the current status of the automatic synchronization event within the Sync Agent with the bgGetSyncStatus method.

Syntax

bgError bgGetSyncStatus(bgSess sess, bgSyncStatus *s);

Table 3-64 lists the bgGetSyncStatus parameters.

Table 3-64 bgGetSyncStatus Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns BG_ERR_INVALID_SESS if the handle is NULL.

bgSyncStatus *s

Pointer to the synchronization status structure in which the status is returned. This pointer cannot be NULL. Note that the memory for the pointer is maintained by the Sync Agent and should not be freed by the application. See Table 3-65 for details on the returned bgSyncStatus structure.


Returns zero if the agent has reached specified status. Returns BG_ERR_INVALID_SESSION if the session handle is invalid. Returns BG_ERR_INTERNAL if a system error has occured.

The bgSyncStatus Structure

The bgSyncStatus structure provides status information on a current or the last automatic synchronization event in the Sync Agent.

Syntax

typedef struct _bgSyncStatus {
  oseSize pubCnt;
  const char **pubs;
  osePrio prio;
  oseU1B _reserved[3]; /**< for alignment */
  ose8B startTime;
  ose8B endTime;
  oseError res;
  const char *errMsg;
  const char *stateName;
  ose2B state;
  ose2B progress;
} bgSyncStatus;

Table 3-65 describes the fields in bgSyncStatus.

Table 3-65 bgSyncStatus Fields

Parameters Description

pubCnt

Number of publications synchronized.

pubs

Array of names of publications synchronized currently or during last synchronization.

prio

Priority of the current or last synchronization.

startTime

Start time of current or last synchronization, in milliseconds, since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronization has not yet started or the last synchronization time is unknown.

endTime

End time of the last synchronization in milliseconds since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronzation is currently in progress or has not yet run.

res

Last synchronization error code. Returns zero if the last synchronization was successful or no synchronization has completed yet.

errMsg

Last synchronization error message or NULL if no error.

stateName

Current synchronization stage name.

state

Current synchronization stage Returns OSE_SYNC_STATE_IDLE if the synchronization is not in progress.

progress

Progress value in percentage of synchronization, if it is in progress.


3.2.1.2.4 Control the Sync Agent

You can issue control commands to the Sync Agent with the bgControlAgent method. This call returns immediately and does not wait for completion of command execution. Use the bgWaitForStatus method to wait until the Sync Agent reaches a certain status.

Issue Sync Agent Control Commands

Returns zero if successful. Returns BG_ERR_INVALID_SESSION if the session handle is invalid. Returns BG_ERR_INVALID_COMMAND if the control command code is invalid. Returns BG_ERR_CANNOT_ACCEPT_CTRL if the Sync Agent is not able to execute the provided command in its current state.

Syntax

bgError bgControlAgent(bgSess sess, int ctrl, int opt);

Table 3-66 lists the bgControlAgent parameters.

Table 3-66 bgControlAgent Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns BG_ERR_INVALID_SESS if the handle is NULL.

int ctrl

Sync Agent control command codes, which are listed in Table 3-67.

int opt

options for given command


Table 3-67 lists the Sync Agent control command codes and options.

Table 3-67 Sync Agent Control Command Codes

Name Description Option Value

BG_CTRL_START

Start the Sync Agent. If the agent is running, pending or resume pending, this command has no effect. If the Sync Agent is paused, this command resumes the agent.

By default, this starts the Sync Agent within a separate process named syncagent or syncagent.exe on Windows platforms. However, if you set the option to BG_CTRL_OPT_START_INTERNAL, the Sync Agent is started within the current process.

BG_CTRL_STOP

Stop the Sync Agent. If the agent is stopped or stop pending, this command has no effect.

By default, stops the Sync Agent gracefully. However, if you set the option to BG_CTRL_OPT_TERMINATE, this kills the Sync Agent process, which should be used only as a last resort. This is not advisable if the Sync Agent was started with the BG_CTRL_OPT_START_INTERNAL option.

BG_CTRL_PAUSE

Pause the Sync Agent. If the agent is paused or pause pending, this command has no effect.

No options available.

BG_CTRL_RESUME

Resume the Sync Agent. If the agent is running, start pending, or resume pending, this command has no effect.

No options available.


Wait for Specific Sync Agent Status

Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.

This method is often used to wait for the Sync Agent to start. For example, the following code shows starting the Sync Agent and then waiting until the Sync Agent is up and running:

bgSess sess;
bgOpenSession(&sess);
bgControlAgent(sess, BG_CTRL_START, 0);
bgWaitForStatus(sess, BG_STATUS_RUNNING);

Syntax

bgError bgWaitForStatus(bgSess sess, int statusCode, long timeOut);

Table 3-68 lists the bgWaitForStatus parameters.

Table 3-68 bgWaitForStatus Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns BG_ERR_INVALID_SESS if the handle is NULL.

int statusCode

The status can be one of the following: BG_STATUS_STOPPED, BG_STATUS_RUNNING or BG_STATUS_PAUSED.

long timeOut

The timeOut parameter is the maximum time to wait for in milliseconds. Unlimited time is enabled if timeOut is specified as -1.


Returns zero if the agent has reached specified status. Returns BG_ERR_INVALID_SESSION if the session handle is invalid. Returns BG_ERR_WAIT_TIMEOUT if the timeout has expired. Returns BG_ERR_INVALID_WAIT_STATUS if the status code is invalid. Other errors may also be returned.

3.2.1.2.5 Setting Synchronization Parameters

You can set certain session parameters explicitly with the set session methods. The new parameter value takes effect only after the Sync Agent is restarted. When the session is created, the initial value for each option is loaded from the ose.ini file.

Options are separated into boolean and numeric parameters:

  • Boolean options are those options that can only be set to OSE_TRUE or OSE_FALSE.

  • Numeric options are set to an integer value.

Use the bgSetNumParam and bgGetNumParam methods to set and get the boolean and numeric session options. The bgSetNumParam method sets a parameter in the ose.ini file.

bgSetNumParam

bgError bgSetNumParam(bgSess sess, int param, long val);

Table 3-69 lists the bgSetNumParam parameters.

Returns zero if the option is retrieved successfully. Returns BG_ERR_INVALID_SESSION if the session handle is invalid. Returns BG_ERR_INVALID_PARAM if an invalid parameter code is specified. Returns BG_ERR_INTERNAL if a system error has occured. Other errors may also be returned.

Table 3-69 bgSetNumParam Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns BG_ERR_INVALID_SESS if the handle is NULL.

int param

Parameter code. See Table 3-12 for a list of all of the options that can bet set by this method.

long val

The parameter value to set. See Table 3-12 for potential values for this option.


bgGetNumParam

bgError bgGetNumParam(bgSess sess, int param, long *val);

Table 3-70 lists the bgGetNumParam parameters.

Returns zero if the option is retrieved successfully. Returns BG_ERR_INVALID_SESSION if the session handle is invalid. Returns BG_ERR_INVALID_PARAM if an invalid parameter code is specified. Returns BG_ERR_INTERNAL if a system error has occured.

Table 3-70 bgGetNumParam Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns BG_ERR_INVALID_SESS if the handle is NULL.

int param

Param code. See Table 3-71 for a list of all of the options that can bet retrieved by this method.

long *val

Pointer to a variable into which to return the parameter value. The pointer cannot be NULL. See Table 3-71 for potential values for this option.


Table 3-71 lists all boolean and numeric synchronization options and potential values. For all boolean options, the value can only be either OSE_TRUE or OSE_FALSE.

Table 3-71 Numeric and Boolean Session Options

Session Option Description

BG_PARAM_DISABLE_AGENT

Boolean parameter. If OSE_TRUE, specifies that the Sync Agent should be disabled. If the Sync Agent is disabled, the application and system startup process cannot start the Sync Agent. In this case, BG_ERR_AGENT_DISABLED error is returned from the bgControlAgent method. OSE_FALSE is the default.

Refers to the ose.ini parameter: BGSYNC.DISABLE.

BG_PARAM_MAX_LOG_FILE_COUNT

Maximum number of log files to keep in the bglog directory. The log is circular, so that when the maximum number of files is reached and a new log file needs to be added, the oldest file will be removed. For Windows 32 and Linux, the default is 128; for Windows CE, the default is 32.Refers to the ose.ini parameter: BGSYNC.MAX_LOG_FILES.

BG_PARAM_MAX_LOG_FILE_SIZE

Maximum log file size in bytes. On Windows 32 and Linux, the default is 1 MB. On Windows CE, the default is 128 KB.

Refers to the ose.ini parameter: BGSYNC.MAX_LOG_FILE_SIZE.

BG_PARAM_NET_WAIT_TIMEOUT

Time interval in milliseconds for the network manager to wait before evaluating the network state in absence of notifications. The network manager evaluates the network when a notification is received or the interval expires. The network is also evaluated periodically after each period of the said interval. The default is 10 minutes (600000 milliseconds).

Refers to the ose.ini parameter: BGSYNC.NET_WAIT_TIMEOUT.


3.2.1.2.6 Close the Synchronization Environment

Clears and performs a cleanup of the synchronization environment and resources. This function must be invoked for every bgOpenSession.

Returns zero if successful. Returns BG_ERR_INVALID_SESSION if the session handle is invalid.

Syntax

bgError bgCloseSession(bgSess sess);

Table 3-72 lists the bgCloseSession parameters.

Table 3-72 bgCloseSession Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns BG_ERR_INVALID_SESS if the handle is NULL.


3.2.1.2.7 Trap Sync Agent Messages with a Callback Function

You can create a callback function that is called when Sync Agent messages are generated, which traps automatic synchronization messages and error data. You register or unregister this callback function with the bgAddMsgCallback or bgRemoveMsgCallback methods.

Register the Callback Function

Returns zero if successful. Returns BG_ERR_INVALID_SESSION if the session handle is invalid. Returns BG_ERR_INTERNAL if a system error has occured.

Syntax

bgError bgAddMsgCallback(bgSess sess, bgUserCtx ctx, bgMsgCallback cb);

Table 3-73 lists the bgAddMsgCallback parameters.

Table 3-73 bgAddMsgCallback Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns BG_ERR_INVALID_SESS if the handle is NULL.

bgUserCtx ctx

A user-defined structure that contains the session environment settings. Since the bgMsgCallback callback method is user-implemented, it should know how to process the user-defined structure. The user context structure must be initialized by the application before calling the bgAddMsgCallback method.

bgMsgCallback cb

The callback function handle.


The Sync Agent invokes the callback function with a message to report the current state and any errors for the Sync Agent or automatic synchronization. Within the callback method, you can perform the appropriate action for the errors returned.

The message callback function is declared as follows:

typedef void (* bgMsgCallback)(bgUserCtx ctx, const bgMsg *msg);

Table 3-74 lists the bgMsgCallback parameters.

Table 3-74 bgMsgCallback Parameters

Name Description

bgUserCtx ctx

A user-defined structure that contains the session environment settings. Since the bgMsgCallback callback method is user-implemented, it should know how to process the user-defined structure. The user context structure must be initialized by the application before calling the bgAddMsgCallback method.

bgMsg *msg

Pointer for the message structure that reports on the current state and any errors for the Sync Agent or automatic synchronization.


The bgMsg structure contains error message information passed to handlers when an event occurs within the Sync Agent or automatic synchronization.

Note:

The memory for bgMsg structure is allocated within the mobile client and should not be freed by the application.

Syntax

typedef struct _bgMsg {
  ose8B time;
  ose4B type;
  ose4B id;
  const char *txt;
  const bgErrorDesc *cause;
} bgMsg;

Table 3-75 describes the fields of bgMsg.

Table 3-75 bgMsg Structure

Name Description

time

Message creation time. Number in milliseconds since the epoch.

type

Message type: BG_MSG_TYPE_INFO, BG_MSG_TYPE_WARNING or BG_MSG_TYPE_ERROR.

id

Application-specific message number.

txt

Message text.

cause

For error messages, optional cause of the error, which can be NULL. If not NULL, points to a bgErrorDesc structure.

If the error has an underlying cause, the cause could potentially point to several secondary messages through a chain of bgErrorDesc structures through cause. This is useful if the Sync Agent returns an internal error. If cause is not present, then cause is set to NULL.


Unregister the Callback Function

Remove the message callback function from the Sync Agent, after which it will no longer be invoked.

Returns zero if successful. Returns BG_ERR_INVALID_SESSION if the session handle is invalid. Returns BG_ERR_INTERNAL if a system error has occured.

Syntax

bgError bgRemoveMsgCallback(bgSess sess, bgUserCtx ctx, bgMsgCallback cb);

Table 3-76 lists the bgRemoveMsgCallback parameters.

Table 3-76 bgRemoveMsgCallback Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns BG_ERR_INVALID_SESS if the handle is NULL.

bgUserCtx ctx

A user-defined structure that contains the session environment settings.

bgMsgCallback cb

The callback function handle.


3.2.1.2.8 Retrieve Synchronization Error Message

Retrieves the last error of a call to one of the automatic synchronization APIs.

Syntax

bgError bgGetLastError(bgSess sess, const bgErrorDesc **errDesc);

Table 3-77 lists the bgGetLastError parameters.

Returns zero if successful. Returns the BG_ERR_INVALID_SESS error if the session handle was invalid. Returns the BG_ERR_INTERNAL error if a system error has occured.

Table 3-77 bgGetLastError Parameters

Name Description

bgSess sess

Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. This handle can be NULL if trying to retrieve error information from a failed bgOpenSession call.

const bgErrorDesc **errDesc

A pointer to an bgErrorDesc pointer into which the bgErrorDesc pointer is returned. The pointer cannot be NULL. The structures referenced by this pointer are only valid until the next call.


The bgErrorDesc structure is a typedef for oseErrorDesc, which is defined as follows:

typedef struct _oseErrorDesc {
  oseError code;                /* error code */
  const char *type;             /* a string describing the type of error */
  const char *msg;              /* error message */
  struct _oseErrorDesc *cause;  /* underlying cause, if present */
} oseErrorDesc;

If the error has an underlying cause, the oseErrorDesc.cause points to another oseErrorDesc structure, which in turn can have its own cause, and so on. This is useful if the OSE call returns an OSE_ERR_INTERNAL_ERROR, which can be further defined within another oseErrorDesc structure. If the cause is not present, oseErrorDesc.cause is NULL.

Note:

The memory for oseErrorDesc structure is allocated within mobile server and should not be freed by the application.

3.2.1.3 The .Net APIs for the Sync Agent and Automatic Synchronization

The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:

Note:

For more details on these classes, refer to the Oracle Database Mobile Server .Net API.
3.2.1.3.1 Overview

Once automatic synchronization for the mobile client is enabled, you can manage it locally through the Sync Agent APIs and remotely through the Mobile Manager UI controls. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is paused, the Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.

The .Net interface for controlling the Sync Agent and automatic synchronization resides in the Oracle.OpenSync.SyncAgent namespace. The .Net APIs are implemented in Oracle.OpenSync.dll.

The .Net interface provides for the following functions:

  • Controlling the Sync Agent.

  • Retrieve the status of the Sync Agent and automatic synchronization events.

  • Specify custom handlers for events that occur in automatic synchronization.

The following are the classes and interface for the .Net API for controlling the Sync Agent and automatic synchronization:

  • BGStatusCode Enumeration

  • BGSession Class

  • BGAgentStatus Class

  • BGSyncStatus Class

  • BGMessageType Enumeration

  • BGMessageHandler Interface

3.2.1.3.2 BGStatusCode Enumeration

The BGStatusCode enumeration specifies the Sync Agent status codes.

Syntax

public enum BGStatusCode
    {
        Stopped = 0, 
        StartPending, 
        Running, 
        PausePending, 
        Paused, 
        ResumePending, 
        StopPending 
    }

Table 3-78 provides more information about these codes.

Table 3-78 Sync Agent Status Codes

Status Name Value Description

Stopped

0

Sync Agent application is not running.

StartPending

1

Sync Agent is in the process of starting.

Running

2

Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active.

PausePending

3

Sync Agent is in the process of being paused.

Paused

4

Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed.

ResumePending

5

Sync Agent is in the process of resuming.

StopPending

6

Sync Agent is in the process of stopping.


3.2.1.3.3 BGSession Class

BGSession is the main class for controlling automatic synchronization through the Sync Agent, as follows:

  • Start, stop, pause, resume, enable or disable automatic synchronization.

  • Retrieve automatic synchronization status information.

  • Specify message handlers for retrieving information about automatic synchronization events.

Note:

In a multi-threaded environment a single BGSession should not be used from multiple threads. Each thread should open its own session.

Properties

The following documents the properties for the BGSession class.

  • Read-write properties read or write the value of a field with get and set accessors.

  • Read-only properties read the value of a field with the get accessor.

  • Write-only properties set the value of a field with the set accessor.

Boolean properties get or set the value of a field to either true or false.

Table 3-79 lists all BGSession properties. Section 3.2.1.3.2, "BGStatusCode Enumeration" lists all enumerations.

Table 3-79 BGSession Properties

Property Description

StatusCode

Gets the Sync Agent status code from the BGStatusCode enumeration.

Enabled

Boolean property that gets or sets to TRUE if the Sync Agent is enabled; otherwise, FALSE. If the Sync Agent is disabled, it is not allowed to start, which is useful when you only want manual synchronization events.


Constructor

BGSession( )

Public Methods

The public methods and their parameters for the BGSession class are listed in Table 3-80:

Table 3-80 BGSession Class Public Method Parameters

Method Description

void Start()

Start the Sync Agent.

If the agent is already running, starting, or resuming, this call is ignored. If the agent is paused, this call resumes the Sync Agent. This call is asynchronous and does not wait for the Sync Agent to be started before returning. Use the waitForStatus method to wait for the Sync Agent.

void StartInternal()

Same as Start, but starts the Sync Agent within the application process.

void Pause()

Pauses the Sync Agent.

If the agent is aready paused or being paused, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be paused before returning. Use the waitForStatus method to wait for the Sync Agent.

void Resume()

Resumes the Sync Agent.

If the agent is already resumed or resuming, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be resumed before returning. Use the waitForStatus method to wait for the Sync Agent.

void Stop()

Stop the Sync Agent.

If the agent is already stopped or stopping, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be stopped before returning. Use the waitForStatus method to wait for the Sync Agent.

void Kill()

Forcefully terminate the Sync Agent process instead of stopping it gracefully. Use this option as a last resort if the Stop method is not working because some tasks are hanging in the Sync Agent. Not recommended if the Sync Agent was started with StartInternal.

void Close()

Closes the session and release all the resources used by the session.

BGAgentStatus GetAgentStatus()

Retrieves the current Sync Agent status. See Section 3.2.1.3.4, "BGAgentStatus Object" for more details on the status information returned.

BGSyncStatus GetSyncStatus()

Get current status of automatic synchronization managed by the Sync Agent. See Table 3-84 for more details on the status information returned.

void WaitForStatus (int statusCode)

boolean WaitForStatus (int statusCode, long timeOut)

Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.

  • The status can be one of the following: RUNNING, PAUSED or STOPPED.

  • The timeOut parameter is the maximum time to wait for in milliseconds. Unlimited time if no timeout provided.

Returns TRUE if the agent has reached specified status; FALSE if the timeout has occurred.


Example

The following example demonstrates how to start the Sync Agent, retrieve status of the Sync Agent and add a message handler for the session:

// Create the BGSession object
 using(BGsession sess = new BGSession())
 {
  //Start the Sync Agent, which enables all automatic synchronization events
  sess.Start();
  //Wait until the Sync Agent successfully starts
  sess.WaitForStatus(BGAgentStatus.RUNNING);
  //Retrieve the status of the Sync Agent
  BGAgentStatus s = sess.GetAgentStatus();
  //Print out the user that is using automatic synchronization
  Console.WriteLine("User name: " + s.clientId);
  //Add a message handler
  sess.MessageReceived += new BGMessageHandler(myHandler);
  ...
  }
 //When finished, close the session to release all resources
 sess.Close();
3.2.1.3.4 BGAgentStatus Object

The BGAgentStatus object represents the current status of the Sync Agent.

Public Methods

The methods for the BGAgentStatus are listed in Table 3-81.

Table 3-81 BGAgentStatus Class Public Method

Method Description

string GetStatusName(BGStatusCode statusCode)

Get language-specific name of a given status code. When you provide one of the status codes shown in Table 3-78, the appropriate name is returned. Translation dependent on the device language settings


Fields

BGAgentStatus provides status information on the Sync Agent. Table 3-82 lists and describes the status information fields within the BGAgentStatus class.

Table 3-82 BGAgentStatus Class Fields

Parameters Description

string AppName

The name of the application or process that is executing the Sync Agent. On some platforms, such as Android, it is possible to execute the Sync Agent within an application process.

int BatteryPower

Remaining percentage of battery life, if relevant.

string ClientId

Sync user name.

string NetworkName

Name of the network currently used for synchronization, evaluated by Sync Agent.

int NetworkSpeed

Network bandwidth in bits per second.

int ProcessId

Process id of the process that is executing the Sync Agent, if relevant for a given platform.

BGStatusCode StatusCode

Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 3-78.


Example

The following provides an example of retrieving and processing the Sync Agent status:

BGAgentStatus ags = bgSess.GetAgentStatus();
 Console.WriteLine("Agent Status:          " + 
   BGAgentStatus.GetStatusName(ags.StatusCode));
if (ags.StatusCode == BGStatusCode.Stopped)
 return;
 
Console.WriteLine("Client ID:             " + ags.ClientId);
Console.WriteLine("Process Name:          " + ags.AppName);
Console.WriteLine("Process ID:            " + ags.ProcessId);
if (ags.NetworkSpeed > 0) {
  Console.WriteLine("Network Name:          " + ags.NetworkName);
  Console.WriteLine("Network Speed:         " + ags.NetworkSpeed + " bps");
}
else
  Console.WriteLine("Network is not present");
if (ags.BatteryPower > 0)
  Console.WriteLine("Battery Power:         " + ags.BatteryPower + "%");
else
  Console.WriteLine("Battery is not present");
3.2.1.3.5 BGSyncStatus Object

The BGSyncStatus object provides status information on a current or the last automatic synchronization event in the Sync Agent.

Public Methods

The methods for the BGSyncStatus are listed in Table 3-83.

Table 3-83 BGSyncStatus Class Public Method

Method Description

String GetSyncStageName( SyncProgressStage stage)

Get language-specific name of a given sync status code. When you provide one of the status codes shown in Table 3-78, the appropriate name is returned. Translation dependent on the device language settings


Fields

BGSyncStatus provides status information on automatic synchronization in the fields listed in Table 3-84.

Table 3-84 BGSyncStatus Class Fields

Parameters Description

DateTime EndTime

End time of the last synchronization. EndTime is set to DateTime.MinValue if the synchronization is currently in progress or has not yet run.

Exception LastError

Exception object thrown during the last synchronization. Returns NULL if the last synchronization was successful or no synchronization has completed yet.

DataPriority Prio

Priority of the current or last synchronization.

SyncProgressStage ProgressStage

Progress stage of synchronization if it is in progress.

int ProgressVal

Progress value in percentage of synchronization, if it is in progress.

string[] Pubs

Array of names of publications synchronized currently or during last synchronization.

DateTime StartTime

Start time of the last synchronization. StartTime is set to DateTime.MinValue if the synchronization has not yet run.


Properties

The following documents the properties for the BGSyncStatus class.

  • Read-write properties read or write the value of a field with get and set accessors.

  • Read-only properties read the value of a field with the get accessor.

  • Write-only properties set the value of a field with the set accessor.

Boolean properties get or set the value of a field to either true or false.

Table 3-85 lists all BGSyncStatus properties. Section 3.2.1.3.2, "BGStatusCode Enumeration" lists all enumerations.

Table 3-85 BGSyncStatus Properties

Property Description

SyncOccured

Read-only boolean property. If an automatic synchronizatoin has already occured, SyncOccured is TRUE.

SyncInProgress

Read-only boolean property. If automatic synchronization is in progress, SyncInProgress is TRUE.


Example

The following provides an example of retrieving and processing the synchronization status:

BGSyncStatus ss = bgSess.GetSyncStatus();
 if (!ss.SyncOccured) return;
 
 Console.WriteLine();
 Console.WriteLine("Sync Started:          " + dt2str(ss.StartTime));

 if (!ss.SyncInProgress)
   Console.WriteLine("Sync Finished:         " + dt2str(ss.EndTime));
 if (ss.Pubs != NULL && ss.Pubs.Length != 0) {
   Console.Write("Publications synced:   ");
   for(int i = 0; i < ss.Pubs.Length; i++) {
     Console.Write(ss.Pubs[i]);
     if (i == ss.Pubs.Length - 1)
       Console.WriteLine();
     else
       Console.Write(", ");
   }
  }

 Console.WriteLine("Sync Priority:         " + ss.Prio.ToString());
 Console.Write("Sync Result:           ");
 if (ss.LastError == NULL)
   Console.WriteLine("Success");
 else
   Console.WriteLine("Failure: " + ss.LastError.ToString());
 Console.WriteLine();
3.2.1.3.6 BGMessageHandler Interface

The BGMessageHandler interface enables the Sync Agent and automatic synchronization message and error data to be trapped during synchronization.

The message handler is defined as follows:

public delegate void BGMessageHandler(object sender, BGMsgEventArgs args);
 

You can implement a callback function with the same input parameters as the BGMessageHandler and specify it as your callback function. The following is an example of a user-implemented callback function called msgCallback. It processes the error message information available in the Msg parameter that is contained within the BGMsgEventArgs structure.

static void msgCallback(object sender, BGMsgEventArgs args)
{
  Console.WriteLine("Time:        " + dt2str(args.Msg.Time));
  Console.WriteLine("Type         " + args.Msg.Type);
  Console.WriteLine("Id           " + args.Msg.Id);
  if (args.Msg.Text != NULL)
     Console.WriteLine("Text         " + args.Msg.Text);
  if (args.Msg.Cause != NULL)
     Console.WriteLine("Cause        " + args.Msg.Cause);
  Console.WriteLine();
}

The following event adds or removes a custom message handler to the Sync Agent.

public event BGMessageHandler MessageReceived

With the MessageReceived event, you can add the message handler as follows:

sess.MessageReceived += new BGMessageHandler(msgCallback);
 

Sync calls the msgCallback method with a message to report the current state and any errors for the Sync Agent or automatic synchronization. Within the msgCallback method, you can perform the appropriate action for the errors returned in the Msg variable of type BGMessage, which is a public variable in the BGMsgEventArgs structure. In addition, System.EventArgs is the base class for BGMsgEventArgs, which contains event data.

For a complete description of the BGMsgEventArgs class, see Section 3.2.1.3.8, "BGMsgEventArgs Class".

3.2.1.3.7 BGMessageType Enumeration

The BGMessageType enumeration contains the definitions for the different message types.

Syntax

public enum BGMessageType
    {
        Info, 
        Warning, 
        Error 
    }

Table 3-86 provides more details about these message types.

Table 3-86 BGMessageType

Status Name Value Description

Info

0

Informational message.

Warning

1

Warning message.

Error

2

Error message.


3.2.1.3.8 BGMsgEventArgs Class

The BGMsgEventArgs class contains the event arguments for the BGMessageHandler interface. This class encapsulates the BGMessage object. Both classes exist in the Oracle.OpenSync.SyncAgent namespace.

Syntax

public class BGMsgEventArgs : EventArgs
{
        public readonly BGMessage Msg; 
}

The BGMessage class contains error message information passed to handlers when an event occurs within the application.

Table 3-87 BGMessage Class Public Fields

Name Description

DateTime Time

Message creation time.

BGMessageType Type

Message type: INFO, WARNING or ERROR. See the Section 3.2.1.3.7, "BGMessageType Enumeration" for details.

BGMessageId Id

Error message number. The error code can be one of the BGMessageId enumeration values, which are documented in the "BGException Error Messages" in the Oracle Database Mobile Server Message Reference.

string Text

Message text.

Exception Cause

For error messages, optional cause of the error, which can be NULL.


3.2.1.3.9 BGException Class

The BGException class signals an error during execution of .Net Sync Agent Control API. The errors can be recoverable. In addition, the BGException class can appear in the Cause field in a BGMessage object.

The BGException class inherits from OSEException, which is documented in Section 3.1.1.3.7, "OSEException Class".

The BGException read-only properties are listed in Table 3-88.

Table 3-88 BGException Properties

Parameters Description

ErrorCode

Gets the exception error code. The error code can be one of the BGMessageId enumeration values, which are documented in the "BGException Error Messages" in the Oracle Database Mobile Server Message Reference.

Kind

Gets the exception type name.

InnerException

Use the InnerException property to get underlying cause of the BGException.


Constructors

BGException(int errCode)

BGException(int errCode, string msg)

The parameters for the constructor are listed in Table 3-89:

Table 3-89 BGException Constructor Parameter Description

Parameter Description

errCode

The error code can be one of the BGMessageId enumeration values, which are documented in the "BGException Error Messages" in the Oracle Database Mobile Server Message Reference.

msg

The error message.


3.2.1.4 OCAPI Sync Control APIs

The following sections describe how to start/stop or enable/disable automatic synchronization from the OCAPI Sync Control API for the mobile client:

Each of these APIs includes a stop method that has a timeout input parameter. You can supply one of the following values for the timeout, which is a long that specifies a time in milliseconds to wait for any current activity in the automatic synchronization to complete.

  • BG_STOP_TIMEOUT: A value in seconds that allows the automatic synchronization process to complete before stopping the service. By default, this is set to 5 seconds.

  • BG_KILL_AGENT: A value of -1 that makes the automatic synchronization service stop immediately, even if it is in the middle of a synchronization. If an automatic synchronization is in process, it will be terminated. NO errors or messages are returned.

  • Any long value in milliseconds: If the automatic synchronization does not stop within the time designated, the method returns with an error of BG_ERROR_TIMEOUT. At this point, reissue the stop method to terminate the automatic synchronization immediately by supplying BG_KILL_AGENT or -1 as the input value.

3.2.1.4.1 C/C++ Sync Control APIs to Start or Enable Automatic Synchronization

The following sections describe the Sync Control APIs for C/C++ applications.

To start or stop the Sync Agent, use the following APIs:

olError olStartSyncAgent() ;
olError olStopSyncAgent(long timeout);

To enable or disable the Sync Agent, use the following APIs:

typedef struct _olSyncOpt {
        olBool bDisable;
} olSyncOpt;
olError olGetSyncOptions(olSyncOpt *opt);
olError olSetSyncOptions(const olSyncOpt *opt);

The olGetSyncOptions and olSetSyncOptions methods take a pointer to the olSyncOpt structure as a parameter. The olSyncOpt structure contains the bDisable boolean, which is true if the Sync Agent is disabled.

To enable the Sync Agent, perform the following:

olSyncOpt opt.bDisable = FALSE;
olSetSyncOptions(&opt);

To disable the Sync Agent, perform the following:

olSyncOpt opt.bDisable = TRUE;
olSetSyncOptions(&opt);

Use olGetSyncOptions method to retrieve the current value of the bDisable boolean.

3.2.1.4.2 C# Sync Control APIs to Start or Enable Automatic Synchronization

The following BGSyncControl class has the following methods:

  • Start—Start automatic synchronization that was previously stopped.

  • Stop—Stop automatic synchronization. Normally, this is used to stop automatic synchronization before a manual synchronization is invoked. Then, use the start method to restart automatic synchronization.

  • Enabled property—Set Enable to TRUE to enable automatic synchronization that was previously disabled. Set to FALSE to disable automatic synchronization. Even if the client is restarted, automatic synchronization is not enabled unless you enable synchronization. This property returns a boolean where true states that automatic synchronization is enabled and false that it is disabled.

public class BGSyncControl
        {
                public void Start();
                public void Stop(int timeout);
        public bool Enabled{)
}

All methods throw an OracleException in case of failure.

3.2.1.4.3 Java Sync Control APIs to Start or Enable Automatic Synchronization

The following BGSyncControl class has the following methods:

  • start—Start automatic synchronization that was previously stopped.

  • stop—Stop automatic synchronization. Normally, this is used to stop automatic synchronization before a manual synchronization is invoked. Then, use the start method to restart automatic synchronization.

  • enable—Enables automatic synchronization that was previously disabled.

  • disable—Disables automatic synchronization on a client. Even if the client is restarted, automatic synchronization is not enabled unless you enable synchronization.

  • isEnabled—Returns a boolean where true states that automatic synchronization is enabled.

package oracle.lite.msync;
class BGSyncControl {
          public void start() throws SyncException;
          public void stop(long timeout) throws SyncException;
         void enable(); 
         void disable(); 
         bool isEnabled(); 
}

3.2.2 OCAPI APIs for Retrieving Status on Automatic Synchronization

Note:

The following OCAPI APIs are currently supported for the mobile client, but are not the direction recommended for future applications. To develop applications for future support, migrate existing applications to use the OSE APIs for Managing Automatic Synchronization.

If you want to know at what stage the automatic synchronization cycle is, you can request status from the Sync Agent. In the client application, execute the get status API, which will return immediately with at what stage the automatic synchronization cycle is executing. This is different from the notification message API, which only returns when an event is completed within the synchronization cycle.

The get status API returns a structure that describes this event.

The following sections provide implementation details for each development language:

3.2.2.1 Retrieving Status for Automatic Synchronization in Java Applications

Use the getStatus method in your Java client application to retrieve status on the automatic synchronization, as follows:

public BGSyncStatus getStatus() throws SyncException

This method returns the BGSyncStatus class with the status information on the automatic synchronization, as follows:

public class BGSyncStatus 
{
   public String clientId;
   public short  syncState;
   public String syncStateStr;
   public short syncProgress;
   public short lastSyncError;
   public short lastSyncType;
   public Date lastSyncTime;
   
   public short applyState;
   public String applyStateStr;
   public short applyProgress;
   public short lastApplyError;
   public Date  lastApplyTime;
   
   public String networkName;
   public int networkSpeed;
   public int batteryPower;
}

See Section 3.2.2.4, "Input Parameters for Retrieving Messages" for a description of the input parameters in the structure.

3.2.2.2 Retrieving Status for Automatic Synchronization in C and C++ Applications

Use the olGetSyncStatus method in your C/C++ client application to retrieve status on the automatic synchronization, as follows:

olError olGetSyncStatus(olSyncStatus *s);

The Sync Agent returns the olSyncStatus class, which you provide as an input parameter, with the information on what happened, as follows:

typedef struct _olSyncStatus {
    char clientId[BG_MAX_USERNAME];
    ol2B syncState;
    ol2B syncProgress;
    char syncStateStr[BG_MAX_STATUS_STR];
    olError lastSyncError;
    ol2B lastSyncType;
    ol8B lastSyncTime;
    ol2B applyState;
    ol2B applyProgress;
    char applyStateStr[BG_MAX_STATUS_STR];
    olError lastApplyError;
    olU2B _reserved;
    ol8B lastApplyTime;
    char networkName[BG_MAX_STATUS_STR];
    ol4B networkSpeed;
    ol4B batteryPower;
} olSyncStatus;

See Section 3.2.2.4, "Input Parameters for Retrieving Messages" for a description of the input parameters in the structure.

3.2.2.3 Retrieving Status for Automatic Synchronization in C# Applications

Use the GetStatus method in your C/C++ client application to retrieve status on the automatic synchronization, as follows:

public BGSyncStatus GetStatus();

This method returns the BGSyncStatus class with the status information on the automatic synchronization, as follows:

public class BGSyncStatus 
{
  public string clientId;
  public short  syncState;
  public string syncStateStr;
  public short syncProgress;
  public short lastSyncError;
  public short lastSyncType;
  public long lastSyncTime;
  public short applyState;
  public string applyStateStr;
  public short applyProgress;
  public short lastApplyError;
  public ushort  _reserved;
  public long  lastApplyTime;
  public string networkName;
  public int networkSpeed;
  public int batteryPower;
}

See Section 3.2.2.4, "Input Parameters for Retrieving Messages" for a description of the input parameters in the structure.

3.2.2.4 Input Parameters for Retrieving Messages

The input parameters in the input structure/class are as follows:

Table 3-90 Status Class Fields

Field Description

clientId

User name

syncState

A numeric value that denotes the current synchronization stage, such as compose, send, or receive.

syncStateStr

String describing the state, as denoted in the syncState, for the automatic synchronization.

syncProgress

A percentage that indicates the current progress for the automatic synchronization.

lastSyncError

If an error occurred in the last synchronization, this is the error code. If no error, this value is zero.

lastSyncType

The priority of the data for the last synchronization. If 1, then high priority data; if 0, then regular priority data was synchronized.

lastSyncTime

Time of the last automatic synchronization.

applyState

Code that indicates the state for the apply phase.

applyStateStr

String describing the state for the apply phase, as denoted in the applyState variable.

applyProgress

A percentage that indicates the current progress for the apply phase.

lastApplyError

If an error occurred in the last apply phase, this is the error code. If no error, this value is zero.

lastApplyTime

Time of the last apply phase.

networkName

The network name assigned to this network.

networkSpeed

Current bandwidth of the network.

batteryPower

Current battery power percentage.


3.2.3 OCAPI Notification APIs for the Automatic Synchronization Cycle Status

Note:

The following OCAPI APIs are currently supported for the mobile client, but are not the direction recommended for future applications. To develop applications for future support, migrate existing applications to use the OSE APIs for Managing Automatic Synchronization.

You can develop a mobile client application to be notified when an automatic synchronization cycle occurs. The application is notified from the Sync Agent when the automatic synchronization completes as well as when a critical event occurs in the client device. For example, when the device battery runs critically low, Oracle Database Mobile Server can notify the application.

In the client application, create a procedure that executes one of the following message APIs. When your application calls the get message API, it blocks until an event occurs within an automatic synchronization. It returns a structure that describes this event.

The following sections provide implementation details for each development language:

3.2.3.1 Automatic Synchronization Notification for C/C++ Application

Use the olGetSyncMsg method in your client application to receive the automatic synchronization notification when implementing for C/C++ applications. In order to block for the status, you need to perform the following:

  1. Start the application messaging service with the olStartSyncMsg method, providing a queue handle of type olAppMsgQ. This message starts the messaging service and returns the queue handle in the olAppMsgQ.

  2. Execute the olGetSyncMsg with the olAppMsgQ message handle and the defined olSyncMsg structure for the returned automatic synchronization information.

The following provides the method definitions:

typedef void *olAppMsgQ
/* start application messaging, get queue handle */
olError olStartSyncMsg(olAppMsgQ *q);
/*Provide the queue handle and block to retrieve automatic synchronization event */
olError olGetSyncMsg(olAppMsgQ q, olSyncMsg *m);

The olGetSyncMsg method blocks until an event occurs, then the Sync Agent returns the olSyncMsg class, which you provide as an input parameter, with the information on what happened, as follows:

typedef struct _olSyncMsg {
    ol2B type;
    ol2B id;
    char msg[BG_MAX_MSG];
} olSyncMsg;

See Section 3.2.3.4, "Input Parameters for Automatic Synchronization Notification" for a description of the input parameters in the structure.

The C/C++ application performs in a different manner than the Java and C# versions in that this creates a message service with its own message queue. Thus, when finished you must perform some cleanup to ensure that the message queue handle is released. Use the olStopSyncMsg method to stop the messaging service and release the handle. This must be performed for every message queue that is opened with the olStartSyncMsg method.

olError olStopSyncMsg(olAppMsgQ q);

If you want to force an existing olGetSyncMsg to return, use the olCancelSyncMsg from another thread in the application. This causes the olGetSyncMsg to return with the BG_ERR_APP_MSG_CANCEL error.

olError olCancelSyncMsg(olAppMsgQ q);

3.2.3.2 Automatic Synchronization Notification for C# Application

Use the GetMessage method in your client application to receive the automatic synchronization notification when implementing for C# applications, as follows:

public BGSyncMsg GetMessage();

This method blocks until an event occurs, then the Sync Agent returns the BGSyncMsg class with the information on what happened, as follows:

public class BGSyncMsg
{
 public int Type;
 public int Id;
 public string Msg;
}

See Section 3.2.3.4, "Input Parameters for Automatic Synchronization Notification" for a description of the input parameters in the class.

3.2.3.3 Automatic Synchronization Notification for Java Applications

Use the getMessage method in your client application to receive the automatic synchronization notification when implementing for Java applications, as follows:

public class BGSyncControl 
{
 public BGSyncMsg getMessage() throws SyncException;
}  

This method blocks until an event occurs, then the Sync Agent returns the BGSyncMsg class with the information on what happened, as follows:

public class BGSyncMsg{
    public int type;
    public int id;
    public String msg;
}  

See Section 3.2.3.4, "Input Parameters for Automatic Synchronization Notification" for a description of the input parameters in the class.

3.2.3.4 Input Parameters for Automatic Synchronization Notification

The input parameters in the input structure/class are as follows:

Table 3-91 The Sync Message Variables

Variable Description

Event type

The event can be of three types, each of which indicate the level of severity of this notification:

  • INFO

  • ERROR

  • WARNING

Event identifier for INFO types:

The INFO event identifer describes what occurred, as follows:

  • SYNC_STARTED: The Sync Agent has started the synchronization task.

  • SYNC_SUCCEEDED: Data synchronization completed successfully.

  • APPLY_STARTED: The Sync Agent has started the apply task.

  • APPLY_SUCCEEDED: The apply phase completed successfully.

  • SVR_NOTIF: The Sync Agent has received a server notification. The message contains information about the server notification, such as publication name, number of modified records and the record priority (high priority or normal).

  • NETWORK_CHANGED: Device has moved into a different network

  • AGENT_STARTED: The Sync Agent started.

  • AGENT_STOPPED: The Sync Agent stopped.

Event identifier for the WARNING type:

The WARNING event identifier describes in more detail what occurred, as follows:

  • BATTERY_LOW: Device's battery is running low

  • MEMORY_LOW: Device's memory is running low

Event identifier for the ERROR type:

The ERROR event identifier describes in more detail what occurred, as follows:

  • APPLY_FAILED: The apply failed. In this case, 'message' contains the reason for failure.

  • SYNC_FAILED: Data synchronization failed. In this case, 'message' contains the reason for failure.

  • AGENT_ERROR: An internal error condition occurred. The message contains the actual error message. Examples would be failure to load a rule, failure to process server notification, failure to evaluate system power, and so on. In spite of this error, the Sync Agent continues to execute. Fatal errors are written to the olSyncAgent.err file.

Event Message

String message that expounds on the information provided by the event type and identifier.