Skip Headers
Oracle® Database Lite Developer's Guide
Release 10.3

Part Number E12090-02
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
View PDF

4 Invoking Synchronization in Applications With the Mobile Sync APIs

The following sections describe the Mobile Sync APIs available to start synchronization programmatically within your application on the Mobile client, whether the application is C, C++, C#, or Java:

4.1 Synchronization APIs For C or C++ Applications

You can initiate and monitor synchronization from a C or C++ client application. The 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\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 functions available for setting up and initiating the synchronization are as follows:

  1. Section 4.1.1, "Overview of C/C++ Synchronization API"

  2. Section 4.1.2, "Initializing the Environment With ocSessionInit"

  3. Section 4.1.3, "Managing the C/C++ Data Structures"

  4. Section 4.1.4, "Retrieving Publication Information With ocGetPublication"

  5. Section 4.1.5, "Managing User Settings With ocSaveUserInfo"

  6. Section 4.1.6, "Manage What Tables Are Synchronized With ocSetTableSyncFlag"

  7. Section 4.1.7, "Configure Proxy Information"

  8. Section 4.1.8, "Start the Synchronization With the ocDoSynchronize Method"

  9. Section 4.1.9, "Clear the Synchronization Environment Using ocSessionTerm"

  10. Section 4.1.10, "Retrieve Synchronization Error Message with ocGetLastError"

  11. Section 4.1.11, "Enable File-Based Synchronization through C or C++ APIs"

4.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 username 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.

4.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 4.1.5, "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 4.1.9, "Clear the Synchronization Environment Using ocSessionTerm" for more information.

Syntax

int ocSessionInit( ocEnv env );

Table 4-1 lists the ocSessioninit parameter and its description.

Table 4-1 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 username and password (See Section 4.1.5, "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 4.1.3.1, "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);

4.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.

4.1.3.1 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 4-2 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 4-2 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, then use HTTP built-in transport driver. This is the default.

If set to OC_USER_METHOD, then use user provided transport functions.

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

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 Lite 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 sync is bi-directional (default).If set to OC_SENDONLY, then push changes only to the server. This stops the sync 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 4.1.3.2, "ocTransportEnv Data Structure".

progressProc

fnProgress

Optional.

If not null, points to the callback for progress listening. See Section 4.1.8.1, "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).

clientDbMode

Enum

Optional.

If set to OC_DBMODE_EMBEDDED (default), it uses local Oracle Database Lite ODBC driver. If set to OC_DBMODE_CLIENT, it uses the Branch Office driver.

syncTimeLog

Short

Optional.

If set to 1, log sync start time is recorded in the conscli.odb file.

updateLog

Short

Optional.

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

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 sync 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;

4.1.3.2 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])

4.1.4 Retrieving Publication Information With ocGetPublication

This function gets the publication name on the client from the Web-to-Go application name. The Web-to-Go user knows only the application name, which happens when the Packaging Wizard is used to package an application before publishing it. If the Web-to-Go 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 4-3 below.

Table 4-3 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 sync webtogo 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("Sync compeleted\n");

         

         // close OCAPI session

         rc = ocSessionTerm(&env);

         return 0;

}

4.1.5 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 4-4 lists the ocSaveUserInfo parameter and its description.

Table 4-4 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 4.1.3, "Managing the C/C++ Data Structures".

4.1.6 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 synchronize—that is, before the next invocation of the ocDoSynchronize method—a selective sync occurs.

Note:

Automatic synchronization is based on a different model than manual synchronization. Automatic synchronization operates on a transactional basis. Thus, the selective sync option is not supported when you use automatic synchronization for a publication, since we are no longer concerned with synchronization of only a subset of data.

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 4-5 lists the name and description of parameters for the ocSetTableSyncFlag function.

Table 4-5 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 Lite 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 Lite 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)
    
    

4.1.7 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 4.1.5, "Managing User Settings With ocSaveUserInfo" for more information.

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

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

    Note:

    The username 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.

4.1.8 Start the Synchronization With the ocDoSynchronize Method

Starts the synchronization process.

Syntax

int ocDoSynchronize( ocEnv *env );

Table 4-6 lists the name and description of the ocDoSynchronize parameter.

