Oracle® Database Lite Developer's Guide Release 10.3 Part Number E12090-02 |
|
|
View PDF |
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:
Section 4.1, "Synchronization APIs For C or C++ Applications"
Section 4.3, "Synchronization API for Java Applications on SQLite Mobile Clients"
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:
Section 4.1.2, "Initializing the Environment With ocSessionInit"
Section 4.1.4, "Retrieving Publication Information With ocGetPublication"
Section 4.1.6, "Manage What Tables Are Synchronized With ocSetTableSyncFlag"
Section 4.1.8, "Start the Synchronization With the ocDoSynchronize Method"
Section 4.1.9, "Clear the Synchronization Environment Using ocSessionTerm"
Section 4.1.10, "Retrieve Synchronization Error Message with ocGetLastError"
Section 4.1.11, "Enable File-Based Synchronization through C or C++ APIs"
For starting synchronization, the application should perform the following:
Create, memset, and initialize the ocEnv
structure.
Invoke the ocSessionInit()
method.
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.
Optionally, you can set proxy information with the ocSetSyncOption
method or specify the synchronization type for each table with the ocSetTableSyncFlag
function.
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.
Once synchronization completes, then invoke the ocSessionTerm()
method to clear the ocEnv
data structure.
If synchronization failed, then use the ocGetLastError
function to retrieve the error message.
For an example, see the SimpleSync.cpp
sample code.
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 theocSessionInit
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 |
---|---|
|
An |
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:
Create the ocEnv
by allocating a variable the size of ocEnv
.
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.
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);
Two data structures—ocEnv Data Structure and ocTransportEnv Data Structure—are used for certain functions in the Mobile Sync API.
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 |
|
Required. |
Name of the user to authenticate. This name is limited to 28 characters, because of other parts of the product. |
password |
|
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 If set to If set to |
newPassword |
|
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 |
appRoot |
|
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 |
syncDirection |
Enum |
Optional. |
If set to 0 ( |
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 |
syncTimeLog |
Short |
Optional. |
If set to 1, log sync start time is recorded in the |
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:
|
cancel |
Short |
Caller can set to 1 on next operation. |
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;
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])
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 |
---|---|
|
Pointer to an |
|
The name of the application. |
|
The buffer where the publication name is returned. |
|
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; }
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 |
---|---|
|
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:
Note:
See Section 4.1.3.1, "ocEnv Data Structure" or Section 4.1.3.2, "ocTransportEnv Data Structure" for more information.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".
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 |
---|---|
|
Pointer to the synchronization environment. |
|
The name of the publication which is being synchronized. If the value for the |
|
This is the name of the snapshot. It is the same as the name of the |
|
If the |
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:
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.
Enable the selective sync for specific tables.
Example:
ocSetTableSyncFlag(&env, <publication_name>,<table_name>,1)
If you are using a firewall and need to configure proxy information, perform the following before you execute the ocDoSynchronize
method:
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.
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
.
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 |
---|---|
|
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.
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 |
---|---|
|
Start of the prepare stage, which collects all internal data from the database and prepares to send the data to the server. |
|
Progress in the prepare stage. |
|
Prepare stage is completed. |
|
Starting to send the data to the server. |
|
Sending the data. |
|
Completed sending the data. |
|
Starting to receive data. |
|
Receiving data from the server. |
|
Completed receiving data from the server. |
|
Starting to process received data. |
|
Processing received data. |
|
Completed processing. Synchronization is finished. |
|
Resume synchronization is restarted. |
|
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.
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 |
---|---|
|
Pointer to the environment structure returned by |
De-initializes all the structures and memory created by the ocSessionInit()
call. Users must ensure that they are always called in pairs.
Retrieves the synchronization error message and code.
Syntax
int ocGetLastError( ocEnv *env, char *buf, int buf_size);
Table 4-9 lists the ocGetLastError
parameters.
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:
Ensure that any previous settings of the File-Based Sync properties are set to NULL
.
Initialize the environment with the ocSessionInit
method.
Set the username and password for the user that is initializing the synchronization.
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);
The following sections describe how you can use Java API to build your own client synchronization initiation:
Section 4.2.8, "Manage What Tables Are Synchronized With Selective Sync"
Section 4.2.9, "Enable File-Based Synchronization through Java APIs"
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
This class initiates synchronization by using the provided synchronization options. The parameters for the constructor are listed in Table 4-10.
Sync(SyncOption
option
)
Table 4-10 Sync Class Constructor
Parameter | Description |
---|---|
|
Instance of the |
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 |
---|---|
|
An object that implements the |
|
Starts a synchronization session and blocks that thread until synchronization is complete. |
|
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()); }
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:
SyncException()
SyncException(int errorCode, string errorMessage)
Table 4-12 syncException Constructor Parameter Description
Parameter | Description |
---|---|
|
The error. Refer the Oracle Database Lite Message Reference. |
|
A readable text message that provides extra information. |
The methods for the SyncException
are listed in Table 4-13.
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.
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 |
---|---|
|
A string containing the name used for authentication by the Mobile Server. |
|
A string containing the user password. |
|
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. |
|
A string containing the name of the transport driver. Currently, only |
|
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. |
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 |
---|---|
|
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. |
|
This saves the settings to the profile for the active user. |
|
This is used to set and get the current user. |
|
|
|
This is used to set and get the password. |
|
This is used to set and get the synchronization parameters. |
|
This is used to set and get the driver name, which defaults to |
|
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(); } }
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 |
---|---|---|
|
N/A |
Clear all entries in the environment before applying any remaining settings. |
|
|
Use the appropriate selection to choose either SSL or AES stream encryption. |
|
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. |
|
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. |
|
N/A |
Do not download any new or updated applications. This is useful when synchronizing over slow connection or on a slow network. |
|
|
"SendOnly" is the same as "pushonly". "ReceiveOnly" allows no changes to be posted to the server. |
" |
N/A |
This setting prevents any new publications created since the last synchronization from being sent, and only synchronizes data from the current publications. |
|
|
The "enable" setting allows [Publication.Item] to be synchronized, "disable" prevents synchronization. |
|
|
|
|
N/A |
Forces a complete refresh. |
|
|
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;"
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 |
---|---|---|
|
N/A |
Clear all entries in the environment before applying the rest of the settings. |
|
server hostname |
The hostname or IP address of the Mobile Server. |
|
proxy server hostname |
The hostname or IP address of the proxy server. |
|
port number |
The port number of the proxy server. |
|
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;"
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:
void progress (int progressType, int completed);
Table 4-18 SyncProgressListener Abstract Method
Parameter | Description |
---|---|
|
This is set to one of the constants listed in Table 4-19. |
|
This is the percentage of completion for specific |
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 |
---|---|
|
States that the synchronization engine is in the initializing stage. The current and total counts are set to 0. |
|
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. |
|
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. |
|
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. |
|
States that the synchronization engine is applying the newly received data from the server to the local data stores. |
|
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.This simple class implements the SyncProgressListener
.
class myProgressTracker implements SyncProgressListener; { public void progress (int progressType, int completed) { System.out.println( "Status: "+progressType+"="+ completed+"%" ); } //progress }
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 |
---|---|
|
The name of the publication which is being synchronized. If the value for the |
|
This is the name of the snapshot. It is the same as the name of the |
|
If the |
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:
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.
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
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:
Create the SyncOption
class with the username and password.
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();
The following sections describe how you can use Java APIs to build your own client synchronization initiation on SQLite Mobile clients:
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
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.
OSESession( ) OSESession( String user ) OSESession( String user, char[] pwd)
Table 4-21 OSESession Class Constructor
Parameter | Description |
---|---|
|
A string containing the name used for authentication by the Mobile Server. |
|
A character array containing the user password. |
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 |
---|---|
|
Attempts to cancel the sync process with a non-blocking call. If successful, throws |
|
Closes any active database connections that the session maintains. This method is called before application exits. |
|
Sets or retrieves the current root directory, as set in the |
|
Sets or retrieves the current encryption type. Possible types can are as follows:
|
|
Set to wipe out all of the client data and replace it with server data, if true. Retrieves value of force refresh. |
|
This is used to set and get the flag for persistently saving the user password. If true, the password will be saved. |
|
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. |
|
Provide or modify the SQLite Mobile client password. |
|
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. |
|
Sets or retrieves the HTTP URL of the Mobile Server. |
|
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 Note: streaming requires that the underlying client transport stack implements HTTP 1.1. Thus, if a platform does not support streaming, |
|
The The |
|
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. |
|
Set synchronization progress listener. |
|
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();
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:
void progress (int stage, int val);
Table 4-23 OSEProgress Method Parameters
Parameter | Description |
---|---|
|
This is set to one of the constants listed in Table 4-24. |
|
This is the percentage of completion for specific |
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 |
---|---|
|
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. |
|
States that the synchronization engine is sending data to the network. |
|
States that the synchronization engine is receiving data from the server. |
|
States that the synchronization engine is applying the newly received data from the server to the local data stores. |
|
States that the synchronization engine has completed the synchronization process. |
This simple class implements the OSEProgressListener
.
class myProgressTracker implements OSEProgressListener; { public void progress (int state, int val) { System.out.println( "Status: "+state+"="+ val+"%" ); } //progress }
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 |
---|---|
|
The name of the publication which is being synchronized. If the value for the For more information, see Section 2.4, "Creating Publications Using Oracle Database Lite APIs". |
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:
OSEException()
OSEException(int errorCode, string errorMessage)
Table 4-26 OSEException Constructor Parameter Description
Parameter | Description |
---|---|
|
Error codes are provided within the |
|
A readable text message, which are listed in "Error Codes and Messages", that provides extra information. |
The methods for the OSEException
are listed in Table 4-27.
Table 4-27 OSEException Class Public Methods
Parameters | Description |
---|---|
|
Gets the error code. |
|
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 |
-12002 |
EMPTY_PASSWORD |
Blank password is not allowed. |
-12101 |
EMPTY_USER |
User name cannot be blank. |
-12105 |
ENCRYPTION_ID_MISMATCH |
Sent encryption 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 |
-12005 |
INVALID_ENCRYPTION_TYPE |
Invalid encryption type specified: |
-12034 |
INVALID_OPCODE |
Received invalid opcode |
-12006 |
INVALID_PRIORITY |
Invalid priority specified: |
-12047 |
INVALID_STRING_LENGTH |
Invalid string length |
-12103 |
INVALID_SYNC_DIRECTION |
Invalid sync direction specified: |
-12012 |
INVALID_TRANSPORT_TYPE |
Invalid transport type specified: |
-12016 |
MISSING_DEFAULT_DATABASE |
Plugin is missing default database needed to create snapshot. |
-12040 |
OPCODE_LENGTH_UNDERRUN |
|
-12008 |
OPCODE_OUT_OF_SEQUENCE |
Opcode |
-12024 |
PASSWORD_NOT_SPECIFIED |
Password is not specified and was not saved for user |
-12004 |
PLUGIN_CLASS_INIT_FAILED |
Failed to initialize plugin class |
-12100 |
PLUGIN_EXCEPTION |
Plugin has thrown an exception, see the cause. |
-12011 |
PLUGIN_CLASS_NOT_FOUND |
Could not find plugin class |
-12044 |
PLUGIN_ID_NOT_FOUND |
Could not find plugin with id |
-12017 |
PUBLICATION_ID_MISMATCH |
Publication id |
-12102 |
PUBLICATION_ID_NOT_FOUND |
Could not find publication with id |
-12043 |
PUBLICATION_NOT_FOUND |
Could not find publication |
-12019 |
SERVER_ERROR |
Server error, id = |
-12038 |
SNAPSHOT_ID_EXISTS |
Snapshot with id |
-12023 |
SNAPSHOT_ID_NOT_FOUND |
Could not find snapshot with 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 |
-12001 |
USER_NOT_SPECIFIED |
User is not specified and the last user was not saved. |
-12003 |
The 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:
Section 4.4.1, "Use the OracleSync Class for Synchronization"
Section 4.4.4, "Monitor Synchronization Progress With the SyncEventHandler"
Section 4.4.5, "Manage What Tables Are Synchronized With Selective Sync"
Section 4.4.6, "Enable File-Based Synchronization through C# APIs"
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 |
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
|
Secure |
Boolean |
Should not be used. To use an SSL connection, prefix the ServerURL property with |
The synchronization public methods of the OracleSync
class are described in Table 4-30.
Table 4-30 OracleSync Public Methods
Method | Description |
---|---|
|
This saves the username, password, URL, proxy, and proxy-port settings for the |
|
Starts a synchronization session and blocks that thread until synchronization is complete. |
|
Closes and performs clean-up for the synchronization session. |
|
Set cancel during any synchronization. The synchronization returns. |
|
Used to retrieve the error log filename. For details, see Section 4.4.3, "Exception Handling and Reading Log Files". |
|
Used for setting selective sync. For details, see Section 4.4.5, "Manage What Tables Are Synchronized With Selective Sync". |
|
Used to set Sync properties. The types of Sync properties that you can set are as follows:
For details on file-based synchronization, see Section 4.4.6, "Enable File-Based Synchronization through C# APIs". |
|
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:
Instantiate the OracleSync
object.
Set relevant properties, such as username, password and URL. The username and password are limited to 28 characters each.
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()
Perform the synchronization with the Synchronize
method. The format of the Synchronize
method is as follows:
void Synchronize()
Note:
ADataException
is thrown if synchronization fails. Also, you must close all database connections before doing a synchronization.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;
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.
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.
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 |
---|---|
|
Automatically synchronize to the specified server. |
|
Automatically synchronize to saved preferred server. |
|
Save user info and exit. |
|
Connect by specific proxy server and port. |
|
Synchronize with SSL encryption. |
|
Force refresh. |
|
Do not synchronize specific Web-to-Go application data. Synchronize with other applications. |
|
Do not synchronize specific publication data. Synchronize with other publications. |
|
Do not synchronize specific table data. Synchronize with other tables. |
|
Synchronize only specific Web-to-Go application data. Do not synchronize with other applications. |
|
Synchronize only specific publication data. Do not synchronize with other publications. |
|
Synchronize only specific table data. Do not synchronize with other tables. |
|
Enable high priority data synchronization. |
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();
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:
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:
|
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; } }
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 |
boolean add |
This boolean, if true, registers the |
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);
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 |
---|---|
|
The |
|
The |
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.
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 |
---|---|
|
The name of the publication which is being synchronized. If the value for the |
|
This is the name of the snapshot. It is the same as the name of the |
|
If the |
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:
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.
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
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:
Instantiate the OracleSync
class and set the username and password.
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 theGetSyncProperty
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();
For more information, refer to the Oracle Database Lite API Specification.