Table 4-6 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.

4.1.8.1 See Progress of Synchronization with Progress Listening

If you create and set the progress callback function, then Oracle Database Lite 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 4-7 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 4-2) to the address of your callback function. Save this with the ocSaveUserInfo or ocSessionInit methods.

4.1.9 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 4-8 lists the ocSessionTerm parameter and its description.

Table 4-8 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.

4.1.10 Retrieve Synchronization Error Message with ocGetLastError

Retrieves the synchronization error message and code.

Syntax

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

Table 4-9 lists the ocGetLastError parameters.

Table 4-9 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.


4.1.11 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 6.8, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Lite 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 username 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, username 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);

4.2 Synchronization API for Java Applications

The following sections describe how you can use Java API to build your own client synchronization initiation:

4.2.1 Overview

The Java interface for Mobile Sync client-side synchronization resides in the oracle.lite.msync package.

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

The Java interface consists of two files, olite40.jar and msync_java.dll. To use the Java interface, the olite40.jar file must be included in the CLASSPATH. These files are located in the <ORACLE_HOME>\Mobile\Sdk\bin directory.

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

  • Sync Class

  • SyncException Class

  • SyncOption Class

  • SyncProgressListener Interface

4.2.2 Sync Class

This class initiates synchronization by using the provided synchronization options. The parameters for the constructor are listed in Table 4-10.

Constructors

Sync(SyncOption option)

Table 4-10 Sync Class Constructor

Parameter Description

option

Instance of the SyncOption Class. This contains all the parameters needed to perform synchronization.


Public Methods

To monitor the progress of the synchronization process, the public method SyncProgressListener adds a progress listener to the object.

SyncProgressListener add(ProgressListener listener)

The parameters for the SyncProgressListener method are described in Table 4-11.

Table 4-11 Sync Class Public Method

Parameter Description

listener

An object that implements the ProgressListener interface. The synchronization object calls the progress() function of this object to notify it of the synchronization progress.

void doSync ()

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

void abort ()

Aborts the synchronization session.


The following code demonstrates how to start a session using the default settings.

try
{
  Sync mySync = new Sync( new SyncOption());
  mySync.doSync();
}
catch ( SyncException e)
{
  System.err.println( "Sync Error:"+e.getMessage());
}

4.2.3 SyncException Class

This class signals a non-recoverable error during the synchronization process. The SyncException() class constructs a clear object. The parameters for the constructor are listed inTable 4-12:

Constructors

SyncException()

SyncException(int errorCode, string errorMessage)

Table 4-12 syncException Constructor Parameter Description

Parameter Description

errorCode

The error. Refer the Oracle Database Lite Message Reference.

errorMessage

A readable text message that provides extra information.


Public Methods

The methods for the SyncException are listed in Table 4-13.

Table 4-13 SyncExceptionClass Public Methods

Parameters Description

int getErrorCode()

Gets the error code.

String getErrorMessage

Gets the error message.


4.2.4 SyncOption Class

The SyncOption class is used to define the parameters for the synchronization process. It can either be constructed manually, or can save or load data from the user profile.

Constructors

SyncOption()
 
SyncOption
   ( String user,
     String password,
     String syncParam,
     String transportType,
     String transportParam)

The parameters for the SyncOption constructor are listed in Table 4-14:

Table 4-14 SyncOption Constructors

Parameter Description

user

A string containing the name used for authentication by the Mobile Server.

password

A string containing the user password.

syncParam

A string which defines an optional list of parameters for the synchronization session. See Section 4.2.5, "Java Interface SyncParam Settings" for more information.

transportType

A string containing the name of the transport driver. Currently, only HTTP or FILE are supported.

transportParam

A string containing all the parameters needed for the specified driver to operate. See Section 4.2.6, "Java Interface TransportParam Parameters" for more information.


Public Methods

These methods load and save the user profile. The parameters of the public methods are listed in Table 4-15:

Table 4-15 Sync Option Public Method Parameters

Parameter Description

void load(String username)

This loads the profile for the specified user name. If the user name is left null, the profile is loaded for the last user to synchronize.

void save()

This saves the settings to the profile for the active user.

void setUser(String username)

This is used to set and get the current user.

String getuser()

 

void setPassword(String password)

String getPassword()

This is used to set and get the password.

void setSyncParam(String syncParam)

string getSyncParam()

This is used to set and get the synchronization parameters.

void setTransportType(String driverName)

String getTransportType()

This is used to set and get the driver name, which defaults to HTTP. Set to FILE if using file-based synchronization.

void setTransportParam(String transportParam)

String getTransportParam()

Set and get the transport parameters.


Example 1

The following code example demonstrates how to start a synchronization session using the default settings:

SyncOption opt = new SyncOption("sam","lion","pushonly", 
           "HTTP","server=server1;proxy=www-proxy.us.oracle.com;proxyPort=80"); 
opt.save();

Example 2

The following example is of a client that creates the SyncOption class and then performs the synchronization with the doSync method.

import oracle.lite.mSync.*;
 
public class JavaSyncClient{
    String user = "SALES1";
    String password = "MANAGER";
    //Set the Sync params
    //Set syncParam to fullrefresh
    String syncParam = "";//fullrefresh;
    // Set the Transport params
    String transportType = "HTTP";
    String trasportParam = "server=localhost";
    
    /**
     * Constructor
     */
    public JavaSyncClient() throws Exception{
        //Create the SyncOption class
        SyncOption syncOpt = new SyncOption(user, password,
            syncParam, transportType, trasportParam);
        syncOpt.setSyncFlag("MYORDERS", "", (short) 0);
        //Save the options before the sync
        syncOpt.save();
        //Create the Sync class
        Sync mySync = new Sync(syncOpt);
        //Perform the synchronization
        mySync.doSync();
    }
 
    /**
     * main
     */
    public static void main(String[] args)  throws Exception {
        JavaSyncClient JavaSyncClient = new JavaSyncClient();
    }
}

4.2.5 Java Interface SyncParam Settings

The syncParam is a string that can be passed when creating the SyncOption object. It allows support parameters to be specified to the synchronization session. The string is constructed of name-and-value pairs. For example:

"name=value;name2=value2;name3=value3, ...;"

The names are not case sensitive, but the values are. The field names which can be used are listed in Table 4-16.

Table 4-16 Java Interface SyncParamSettings

Name Value/Options Description

"reset"

N/A

Clear all entries in the environment before applying any remaining settings.

"security"

SSL or AES

Use the appropriate selection to choose either SSL or AES stream encryption.

"highPriority"

String

A string parameter that forces the server to append a restricting predicate to the publication item querys where restricting predicate exists. This limits the number of records client downloads and should be used in combination with selective sync which selects only high priority snapshots.

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 Lite Troubleshooting and Tuning Guide for more information.

"pushOnly"

A boolean value which makes synchronization push only.

Use this setting to upload changes from the client to the server only, do not download. This is useful when data transfer is one way, client to server.

"noapps"

N/A

Do not download any new or updated applications. This is useful when synchronizing over slow connection or on a slow network.

"syncDirection"

"sendonly" "receiveonly"

"SendOnly" is the same as "pushonly".

"ReceiveOnly" allows no changes to be posted to the server.

"noNewPubs"

N/A

This setting prevents any new publications created since the last synchronization from being sent, and only synchronizes data from the current publications.

"tableFlag"

"enable"

The "enable" setting allows [Publication.Item] to be synchronized, "disable" prevents synchronization.

[Publication.Item]

"disable"

 

"fullrefresh"

N/A

Forces a complete refresh.

"clientDBMode"

"EMBEDDED" or "CLIENT"

If set to "EMBEDDED", access to the database is by conventional ODBC, if set to "CLIENT" access is by multi-client ODBC.


Example 1

The first example enables SSL security and disables application deployment for the current synchronization session:

"security=SSL; noapps;"

Example 2

The second example resets all previous settings, activates upload for the Dept table only:

"reset;pushOnly;tableFlag[TestApp.Emp]=disable;tableFlag[TestApp.Dept]=enable;"

4.2.6 Java Interface TransportParam Parameters

The format of the TransportParam string is used to set specific parameters using a string of name-and-value pairs, for example:

"name=value;name2=value2;name3=value3, ...;"

The names are not case sensitive, but the values are. The field names which can be used are listed in Table 4-17.

Table 4-17 TransportParam Parameters

Name Value Description

"reset"

N/A

Clear all entries in the environment before applying the rest of the settings.

"server"

server hostname

The hostname or IP address of the Mobile Server.

"proxy"

proxy server hostname

The hostname or IP address of the proxy server.

"proxyPort"

port number

The port number of the proxy server.

"cookie"

cookie string

The cookie to be used for transport.


Example

The example directs the Mobile Sync Agent to use the server at "test.oracle.com" through the proxy "proxy.oracle.com" at port 8080:

"server=test.oracle.com;proxy=proxy.oracle.com;proxyPort=8080;"

4.2.7 SyncProgressListener Service

The SyncProgressListener is an interface that allows progress updates to be trapped during synchronization.

This class initiates synchronization by using the provided synchronization options. The parameters for the method are listed in Table 4-18:

Method

void progress
 
   (int progressType, 
    int completed);

Table 4-18 SyncProgressListener Abstract Method

Parameter Description

progressType

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

completed

This is the percentage of completion for specific progressType.


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

Table 4-19 SyncProgressListener Interface Constants

Constant Name Progress Type

PT_INT

States that the synchronization engine is in the initializing stage. The current and total counts are set to 0.

PT_PREPARE_SEND

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.

PT_SEND

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

The total count equals the number of bytes to be sent, and the current count equals the byte count being sent currently.

PT_RECV

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

The total count equals the number of bytes to be received, and the current count equals the byte count being received currently.

PT_PROCESS_RECV

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

PT_COMPLETE

States that the synchronization engine has completed the synchronization process.


Note:

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

Example

This simple class implements the SyncProgressListener.

class myProgressTracker implements SyncProgressListener;
 {
  public void progress
     (int progressType, 
     int completed)
    {
      System.out.println( "Status: "+progressType+"="+ completed+"%" );
     } //progress
 }

4.2.8 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 doSynchronize 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.

Note:

Automatic synchronization is based on a different model than manual synchronization. Automatic synchronization operates on a transactional basis. Thus, the selective sync option is not supported when you use automatic synchronization for a publication, since we are no longer concerned with synchronization of only a subset of data.

Syntax

public void setSyncFlag(java.lang.String publication_name, 
          java.lang.String table_name, 
          short sync_flag) throws SyncException

Table 4-5 lists the name and description of parameters for the setSyncFlag function.

Table 4-20 setSyncFlag 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. 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 Lite 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 Lite 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 doSynchronize(), you must call setSyncFlag().


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:

    setSyncFlag(<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:

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

Alternatively, see the following code snippet on how to enable the selective sync flag for EVERY table EXCEPT the OrdersODB.TEST table.

SyncOption op = new SyncOption(user, passwd, 
                    "noNewPubs","HTTP",server.toString());
op.setSyncFlag("","",(short)1); //turn on sync flag for all the tables
op.setSyncFlag("","OrdersODB.TEST",(short)0); 
                     //turn off sync flag for OrdersODB.TEST

4.2.9 Enable File-Based Synchronization through Java 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 6.8, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Lite Administration and Deployment Guide for more details on file-based synchronization.

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

  1. Create the SyncOption class with the username and password.

  2. Specify the synchronization direction and directory and filename for the synchronization file with the setSyncProperty method of the SyncOption 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.

The following code example sets the direction, filename, username and password. 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, the Sync class is instantiated with the SyncOption settings and a synchronization is performed.

SyncOption sync_op = new SyncOption("S11U1", "manager", "", "", "");
 
op.setSyncProperty(SyncOption.SEND_FILE_PROP,"C:\\temp\\send1.bin"); 
Sync mSync = new Sync(op);
mSync.doSync();

4.3 Synchronization API for Java Applications on SQLite Mobile Clients

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

4.3.1 Overview

The Java interface for SQLite Mobile client synchronization resides in the oracle.opensync.ose package.

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 msync.jar file. To use the JNI synchronization interface, include the jsync.jar file in the CLASSPATH and msync_java.dll file in the PATH. These files are located in the <ORACLE_HOME>\Mobile\Sdk\sqlite directory.

The pure Java library for the Blackberry RIM platform is located in the <ORACLE_HOME>\Mobile\Sdk\sqlite\rim\lib directory; the pure Java library for the Android platform is located in the <ORACLE_HOME>\Mobile\Sdk\sqlite\android\lib directory.

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

  • OSESession Class

  • OSEProgressListener Interface

4.3.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.

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 4-10.

Constructors

OSESession( )

OSESession( String user )

OSESession( String user, char[] pwd)

Table 4-21 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 4-22:

Table 4-22 OSESession Class Public Method Parameters

Parameter Description

void cancelSync( )

Attempts to cancel the sync 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 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.

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 will be 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 will be changed to the new password.

void setPassword(char[] pwd)

Provide or modify the SQLite Mobile client password.

void setSyncNewPub( )

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.

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 will be 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, WinCE, Windows Mobile and Linux platfoms or in the directory specified by the SQLITE.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 saveUser()

String getUser()

The saveUser method saves user information, such as users specific information, and the last sync 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 4.3.4, "Enable Selective Synchronization" for more information.

void setProgress(OSEProgressListener p)

Set synchronization progress listener.

void sync()

Initiates a manual synchronization from within the application.


Example

The following example sets the username 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 username 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();

4.3.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 4-23:

Method

void progress (int stage, int val);

Table 4-23 OSEProgress Method Parameters

Parameter Description

stage

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

val

This is the percentage of completion for specific stage.


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

Table 4-24 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.


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
 }

4.3.4 Enable 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 4-5 lists the name and description of parameter for the selectPub method.

Table 4-25 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 Lite APIs".


4.3.5 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 4-26:

Constructors

OSEException()

OSEException(int errorCode, string errorMessage)

Table 4-26 OSEException Constructor Parameter Description

Parameter Description

errorCode

Error codes are provided within the OSEExceptionConstants class, which are listed in "Error Codes and Messages". See the Javadoc for full details.

errorMessage

A readable text message, which are listed in "Error Codes and Messages", that provides extra information.


Public Methods

The methods for the OSEException are listed in Table 4-27.

Table 4-27 OSEException Class Public Methods

Parameters Description

int getErrorCode()

Gets the error code.

String getErrorMessage

Gets the error message.


Error Codes and Messages

Table 4-28 lists the error codes and messages that can be returned in the OSEException class.

Table 4-28 OSEException Error Messages

Error Code Error Message Error number

DATABASE_NOT_FOUND

Could not find database <database_name>.

-12002

EMPTY_PASSWORD

Blank password is not allowed.

-12101

EMPTY_USER

User name cannot be blank.

-12105

ENCRYPTION_ID_MISMATCH

Sent encryption id <id> + 1 does not match received <id>.

-12030

ERR_CREDENTIALS

Failed to get credentials from the server (the current credentials are invalid or missing).

-12104

HTTP_RESPONSE

Unsuccessful HTTP response

-12035

INTERNAL_ERROR

Internal error has occured (see the cause).

-12039

INVALID_DML_TYPE

Received invalid record DML type <dml_type>.

-12005

INVALID_ENCRYPTION_TYPE

Invalid encryption type specified: <encryption_type>.

-12034

INVALID_OPCODE

Received invalid opcode <opcode>.

-12006

INVALID_PRIORITY

Invalid priority specified: <priority>.

-12047

INVALID_STRING_LENGTH

Invalid string length <number> received in opcode <opcode>.

-12103

INVALID_SYNC_DIRECTION

Invalid sync direction specified: <sync_direction>.

-12012

INVALID_TRANSPORT_TYPE

Invalid transport type specified: <transport_type>.

-12016

MISSING_DEFAULT_DATABASE

Plugin is missing default database needed to create snapshot.

-12040

OPCODE_LENGTH_UNDERRUN

<numbytes> bytes for opcode <opcode> have not been read.

-12008

OPCODE_OUT_OF_SEQUENCE

Opcode <opcode> was not expected at this time.

-12024

PASSWORD_NOT_SPECIFIED

Password is not specified and was not saved for user <username>.

-12004

PLUGIN_CLASS_INIT_FAILED

Failed to initialize plugin class <class_name>.

-12100

PLUGIN_EXCEPTION

Plugin has thrown an exception, see the cause.

-12011

PLUGIN_CLASS_NOT_FOUND

Could not find plugin class <class_name>.

-12044

PLUGIN_ID_NOT_FOUND

Could not find plugin with id <id>.

-12017

PUBLICATION_ID_MISMATCH

Publication id <id> for snapshot with id <id> does not match publication id <id> in the current transaction.

-12102

PUBLICATION_ID_NOT_FOUND

Could not find publication with id <id>.

-12043

PUBLICATION_NOT_FOUND

Could not find publication <publication_name>.

-12019

SERVER_ERROR

Server error, id = <id>.

-12038

SNAPSHOT_ID_EXISTS

Snapshot with id <id> already exists.

-12023

SNAPSHOT_ID_NOT_FOUND

Could not find snapshot with id <id>.

-12021

SYNC_CANCELED

Sync was canceled.

-12000

UNCOMPRESSED_DATA

Received erroneous uncompressed data.

-12032

UNENCRYPTED_DATA

Received erroneous unencrypted data.

-12031

UNEXPECTED_BLOB_DATA

Got a record with BLOBs for a plugin that does not support BLOBs.

-12018

UNEXPECTED_OPCODE

Expecting opcode <opcode>, received <opcode>.

-12001

USER_NOT_SPECIFIED

User is not specified and the last user was not saved.

-12003


4.4 Synchronization API for C#

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

The C# interface provides for the following functions:

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:

4.4.1 Use the OracleSync Class for Synchronization

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

Table 4-29 shows the properties you can set for initializing the environment before invoking synchronization:

Table 4-29 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

The hostname or IP address of the Mobile Server. If you want to use SSL, set the URL using the HTTPS prefix instead of the HTTP prefix.

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 Lite Troubleshooting and Tuning Guide for more information.

Option

Option

Set one or more of the appropriate sync options with an OR statement from the SyncOption enumerator. 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 4-30.

Table 4-30 OracleSync Public Methods

Method Description

void save()

This saves the username, 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 4.4.3, "Exception Handling and Reading Log Files".

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

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

int SetSyncProperty (string prop, string val)

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

  • HTTP_USER_PROP —HTTP authentication user name.

  • HTTP_PASS_PROP — HTTP authentication password.

  • USER_NAME_PROP —User context when a member is synchronizing.

  • USER_PASS_PROP —User context password, when a member is synchronizing.

  • SEND_FILE_PROP — Send file name for file based synchronization

  • RECEIVE_FILE_PROP —Receive file name for file based synchronization.

For details on file-based synchronization, see Section 4.4.6, "Enable File-Based Synchronization through C# APIs".

int GetSyncProperty (string prop, out string val)

Used to retrieve Sync 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 username, password and URL. The username 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;

4.4.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.

4.4.2.1 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.

4.4.2.2 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, username and password.

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

Alternatively, you can configure a string that contains the options listed in Table 4-31 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 4-31.

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 4-31 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 Web-to-Go application data. Synchronize with other applications.

/nopub:(publication_name)

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

/notable:(table_name)/notable:(odb_name).(table_name)

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

/onlyapp:(application_name)

Synchronize only specific Web-to-Go 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.


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

4.4.4 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:

4.4.4.1 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 4-7.

There are two parameters, as follows:

Table 4-32 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;
 }
}

4.4.4.2 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 4-33.

Table 4-33 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);

4.4.4.3 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 Figure 4-0.

Table 4-34 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.

4.4.5 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.

Note:

Automatic synchronization is based on a different model than manual synchronization. Automatic synchronization operates on a transactional basis. Thus, the selective sync option is not supported when you use automatic synchronization for a publication, since we are no longer concerned with synchronization of only a subset of data.

Syntax

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

Table 4-5 lists the name and description of parameters for the setTableSyncFlag function.

Table 4-35 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 Lite 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 Lite 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 OrdersODB.TEST table.

m_sync.SetTableSyncFlag("","",(short)1); //turn on sync flag for all the tables
m_sync.SetTableSyncFlag("","OrdersODB.TEST",(short)0); 
                     //turn off sync flag for OrdersODB.TEST

4.4.6 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 6.8, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Lite 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 username 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, username 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();

4.5 mSync/OCAPIs/mSyncCom

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