The following sections describe the mobile client synchronization APIs available to manage both manual and automatic synchronization programmatically within your application on the mobile client:
Section 4.1, "Invoke Manual Synchronization on the Mobile Client"
Section 4.2, "Manage Automatic Synchronization on the Mobile Client"
You can modify the client-side application to start the synchronization programmatically. This section describes how to perform the synchronization upload and download phases for the client using the Synchronization APIs.
Note:
Currently, there are no APIs to perform the upload activity on UNIX platforms.To execute the upload portion of synchronization from the client from within your client application, perform the following steps:
Initialize the synchronization parameters.
Set up the transport parameters.
Initialize the synchronization options and environment, such as user name, password, and selective synchronization.
Perform the synchronization.
Use the following APIs for invoking manual synchronization on your mobile clients:
Section 4.1.1, "OSE Synchronization API for Applications on Mobile Clients"
Section 4.1.2, "SQLite Synchronization API for .Net Clients"
Section 4.1.3, "OCAPI Synchronization API for the Mobile Client"
OSE synchronization interfaces are available for pure Java clients, native clients and .Net clients. The following sections provide more details:
Note:
Use the OSE classes for all new application development for your mobile clients. These are the classes that will be supported for the future.The following sections describe how you can use the OSE Java APIs to build your own client synchronization initiation on mobile clients:
Note:
For more details on these classes, refer to the Oracle Database Mobile Server JavaDoc.Section 4.1.1.1.5, "Custom Transport with the OSETransport Class"
Section 4.1.1.1.6, "Sequences Emulated for SQLite Mobile Clients in Replicated Environment"
The Java interface for mobile client synchronization resides in the oracle.opensync.ose
package. The OSE Sync interface is included in the osync_se.jar
for the pure Java client.
The Java interface provides for the following functions:
Setting client-side user profiles containing data such as user name, password, and server
Starting the synchronization process
Tracking the progress of the synchronization process
For Win32, Windows Mobile, and Linux clients, the Java interface is implemented using JNI and consists of two files: jsync.jar
and msync_java.dll
. The pure Java interface is implemented in the 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
. For both mobile clients, common binaries, including these files, are located in the <
ORACLE_HOME>\Mobile\Sdk\sqlite directory. Files specific to each client can be in <
ORACLE_HOME>\Mobile\Sdk\bdb and <
ORACLE_HOME>\Mobile\Sdk\sqlite respectively.
The pure Java library for the Blackberry RIM platform is located in the <ORACLE_HOME
>\Mobile\Sdk\<mobile_client>
\rim\lib
directory; the pure Java library for the Android platform is located in the <
ORACLE_HOME>\Mobile\Sdk\<mobile_client>
\android\lib
directory, where <mobile_client>
is either bdb
or sqlite
depending on the mobile client.
The following are the classes and interface for the Java API for mobile clients:
OSESession
Class
OSEProgressListener
Interface
OSETransport
Interface
OSESession
enables setting synchronization parameters and options. This class exposes APIs to invoke and control synchronization by using the provided synchronization options.
In a multi-threaded environment, you cannot execute OSESession
methods from multiple threads. Each thread should open its own session. The only exception is cancelSync
, which can be executed by another thread.
Note:
Synchronization progress is reported through theOSEProgressListener
interface, which is set by the OSESession setProgress(OSEProgressListener)
method.The parameters for the constructor are listed in Table 4-1.
OSESession( ) OSESession( String user ) OSESession( String user, char[] pwd)
Table 4-1 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-2:
Table 4-2 OSESession Class Public Method Parameters
Parameter | Description |
---|---|
|
Attempts to cancel the synchronization 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. |
|
The The |
|
Provided the publication name, adds the publication to the list of publications to be synchronized selectively. See Section 4.1.1.1.4, "Selective Synchronization" for more information. |
|
Sets or retrieves the current root directory, as set in the |
|
Sets or returns |
|
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 mobile client password. |
|
Set synchronization progress listener. For more details, see Section 4.1.1.1.3, "OSEProgressListener Interface". |
|
Sets or returns the current HTTP proxy, which can be the hostname or IP address of the proxy server. NULL is returned if proxy is not used. |
|
Sets or retrieves a flag that indicates whether the application client updates should be downloaded during the next synchronization. If set to |
|
Sets or retrieves the current synchronization direction of data for the mobile client. You can indicate whether the client should perform normal synchronization with
This direction setting affects only user data. All mobile server data, such as awknowledgements, will still be uploaded or downloaded as appropriate. |
|
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 synchronization priority. The default is You can only use fast refresh with a high priority restricting predicate. If you use any other type of refresh, the high priority restricting predicate is ignored. See Section 1.2.10, "Priority-Based Replication" in the Oracle Database Mobile Server Troubleshooting and Tuning Guide for more information. |
|
Sets and retrieves the current transport type, which can be one of the following:
|
|
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, |
|
If |
|
Sets custom user-defined transport for synchronization, which you implement in the |
|
Initiates a manual synchronization from within the application. |
The following example sets the user name and password to JOHN/john
. The mobile server URL is identified as localhost:88
. And a synchronization is initiated with the sync
method.
/* set up user name and password */ String user = "JOHN"; String pwd = "john"; /* create OSESession with user John */ OSESession sess = new OSESession(user, pwd.toCharArray()); /* Identify Mobile Server URL */ sess.setURL("localhost:88"); /* Identify the progress listener, myProgressTracker */ sess.setProgress(myProgressTracker); /* Initiate Sync */ sess.sync();
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-3:
void progress (int stage, int val);
Table 4-3 OSEProgress Method Parameters
Parameter | Description |
---|---|
|
This is set to one of the constants listed in Table 4-4. |
|
This is the percentage of completion for specific |
The names of the constants which report the synchronization progress are listed in Table 4-4.
Table 4-4 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-5 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 Mobile Server APIs". |
You can implement a custom user-defined transport for synchronization with the OSETransport
interface. Implement the following methods to connect and disconnect the connection and to open the input and output streams. These methods are used for the transport when you provide your implementation in the setUserTransport
method in the OSESession
class.
SQLite only supports sequences in a replicated environment. Sequences partitioned per client are useful for generating unique, non-overlapping values to avoid data conflicts.
Note:
For details on using sequences in Berkeley DB, see Section 2.4.1.8, "Creating Client-Side Sequences for the Downloaded Snapshot".In order to emulate sequence behavior on SQLite, the Sync Client replicates the partitioned sequence information from the server. The mobile client applications can generate unique column values from the partitioned sequence information, which is replicated for every SQLite database in the C$SEQ_CLIENTS
table.
The C$SEQ_CLIENTS
table has the following definition:
TABLE C$SEQ_CLIENTS( "NAME" VARCHAR2(30) NOT NULL, -- sequence name "CUR_VALUE" NUMBER(10,0), -- current value, set to NULL on the first sync "MAX_VALUE" NUMBER(10,0) NOT NULL, -- max value "MIN_VALUE" NUMBER(10,0) NOT NULL, -- min value "PUB_NAME" VARCHAR2(30) NOT NULL, -- publication name (for internal use) "DB_NAME" VARCHAR2(30), -- database name (for internal use) "INCREMENT_BY" NUMBER(10,0) NOT NULL, -- increment PRIMARY KEY ("NAME"))
To select the next sequence value, users can perform the following:
Select CUR_VALUE
or MIN_VALUE
if CUR_VALUE
is NULL
.
Add INCREMENT_BY
to the CUR_VALUE
.
Update the CUR_VALUE
with the CUR_VALUE
+INCREMENT_BY
for the sequence.
Example 4-1 Emulating Sequences on the Mobile Client
The following Java code example demonstrates this functionality:
/* Advance sequence value using sequence properties replicated from the * server using C$SEQ_CLIENTS table * @param seq sequence name * @return int next sequence value * @throws DatabaseException if sequence is not found. */ int advanceSequence(String seq) throws Exception { int seqNextVal = 0; Statement statement = _db.createStatement( "SELECT ifnull((cur_value+increment_by),min_value) FROM "+SEQUENCES_TABLE+" WHERE name = ?"); statement.prepare(); statement.bind(1, seq); Cursor cursor = statement.getCursor(); if(cursor.next()) { Row row = cursor.getRow(); seqNextVal = row.getInteger(0); } else { throw new Exception("Sequence not found: " + seq); } cursor.close(); statement.close(); statement = _db.createStatement( "UPDATE "+SEQUENCES_TABLE+" SET cur_value = ifnull((cur_value+increment_by),min_value) WHERE name = ?"); statement.prepare(); statement.bind(1, seq); statement.execute(); statement.close(); return seqNextVal; }
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-7:
OSEException()
OSEException(int errorCode, string errorMessage)
Table 4-7 OSEException Constructor Parameter Description
Parameter | Description |
---|---|
|
Error codes are provided within the |
|
A readable text message that provides extra information. |
The methods for the OSEException
are listed in Table 4-8.
Table 4-8 OSEException Class Public Methods
Parameters | Description |
---|---|
|
Gets the error code. |
|
Gets the error message. |
For a complete list of the error messages that can be thrown in the OSEException
, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.
You can initiate and monitor synchronization from a native client application. The OSE synchronization methods for the native interface are defined in ose.h
, which is located in <ORACLE_HOME
>\Mobile\Sdk\include
, and implemented in ose.dll
, which is located in the <ORACLE_HOME
>\Mobile\Sdk\bin
directory.
The following sections describe how to set up and initiate synchronization:
Section 4.1.1.2.2, "Initializing the Environment With oseOpenSession"
Section 4.1.1.2.5, "Start the Synchronization With the oseSync Method"
Section 4.1.1.2.6, "Manage What Publications Are Synchronized With oseSelectPub"
Section 4.1.1.2.7, "See Progress of Synchronization with Progress Listening"
Section 4.1.1.2.8, "Cancel a synchronization event using oseCancelSync"
Section 4.1.1.2.9, "Close the Synchronization Environment Using oseCloseSession"
Section 4.1.1.2.10, "Retrieve Synchronization Error Information with oseGetLastError"
Section 4.1.1.2.11, "Enable File-Based Synchronization through Native APIs"
For starting synchronization, the application should perform the following:
Invoke the oseOpenSession
method to initialize the session and its environment and resources.
Set any session options. Invoke the oseSaveUser
method to preserve the last user, URL, proxy and optionally the user password for future synchronization events.
Invoke oseSync
method to synchronize, which returns after the synchronization completes, an error occurs, or the user interrupts the process.
Synchronization progress is reported through the oseProgressFunc
interface, which is set by the oseSetProgress
method.
If synchronization failed, use the oseGetLastError
method to retrieve the error message.
When done with the session, invoke the oseCloseSession
method to close the session and release its resources.
The oseOpenSession
method initializes the synchronization environment—which is passed to each subsequent call with the oseSess
handle.
In a multi-threaded environment, you cannot concurrently use a session from multiple threads, even with the same user. Instead, each thread should open its own session with the oseOpenSession
method. The only exception is oseCancelSync
, which can be executed by another thread.
Note:
Every time you invoke theoseOpenSession
method, you must also clean up with oseCloseSession
method. These methods should always be called in pairs. See Section 4.1.1.2.9, "Close the Synchronization Environment Using oseCloseSession" for more information.oseError oseOpenSession(const char *user, const char *pwd, oseSess *sess);
Table 4-9 lists the oseOpenSession
parameters.
Table 4-9 oseOpenSession Parameters
Name | Description |
---|---|
|
User name for synchronization. If |
|
User password. If |
|
Pointer to a session handle into which the new session is returned. This handle cannot be |
This call initializes the oseSess
synchronization environment handle—which holds context information for the synchronization engine—and restores any session options that were saved with the last oseSaveUser
method invocation. See Section 4.1.1.2.4, "Saving User Settings With oseSaveUser" for more information on oseSaveUser
.
If successful, zero is returned; otherwise, an OSE error code is returned.
You can set certain session options explicitly with the set session methods. Every session option, except OSE_OPT_NEW_PASSWORD
, is set for the duration of the session, unless it is explicitly reset with the appropriate set session option method.
When the session is created, the initial value for each option is loaded from the following:
The ose.ini
file.
If it is not set in the ose.ini
file, the option value is loaded from the saved options in the internal OSE Meta files. The OSE Meta files save session information that was either set on the previous synchronization or set explicitly with the appropriate set session option method. New values for options set by the user, such as OSE_OPT_URL
or OSE_OPT_PROXY
, are saved in the internal OSE Meta files during next synchronization.
If not set in the ose.ini
file or saved as within the OSE Meta files, the default value is taken for each option.
Options are separated into boolean, numeric, and string options:
Boolean options are those options that can only be set to OSE_TRUE
or OSE_FALSE
.
Numeric options are set to an integer value.
String options are those options that are defined with a character string.
The following sections describe the session options and the methods that can get or set the values for these options:
Boolean and Numeric Session Options
Use the oseSetNumOption
and oseGetNumOption
methods to set and get the boolean and numeric session options.
oseError oseSetNumOption(oseSess sess, int opt, long val);
Table 4-10 lists the oseSetNumOption
parameters.
Returns zero if the option is set successfully. An OSE error code is returned if an invalid option code or an invalid value is specified.
Table 4-10 oseSetNumOption Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Option code. See Table 4-12 for a list of all of the options that can bet set by this method. |
|
The option value to set for the session. See Table 4-12 for potential values for this option. |
oseError oseGetNumOption(oseSess sess, int opt, long *val);
Table 4-11 lists the oseGetNumOption
parameters.
Returns zero if the option is retrieved successfully. An OSE error code is returned if an invalid option code is specified.
Table 4-11 oseGetNumOption Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Option code. See Table 4-12 for a list of all of the options that can bet retrieved by this method. |
|
Pointer to a variable into which to return the option value. The pointer cannot be |
Table 4-12 lists all boolean and numeric synchronization options and potential values. For all boolean options, the value can only be either OSE_TRUE
and OSE_FALSE
.
Table 4-12 Numeric and Boolean Session Options
Session Option | Description |
---|---|
|
Specifies the synchronization direction with one of the following numeric constants:
|
|
Specifies the encryption type, which indicates how the data is encrypted when transfered over the network.
|
|
Transport type designates the protocol used to transfer data to and from the mobile server.
|
|
Transport direction. This is used to indicate connected or disconnected (that is, File-Based) sync.
|
|
Boolean option. Indicates whether the user synchronization password should be saved on the client, which means that it will not need to be explicitly provided for future sessions. The password is saved in an encrypted form. |
|
Boolean option. If
|
|
Synchronization priority constants:
|
|
Boolean option. Indicates whether synchronization should download a list of application and client updates that can be installed later.
Also, see the |
|
Boolean option. Indicates whether new publications can be created during synchronization.
|
|
Boolean option. Indicates if the synchronization is force-refresh. Ignores client changes and reloads all client data from the mobile server.
|
|
Boolean option. Indicates whether files are used to temporarily store the data either before it is sent or after it is received. If enabled, client changes are first saved into a file named The related Also, see the |
|
Boolean option. Indicates whether the resume protocol should be used on top of the synchronization transport. To use this option, the The resume protocol is typically used for lengthy synchronization sessions over unstable network connections. It resumes sending and receiving data from the point of a network disconnect, thus avoiding the restart of synchronization from scratch. This option is used only with connected transport (
Related |
|
Boolean read-only option. You can only retrieve the value with the Also, see the |
|
Boolean option. Indicates whether any databases newly created during synchronization should be encrypted. The encryption key for each database is either retrieved from the synchronization keystore or generated based on the user password, if not found in the keystore. Applications can define their own keys for each database before database creation with the keystore APIs.
The related You can set, get, and remove the encryption key with the |
Use the oseSetStrOption
and oseGetStrOption
methods to set and get the string session options. Every string option, except the OSE_OPT_APP_ROOT
option, defaults to NULL
if not loaded during session initialization.
oseError oseSetStrOption(oseSess sess, int opt, const char *val);
Table 4-13 lists the oseSetStrOption
parameters.
Returns zero if the option is set successfully. An OSE error code is returned if an invalid option code or an invalid value is specified.
Table 4-13 oseSetStrOption Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Option code. See Table 4-15 for a list of all of the options that can bet set by this method. |
|
The option value to set for the session. See Table 4-15 for potential values for this option. |
oseGetStrOption and oseGetStrOptionNC
oseError oseGetStrOption(oseSess sess, int opt, char *val, int bufSize); oseError oseGetStrOptionNC(oseSess sess, int opt, const char **val);
The difference between the two calls is that the oseGetStrOptionNC
does not require you to allocate the buffer for the returned string. Instead, a pointer to a string is passed. The string is NULL
-terminated, which is how the length is known.
Table 4-14 lists the oseGetStrOption
parameters.
Returns zero if the option is set successfully. OSE_ERR_INVALID_STR_OPT
error is returned if an invalid option code is specified. OSE_ERR_INVALID_BUFFER
error is returned if the buffer provided is too small to store the value and the terminating NULL
character.
Table 4-14 oseGetStrOption Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Option code. See Table 4-15 for a list of all of the options that can bet retrieved by this method. |
|
For |
|
For |
|
Size of the buffer. |
Table 4-15 lists all string session options and potential values.
Table 4-15 Session String Options
Option | Option Description |
---|---|
|
Mobile server URL. |
|
HTTP proxy, if present, as |
|
New password provided to modify the synchronization password during the next synchronization. This option needs to be set each time the password needs to be changed for the session. |
|
Read-only option, used to retrieve the synchronization user name. |
|
Used to set the synchronization password in the current session. This overwrites the password that was originally provided to the This password is saved in the OSE Meta files if the |
|
Root directory for internal synchronization files. By default, it is the synchronization client installation |
|
File URL used for a file-based sync. Specifies the path to the file, which can optionally prefixed by |
The oseSaveUser
method saves the last user, URL, proxy and optionally the user password for future synchronization events into an OSE Meta file. However, the password is saved only if the OSE_OPT_SAVE_PASSWORD
option is enabled. These settings are normally saved at the end of each synchronization, if changes are detected. These settings can be used for the current session or used by the oseOpenSession
method to initialize the environment when next invoked.
Returns zero if successful and OSE_ERR_INTERNAL_ERROR
if an input/output error occured during saving.
oseError oseSaveUser(oseSess sess);
Table 4-16 lists the oseSaveUser
parameters.
Returns zero if successful. Returns the OSE_ERR_INTERNAL_ERROR
error if an input/output error occurs when saving the settings.
Table 4-16 oseSaveUser Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
This saves or overwrites the user settings into an OSE Meta file on the client side.
Note:
See Section 4.1.1.2.3, "Setting Session Options" for details on the user settings saved.Starts the synchronization process synchronously.
Returns zero if synchronization is successful. Returns OSE_ERR_INVALID_SESS
if session handle was invalid and OSE_ERR_SYNC_CANCELED
if synchronization was canceled from another thread by the oseCancelSync
method. Other OSE error codes are returned if the synchronization fails.
oseError oseSync(oseSess sess);
Table 4-17 lists the oseSync
parameters.
Selective sync allows only certain publications to be synchronized. The oseSelectPub
method selects a publication for selective sync, which specifies if it is to be synchronized on the next synchronization. Selective sync only works if you have first performed at least one synchronization for the client. Then, a selective sync for the publication occurs at the next invocation of the oseSync
method.
The application can select publications needed by repeatedly calling the oseSelectPub
method. To revert to the regular (non-selective) synchronization selection, invoke this method with NULL
as the publication name.
The default setting is for all publications to be synchronized.
oseError oseSelectPub(oseSess sess, const char *pub);
Table 4-18 lists the oseSelectPub
parameters.
Returns zero if successful. Returns the OSE_ERR_PUB_NOT_FOUND
error if the publication with the provided name was not found.
Table 4-18 oseSelectPub Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Publication name to select for the next synchronization. |
You can implement a progress callback function that is called so that you can be notified of the progress of the synchronization operations. If you create and set the progress callback method, the mobile client invokes this callback method at appropriate times while the oseSync
method is executing.
The following is the declaration of the progress callback function.
oseError (* oseProgressFunc)(void *ctx, int stage, int val);
When the oseOpenSession
invokes the method you declare in oseSetProgress
, it provides the following information as input to your method:
ctx
—A pointer to user-defined state information for the callback. This handle is a pointer to a user-defined structure. Since the oseProgressFunc
callback method is user-implemented, it should know how to process the user-defined structure. The user context structure may or may not be initialized by the application before calling the oseSetProgress
method.
stage
—The stage in the synchronization process, which is one of the following values, where these values are defined in ose.h
:
Table 4-19 Description of the Stage Values
Stage Value | Value | Description |
---|---|---|
|
0 |
No synchronization occuring. |
|
1 |
Preparing data into temporary files. This state only occurs if the |
|
2 |
Sending the data to the mobile server. |
|
3 |
Receiving data from the mobile server. |
|
4 |
Processing data from temporary file. This state only occurs if the |
val
—The percentage completed in the particular stage that synchronization is in from 0 to 100.
After you define the progress callback function, you can initialize it with the mobile client by executing the oseSetProgress
method:
oseError oseSetProgress(oseSess sess, void *ctx, oseProgressFunc pf);
You can unregister the progress callback function by executing oseSetProgress
method as follows:
oseSetProgress(oseSess, NULL, NULL);
Table 4-20 lists the oseSetProgress
parameters.
Table 4-20 oseSetProgress Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
A pointer to the session environment settings. This handle is a pointer to a user-defined structure. Since the |
|
The progress callback function. |
Cancels the synchronization operation from another thread and returns immediately without waiting for the synchronization operation to abort.
oseError oseCancelSync(oseSess sess);
Table 4-21 lists the oseCancelSync
parameters.
Returns zero, if successful. Returns OSE_ERR_INVALID_SESS
if the oseSess
session handle is invalid.
Clears and performs a cleanup of the synchronization environment and resources. This function must be invoked for every oseOpenSession
, even if oseSync
has not been executed even once.
Returns zero, if successful. Returns OSE_ERR_INVALID_SESS
if the oseSess
session handle is invalid.
oseError oseCloseSession(oseSess sess);
Table 4-22 lists the oseCloseSession
parameters.
Retrieves the extended synchronization error message and code from the last call. This information contains the last OSE error info as well as any internal errors that caused the error.
oseError oseGetLastError(oseSess sess, const oseErrorDesc **errDesc);
Table 4-23 lists the oseGetLastError
parameters.
Returns zero if successful. Returns the OSE_ERR_INVALID_SESS
error if the session handle was invalid. Returns the OSE_ERR_INTERNAL_ERROR
error if a system error has occured.
Table 4-23 oseGetLastError Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. This handle can be |
|
A pointer to an |
The oseErrorDesc
structure is defined as follows:
typedef struct _oseErrorDesc { oseError code; /* error code */ const char *type; /* a string describing the type of error */ const char *msg; /* error message */ struct _oseErrorDesc *cause; /* underlying cause, if present */ } oseErrorDesc;
If the error has an underlying cause, the oseErrorDesc.cause
points to another oseErrorDesc
structure, which in turn can have its own cause, and so on. This is useful if the OSE call returns an OSE_ERR_INTERNAL_ERROR
, which can be further defined within another oseErrorDesc
structure. If the cause is not present, oseErrorDesc.cause
is NULL
.
Note:
The memory foroseErrorDesc
structure is allocated within the mobile client and should not be freed by the application.When you want to use file-based synchronization, you must enable file-based synchronization. Once enabled, then when you initiate manual synchronization, then the synchronization file is created. See Section 5.10, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Mobile Server Administration and Deployment Guide for more details on file-based synchronization.
To enable file-based synchronization programmatically, perform the following:
Ensure that any previous settings of the File-Based Sync properties are set to NULL
.
Initialize the session with the oseOpenSession
method providing the user name and password for the user that is initializing the synchronization.
Specify File-Based Sync by setting OSE_OPT_TRANSPORT_TYPE
to OSE_TR_TYPE_FILE
.
Specify the synchronization direction in the OSE_OPT_TRANSPORT_DIRECTION
option as follows:
OSE_TR_DIR_SEND
: Send, which creates the synchronization file.
OSE_TR_DIR_RECEIVE
: Receive, which takes in a file from the mobile server.
Set the OSE_OPT_FILE_URL
to the path and filename of the file.
If sending, the path and filename is where the mobile client saves the uploaded data for the mobile server. This file is created with the mobile client transactions destined for the mobile server.
If receiving, the path and filename where the data file that was received from the mobile server. This file is loaded and processed within the mobile client.
Provides a database connection handle from the application to use in the OSE engine, instead of the OSE engine opening its own database connection, which is the default. The connection handle is set for the duration of the session unless explicitly unset by the same call with a NULL
connection handle value.
Applications can keep open cursors while invoking synchronization. If the connection is not shared, the OSE engine needs to create its own connection and start a new exclusive transaction; however, SQLite does not support creating exclusive transactions when another connection has open cursors.
oseError oseShareConnection(oseSess sess, const char *db, void *connHdl);
Table 4-24 lists the oseShareConnection
parameters.
Returns zero, if successful. Returns OSE_ERR_PLUGIN_ERROR
if a plugin error has occured, the value of which can be retrieved with the oseGetLastError
method.
Table 4-24 oseShareConnection Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Database name for which the connection handle is provided. |
|
Valid database connection handle for a particular type of database that is used in the OSE plugin. For example, for SQLite and Berkeley DB, the connection handle should be of type |
An application can provide its own custom key to encrypt each database instead of using a key generated from the synchronization password. Subsequently, the key in the key store is used by the mobile client to open the database after it is created.
The oseSetDBKey
method sets a database encryption key provided by the application in the OSE key store for the database. Applications need to re-execute this call when they re-encrypt the database with a different key, so that OSE engine has the current key to access the database during synchronization.
For more details, see the description for the OSE_OPT_ENCRYPT_DATABASES
option in Table 4-12.
oseError oseSetDBKey(oseSess sess, const char *db, const void *key, oseSize keyLen);
Table 4-25 lists the oseSetDBKey
parameters.
Returns zero, if successful. Returns the OSE_ERR_INTERNAL_ERROR
error if the internal error occured in the key store.
Table 4-25 oseSetDBKey Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Database name for which to set the key. |
|
Buffer with the provided key. |
|
Length of the provided key. |
The oseGetDBKey
method retrieves the database encryption key from the OSE key store. For more details, see the description for the OSE_OPT_ENCRYPT_DATABASES
option in Table 4-12.
oseError oseGetDBKey(oseSess sess, const char *db, void *buf, oseSize bufSize, oseSize *retLen);
Table 4-26 lists the oseGetDBKey
parameters.
Returns zero, if successful. Returns the OSE_ERR_INVALID_BUFFER
error if the buffer was too small to store the key. Returns the OSE_ERR_INTERNAL_ERROR
error if the internal error occured in the key store.
Table 4-26 oseGetDBKey Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Database name for which to retrieve the key. |
|
Buffer to store the key. |
|
Size of the buffer that stores the key. |
|
Actual length of the key. The length will be zero if the key is not found. |
The oseRemoveDBKey
method removes the database encryption key from the OSE key store. For more details, see the description for the OSE_OPT_ENCRYPT_DATABASES
option in Table 4-12.
oseError oseRemoveDBKey(oseSess sess, const char *db);
Table 4-27 lists the oseRemoveDBKey
parameters.
Returns zero, if successful. Returns the OSE_ERR_INTERNAL_ERROR
error if the internal error occured in the key store.
The following sections describe how you can use the OSE .Net Synchronization APIs to build your own client synchronization initiation on mobile clients:
Note:
For more details on these classes, refer to the Oracle Database Mobile Server .Net API.The .Net interface for mobile client synchronization resides in the Oracle.OpenSync.OSE
namespace and is implemented in Oracle.OpenSync.dll
.
The .Net interface provides for the following functions:
Setting client-side user profiles containing data.
Starting the synchronization process.
Tracking the progress of the synchronization process.
Table 4-28 lists all enumerations and values that can be used by OSESession
APIs.
Enumeration | Members |
---|---|
Specifies the synchronization direction as follows:
|
|
Specifies the encryption type, which indicates how the data is encrypted when transfered over the network.
|
|
Transport type designates the protocol used to transfer data to and from the mobile server.
|
|
Synchronization priority:
|
|
Synchronization stage:
|
OSESession
enables setting synchronization parameters and options. This class exposes APIs to invoke and control synchronization by using the provided synchronization options.
In a multi-threaded environment, you cannot execute OSESession
methods from multiple threads. Each thread should open its own session. The only exception is CancelSync
, which can be executed by another thread.
The parameters for the constructor are listed in Table 4-29.
OSESession( ) OSESession( String user ) OSESession( String user, char[] pwd)
Table 4-29 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-30:
Table 4-30 OSESession Class Public Method Parameters
Parameter | Description |
---|---|
|
Attempts to cancel the synchronization process with a non-blocking call. |
|
Closes any active database connections that the session maintains. This method is called before application exits. |
|
The |
|
The The See Section 4.1.1.3.6, "Selective Synchronization" for more information. |
|
Set synchronization progress listener with the |
|
Initiates a manual synchronization from within the application. |
|
Provides database connection handle from the application to use in the OSE engine, instead of engine opening its own database connection, which is default. The connection handle is set for the duration of the session unless explicitly unset by calling Parameters include the database name and a connection handle, which has to be a valid native handle for the particular type of database that is used in the OSE plugin. For example, SQLIte and Berkeley DB handle should be of native type |
The following documents the properties for the OSESession
class.
Read-write properties read or write the value of a field with get
and set
accessors.
Read-only properties read the value of a field with the get
accessor.
Write-only properties set the value of a field with the set
accessor.
Boolean properties get or set the value of a field to either true or false.
Table 4-31 lists all properties. Table 4-28 lists all enumerations.
Table 4-31 OSESession Properties
Property | Accessors | Description |
---|---|---|
|
Read-write |
Gets or sets the synchronization direction on the |
|
Read-write |
Gets or sets the encryption type on the |
|
Read-write |
Gets or sets the transport type on the |
|
Read-write |
Gets or sets the synchronization priority on the |
|
Read-write |
Boolean property. The default is The password is saved in an encrypted form. |
|
Read-write |
Boolean property. Indicates whether the next synchronization should be an automatic synchronization. The default is |
|
Read-write |
Boolean property. Indicates whether synchronization should download a list of application and client updates that can be installed later. The default is |
|
Read-write |
Boolean property. Indicates whether new publications can be created during synchronization. The default is |
|
Read-write |
Boolean property. Indicates if the synchronization is force-refresh. Ignores client changes and reloads all client data from the mobile server. The default is |
|
Read-write |
Boolean property. Indicates whether files are used to temporarily store the data either before it is sent or after it is received. If enabled, client changes are first saved into a file named The related |
|
Read-write |
Boolean property. Indicates whether the resume protocol should be used on top of the synchronization transport. To use this option, the The resume protocol is typically used for lengthy synchronization sessions over unstable network connections. It resumes sending and receiving data from the point of a network disconnect, thus avoiding the restart of synchronization from scratch. This property is used only with connected transport ( The default is Related |
|
Read-write |
Mobile server URL property. |
|
Read-write |
HTTP proxy property, if present, as |
|
Write-only |
New password provided to modify the synchronization password during the next synchronization. This option needs to be set each time the password needs to be changed for the session. |
|
Read-only |
Read-only property, used to retrieve the synchronization user name. |
|
Write-only |
Used to set the synchronization password in the current session. This overwrites the password that was originally provided to the This password is saved in the OSE Meta files if the |
|
Read-write |
Root directory for internal synchronization files. By default, it is the synchronization client installation |
/* Create the OSESession object */ oseSess = new OSESession(user, pwd != NULL ? pwd.ToCharArray() : NULL); /* Assign Session options */ if (url != NULL) oseSess.URL = url; if (f) oseSess.UseFiles = true; if (sp) oseSess.SavePassword = true; if (bResume) oseSess.UseResume = true; if (ne) oseSess.EncryptionType = EncryptionType.None; else if (ssl) oseSess.EncryptionType = EncryptionType.SSL; /* Save the session options */ if (!ns) oseSess.SaveUser(); /* Assign a progress handler named syncProgress */ oseSess.SyncProgress += new OSEProgressHandler(syncProgress); /* Perform the synchronization */ oseSess.Sync();
The following documents the properties for the OSEProgressEventArgs
class, which are used primarily in the OSEProgressHandler
interface.
Read-write properties read or write the value of a field with get
and set
accessors.
Read-only properties read the value of a field with the get
accessor.
Write-only properties set the value of a field with the set
accessor.
Table 4-32 lists all properties.
The OSEProgressHandler
interface enables progress updates to be trapped during synchronization.
Sync calls the a registered progress handler to report the current stage and the percent of completion of that stage, which can be retrieve with the Stage
and Value
properties, as described in Table 4-31.
public delegate void OSEProgressHandler(object sender, OSEProgressEventArgs args);
Table 4-33 OSEProgressHandler Parameters
Name | Description |
---|---|
|
Sender of the event, which is set to the |
|
Progress event arguments that include |
You can implement your own progress handler by providing the same parameter declaration as in the OSEProgressHandler
declaration. The following implements a progress handler called syncProgress
, which takes in a sender and an OSEProgressEventArgs
structure. It evaluates the Stage
and the Value
of the OSEProgressEventArgs
structure when invoked by the Sync Agent.
static void syncProgress(object sender, OSEProgressEventArgs args) { if (args.Stage == SyncProgressStage.Idle) return; if (prevVal == -1) { Console.Write(args.Stage); prevVal = 0; } int dots = (args.Value - prevVal) / 2; for(int i = 0; i < dots; i++) Console.Write('.'); if (args.Value == 100) { Console.WriteLine(); prevVal = -1; } else prevVal = args.Value; }
Then, you set the progress handler by setting the SyncProgress
event, as shown below:
oseSess.SyncProgress += new OSEProgressHandler(syncProgress);
Selective sync specifies whether a publication should be synchronized or not for the next session. Provide the name of the publication with the SelectPub
method to indicate whether the publication is to be synchronized on the next execution of the Sync
method. The default setting is NULL
for all publications.
Note:
Automatic synchronization selectively synchronizes only publications that contain automatic publication items.Table 4-34 lists the name and description of parameter for the SelectPub
method.
Table 4-34 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 Mobile Server APIs". |
This class signals an error during the synchronization process.
The OSEException
read-only properties are listed in Table 4-35.
Table 4-35 OSEException Properties
Parameters | Description |
---|---|
|
Gets the exception error code. The error code can be one of the |
|
Gets the exception type name. |
|
Use the |
OSEException(int errorCode)
OSEException(int errorCode, string errorMessage)
Table 4-36 OSEException Parameter Description
Parameter | Description |
---|---|
|
The error code can be one of the |
|
A readable text message that provides extra information. |
For a complete list of the error messages in the OSEException
class, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.
You can initiate and monitor synchronization from an .Net provider application. See the SQLite documentation for information on the .Net provider.
Note:
The following OCAPI synchronization APIs are currently supported for the mobile client, but are not the direction recommended for future applications. To develop applications for future support, migrate existing applications to use the Section 4.1.1, "OSE Synchronization API for Applications on Mobile Clients".The following sections describe the OCAPI synchronization APIs:
You can initiate and monitor synchronization from a C or C++ client application. The OCAPI synchronization methods for the C/C++ interface are contained in ocapi.h
and ocapi.dll
, which are located in the <ORACLE_HOME
>\Mobile\bin
directory.
A C++ example is provided in the <ORACLE_HOME
>\Mobile\Sdk\Samples\sync\win32\msync\src
directory. The source code is contained in SimpleSync.cpp
. The executable—SimpleSync.exe
—is in the <ORACLE_HOME
>\Mobile\Sdk\Samples\sync\msync\bin
directory.
The following sections describe how to set up and initiate synchronization:
Section 4.1.3.1.2, "Initializing the Environment With ocSessionInit"
Section 4.1.3.1.6, "Retrieving Publication Information With ocGetPublication"
Section 4.1.3.1.7, "Managing User Settings With ocSaveUserInfo"
Section 4.1.3.1.8, "Manage What Tables Are Synchronized With ocSetTableSyncFlag"
Section 4.1.3.1.10, "Start the Synchronization With the ocDoSynchronize Method"
Section 4.1.3.1.11, "See Progress of Synchronization with Progress Listening"
Section 4.1.3.1.12, "Clear the Synchronization Environment Using ocSessionTerm"
Section 4.1.3.1.13, "Retrieve Synchronization Error Message with ocGetLastError"
Section 4.1.3.1.14, "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 user name and password. If you want to preserve all optional fields set in the ocEnv
structure for future synchronization sessions, then execute the ocSaveUserInfo
method.
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.3.1.7, "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.3.1.12, "Clear the Synchronization Environment Using ocSessionTerm" for more information.int ocSessionInit( ocEnv env );
Table 4-37 lists the ocSessioninit
parameter and its description.
Table 4-37 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 user name and password (See Section 4.1.3.1.7, "Managing User Settings With ocSaveUserInfo"). An ocEnv
structure is passed as the input parameter. Perform the following to prepare the ocEnv
variable:
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.4, "ocEnv Data Structure".
The following example allocates a new ocEnv
, which is then passed into the ocSessionInit
call.
env = new ocEnv; // Reset ocenv memset( env, 0, sizeof(ocEnv) ); // init OCAPI ocError rc = ocSessionInit(env);
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-38 lists the field name, type, usage, and corresponding description of the ocEnv
structure parameters.
Required—If the usage is required, then you either set before calling the ocSessionInit
function or you have saved these parameters previously with the ocSaveUserInfo
function.
Optional—If the usage is optional, then optionally set after calling the ocSessionInit
function and before the ocDoSynchronize
function.
Read Only.
Table 4-38 ocEnv Structure Field Parameters
Field | Type | Usage | Description |
---|---|---|---|
|
|
Required. |
Name of the user to authenticate. This name is limited to 28 characters, because of other parts of the product. |
|
|
Required. |
User password (clear text). This name is limited to 28 characters, because of other parts of the product. |
|
|
Required. |
If set to If set to If set to |
|
|
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. |
|
|
Optional. |
If set to 1, the password is saved locally and is loaded the next time |
|
|
Optional. |
Directory to where the application will be copied. If first character is NULL, then it uses the default directory. |
|
|
Optional. |
0= OFF (default) 1= ON; Only high priority table or rows are synchronized when turned on. You can only use fast refresh with a high priority restricting predicate. If you use any other type of refresh, the high priority restricting predicate is ignored. See Section 1.2.10, "Priority-Based Replication" in the Oracle Database Mobile Server Troubleshooting and Tuning Guide for more information. |
|
|
Optional. |
If set to 0, then AES is used on the transport. If set to |
|
|
Optional. |
If set to 0 ( |
|
|
Read-only. |
Extended error code - either OS or OKAPI error code. |
|
|
Transport buffer. See Section 4.1.3.1.5, "ocTransportEnv Data Structure". |
|
|
|
Optional. |
If not NULL, points to the callback for progress listening. See Section 4.1.3.1.11, "See Progress of Synchronization with Progress Listening". |
|
|
Reserved |
|
|
|
Reserved |
|
|
|
Optional. |
Can be set to anything by the caller for context information (such as progress dialog handle, renderer object pointer, and so on. |
|
|
Reserved. |
|
|
|
Reserved. |
|
|
|
Reserved (for Wireless/Nettech only). |
|
|
|
Optional. |
If set to 1, then only push changes to the server. |
|
|
Optional. |
Set to 1 (by default), performs application deployment. If set to 0, then no applications will be received from the server. |
|
|
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). |
|
|
Optional. |
Debug only. If set to 1, logs server-side insert and update row information to the publication client database. |
|
|
Optional. |
Debug only. A bitset of the following flags:
|
|
|
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 application name. The user knows only the application name, which happens when the Packaging Wizard is used to package an application before publishing it. If the application needs the publication name in order to interact with the database, then this function is used to retrieve that name, given the application name.
ocError ocGetPublication(ocEnv* env, const char* application_name, char* buf, int buf_len);
The parameters for the ocGetPublication
function are listed in Table 4-39 below.
Table 4-39 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 synchronize applicaton "Sample3" char buf[32]; rc = ocGetPublication(&env, "Sample3", buf, sizeof(buf)); rc = ocSetTableSyncFlag(&env, buf, NULL, 0); // call sync rc = ocDoSynchronize(&env); if (rc < 0) fprintf(stderr, "ocDoSynchronize failed with %d:%d\n", rc, env.exError); else printf("Synchronization compeleted\n"); // close OCAPI session rc = ocSessionTerm(&env); return 0; }
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.
int ocSaveUserInfo( ocEnv *env );
Table 4-40 lists the ocSaveUserInfo
parameter and its description.
Table 4-40 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.4, "ocEnv Data Structure" or Section 4.1.3.1.5, "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.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 synchronization—that is, on the next invocation of the ocDoSynchronize
method—a selective sync occurs.
The default sync_flag
setting for ocSetTableSyncFlag
is TRUE (1) for all the tables; that is, all tables are flagged to be synchronized. If you want to selectively synchronize specific tables, you must first disable the default setting for all tables and then enable the synchronization for only the specific tables that you want to synchronize.
ocSetTableSyncFlag(ocEnv *env, const char* publication_name, const char* table_name, short sync_flag)
Table 4-41 lists the name and description of parameters for the ocSetTableSyncFlag
function.
Table 4-41 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.3.1.7, "Managing User Settings With ocSaveUserInfo" for more information.
If required, configure the proxy user name and password. To configure the proxy user name and password, use the ocSetSyncOption
and provide the following:
ocSetSyncOption( env, "HTTPUSER=<username>;HTTPPASS=<password>");
Note:
The user name and password are limited to 28 characters.Where the ocSetSyncOption
syntax is as follows:
int ocSetSyncOption(ocEnv *env, const char *str);
You can set one or more name/value pairs searated by a semi-colon in the string. The previous example shows the HTTPUSER
and HTTPPASS
name/value pairs. You can also set the URL string as follows: URL=www.myhost.com
.
Starts the synchronization process.
int ocDoSynchronize( ocEnv *env );
Table 4-42 lists the name and description of the ocDoSynchronize
parameter.
Table 4-42 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, the mobile client invokes this callback function at different times while the ocDoSynchronize
method is executing. Create the callback function, as follows:
void myProgressProc ( void *env, int stage, int present);
When the ocDoSynchronize
invokes your myProgressProc
function, it provides the following information as input to your function:
env
—A pointer to the environment (ocEnv
structure) for the synchronization session. This provides the function to retrieve the userContext
pointer.
stage
—A number that denotes the stage in the synchronization process, which is one of the following values, where these values are defined in ocapi.h
:
Table 4-43 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-38) 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.
int ocSessionTerm( ocEnv *env );
Table 4-44 lists the ocSessionTerm
parameter and its description.
Table 4-44 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.
int ocGetLastError( ocEnv *env, char *buf, int buf_size);
Table 4-45 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 5.10, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Mobile Server Administration and Deployment Guide for more details on file-based synchronization.
To enable file-based synchronization programmatically with the ocEnv
structure, perform the following:
Ensure that any previous settings of the File-Based Sync properties are set to NULL
.
Initialize the environment with the ocSessionInit
method.
Set the user name 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, user name and password. Notice that the ocEnv
structure is memset to zero to ensure that if a previous direction and filename were specified, then these are invalidated for the next file-based synchronization. The SEND_FILE_PROP
property is set with the filename and direction, which tells the Sync Client to marshall the mobile client transactions that are to be uploaded to the mobile server into this file. If you were receiving a synchronization file from the mobile server, you would have set the RECEIVE_FILE_PROP
property with the location and name of this file.
Finally, the ocEnv
structure is provided to the ocDoSynchronize
method, which performs the file-based synchronization.
ocEnv env; memset(&env, 0, sizeof(ocEnv)); ocSessionInit(&env); strcpy(env.username, "S11U1"); strcpy(env.password, "manager"); ocSetSyncProperty(&env, SEND_FILE_PROP, "C:\\temp\\send1.bin"); ocDoSynchronize(&env); ocSessionTerm(&env);
The OCAPI C# interface for Mobile Sync client-side synchronization resides in the Oracle.DataAccess.Lite
package.
The C# interface provides for the following functions:
Setting client-side user profiles containing data such as user name, password, and server
Starting the synchronization process
Tracking the progress of the synchronization process
The C# interface is contained in the Oracle.DataAccess.Lite.dll
. The OracleSync
class, defined in the OracleSync.cs
file, contains the C# API for synchronization.
The following sections describe how to use the C# API:
Section 4.1.3.2.1, "Use the OracleSync Class for Synchronization"
Section 4.1.3.2.4, "Set the Environment and Synchronize With the OracleEngine"
Section 4.1.3.2.5, "Exception Handling and Reading Log Files"
Section 4.1.3.2.6, "Monitor Synchronization Progress With the SyncEventHandler"
Section 4.1.3.2.10, "Manage What Tables Are Synchronized With Selective Sync"
Section 4.1.3.2.11, "Enable File-Based Synchronization through C# APIs"
You use the OracleSync
class to initialize and perform synchronization using the C# APIs.
Table 4-46 shows the properties you can set for initializing the environment before invoking synchronization:
Table 4-46 OracleSync Properties
Properties | Type | Description |
---|---|---|
|
|
The name of the user who is initiating the synchronization. |
|
|
The password for the user who is initiating the synchronization. |
|
|
The hostname or IP address of the mobile server. If you want to use SSL, set the URL using the |
|
|
The hostname or IP address of the proxy server. |
|
|
The hostname or IP address of the proxy port. |
|
|
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; |
|
|
You can only use fast refresh with a high priority restricting predicate. If you use any other type of refresh, the high priority restricting predicate is ignored. See Section 1.2.10, "Priority-Based Replication" in the Oracle Database Mobile Server Troubleshooting and Tuning Guide for more information. |
|
|
Set one or more of the appropriate synchronization options with an OR statement from the
|
|
|
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-47.
Table 4-47 OracleSync Public Methods
Method | Description |
---|---|
|
This saves the user name, 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.1.3.2.5, "Exception Handling and Reading Log Files". |
|
Used for setting selective sync. For details, see Section 4.1.3.2.10, "Manage What Tables Are Synchronized With Selective Sync". |
|
Used to set Synchronization properties. The types of Synchronization properties that you can set are as follows:
|
|
Used to retrieve Synchronization property settings. See the |
To create the OracleSync
class in preparation for the synchronization, perform the following:
Instantiate the OracleSync
object.
Set relevant properties, such as user name, password and URL. The user name 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, user name and password.
OracleEngine.Synchronize("S11U1", "manager", "myserver.mydomain.com")
Alternatively, you can configure a string that contains the options listed in Table 4-48 with a single String
input parameter and synchronize, as follows:
OracleEngine.Synchronize(args)
In the above example, the String
args
input parameter is a combination of the options in Table 4-48.
String args = "S11U1/manager@myserver.mydomain.com /save /ssl /force"
Include as many of the options that you wish to enable in the String
.
Table 4-48 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 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 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-43.There are two parameters, as follows:
Table 4-49 SyncEventArgs Parameters
Parameter | Description |
---|---|
|
The stage in which the synchronization is acting on the mobile client. The possible stages are as follows:
|
|
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-50.
Table 4-50 SetEventHandler Method Parameters
Parameter | Description |
---|---|
|
The |
|
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 Table 4-51.
Table 4-51 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.
void SetTableSyncFlag (string pubName, string tableName, bool sync_flag)
Table 4-52 lists the name and description of parameters for the setTableSyncFlag
function.
Table 4-52 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 Orders.TEST
table.
m_sync.SetTableSyncFlag("","",(short)1); //turn on sync flag for all the tables m_sync.SetTableSyncFlag("","Orders.TEST",(short)0); //turn off sync flag for Orders.TEST
When you want to use file-based synchronization, you must enable file-based synchronization. Once enabled, then when synchronization occurs—either through automatic or manual synchronization—then the synchronization file is created. See Section 5.10, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Mobile Server Administration and Deployment Guide for more details on file-based synchronization.
To enable file-based synchronization programmatically with the OracleSync
class, specify the following:
Instantiate the OracleSync
class and set the user name 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, user name and password in the SetSyncProperty
method. In this example, the SEND_FILE_PROP
property is set with the filename and direction, which tells the Sync Client to marshall the mobile client transactions that are to be uploaded to the mobile server into this file. If you were receiving a synchronization file from the mobile server, you would have set the RECEIVE_FILE_PROP
property with the location and name of this file.
Finally, perform the synchronization with the Synchronize
method.
OracleSync m_sync = new OracleSync(); m_sync.UserName = "S11U1"; m_sync.Password = "manager"; m_sync.SetSyncProperty(OracleSync.SEND_FILE_PROP,"C:\\temp\\send1.bin"); m_sync.Synchronize();
For more information, refer to the Oracle Database Mobile Server API Specification.
The following APIs are used to manage automatic synchronization on the Mobile cllient:
Section 4.2.1, "OSE APIs for Managing Automatic Synchronization"
Section 4.2.2, "OCAPI APIs for Retrieving Status on Automatic Synchronization"
Section 4.2.3, "OCAPI Notification APIs for the Automatic Synchronization Cycle Status"
Note:
Use the OSE classes for all new application development for your mobile clients. These are the classes that will be supported for the future.Automatic synchronization is enabled by default if a publication is enabled for automated synchronization. However, you may programmatically turn on and off automatic synchronization on the mobile client using the Sync Control API.
Use the start or stop methods to start or stop the Sync Agent. The user may want to stop the Sync Agent for many reasons, such as aborting an automatic synchronization that may be running longer than desired, freeing up system resources, or de-fragmenting or backing up a client database.
Note:
There is also a GUI for starting, stopping the automatic synchronization process from the mobile server. See Section 5.5.2, "Start, Stop, or Get Status for Automatic Synchronization" in the Oracle Database Mobile Server Administration and Deployment Guide for more details.The following are the different methods of managing automatic synchronization and the Sync Agent:
Pause/Resume—Pause and resume all Sync Agent activities without stopping the process or freeing any resources, which would occur if you stopped or disabled the Sync Agent. Pause and resume are the most efficient method for suspending the Sync Agent and all automatic synchronization events, since it does not stop the process or free any resources.
By default, if you are using the mSync GUI to initiate a manual synchronization, the underlying code pauses and resumes the automatic synchronization for you, as described below:
Pause the automatic synchronization with the Sync Control API.
Initiate the manual synchronization with the programmatic API.
Resume the automatic synchronization with the Sync Control API. If the resume is not executed, the Sync Agent is automatically resumed when the client restarts.
Start/Stop—Stop the Sync Agent, which includes stopping the process and freeing all resources, until a start operation is executed or the client is restarted. If the start operation is not executed, the Sync Agent is automatically resumed when the client restarts.
Enable/Disable—Disabling the Sync Agent stops the Sync Agent until an enable operation is executed. Even restarting the client will not re-enable the Sync Agent. Thus, in a disabled state, no automatic synchronization events will occur.
The following control APIs can be used to manage automatic synchronization:
Section 4.2.1.1, "JAVA APIs for the Sync Agent and Automatic Synchronization"
Section 4.2.1.2, "Native APIs for the Sync Agent and Automatic Synchronization"
Section 4.2.1.3, "The .Net APIs for the Sync Agent and Automatic Synchronization"
The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:
Note:
For more details on these classes, refer to the Oracle Database Mobile Server JavaDoc.Once automatic synchronization for the mobile client is enabled, you can manage it either locally through the Sync Agent APIs or remotely through the Mobile Manager UI controls. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is paused, the Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.
The Java interface for controlling the Sync Agent and automatic synchronization resides in the oracle.opensync.syncagent
package.
The Java interface provides for the following functions:
Tracking the progress of the automatic synchronization process.
Retrieve the status of the Sync Agent.
Specify custom handlers for events that occur in automatic synchronization.
The following are the classes and interface for the Java API for controlling the Sync Agent and automatic synchronization:
BGSession
Class
BGAgentStatus
Class
BGSyncStatus
Class
BGMessageHandler
Interface
BGSession
is the main class for controlling automatic synchronization through the Sync Agent, as follows:
Start, stop, pause, resume, enable or disable automatic synchronization.
Retrieve automatic synchronization status information.
Specify message handlers for retrieving information about automatic synchronization events.
Note:
In a multi-threaded environment a singleBGSession
should not be used from multiple threads. Each thread should open its own session.BGSession( )
The public methods and their parameters for the BGSession
class are listed in Table 4-53:
Table 4-53 BGSession Class Public Method Parameters
Parameter | Description |
---|---|
|
Adds or removes a custom message handler to the Sync Agent. See Section 4.2.1.1.5, "BGMessageHandler Interface" for more information. |
|
Returns |
|
Closes the session and release all the resources used by the session. |
|
|
|
Retrieves the current Sync Agent status. See Section 4.2.1.1.3, "BGAgentStatus Object" for more details on the status information returned. |
|
Retrieves the current Sync Agent status code, which are described in Table 4-56, "Sync Agent Status Codes". |
|
Get current status of automatic synchronization managed by the Sync Agent. See Table 4-55 for more details on the status information returned. |
|
Pauses the Sync Agent. If the agent is aready paused or being paused, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be paused before returning. Use the |
|
Resumes the Sync Agent. If the agent is already resumed or resuming, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be resumed before returning. Use the |
|
Starts up the Sync Agent UI. |
|
Start the Sync Agent. If the agent is already running, starting, or resuming, this call is ignored. If the agent is paused, this call resumes the Sync Agent. This call is asynchronous and does not wait for the Sync Agent to be started before returning. Use the |
|
Stop the Sync Agent. If the agent is already stopped or stopping, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be stopped before returning. Use the |
|
Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.
Returns |
The following example demonstrates how to start the Sync Agent, retrieve status of the Sync Agent and add a message handler for the session:
// Create the BGSession object BGSession sess = new BGSession(); try { //Start the Sync Agent, which enables all automatic synchronization //events sess.start(); //Wait until the Sync Agent successfully starts sess.waitForStatus(BGAgentStatus.RUNNING); //Retrieve the status of the Sync Agent BGAgentStatus s = sess.getAgentStatus(); //Print out the user that is using automatic synchronization System.out.println("User name: " + s.clientId); //Add a message handler sess.addMessageHandler(new myMessageHandler()); ... } finally { //When finished, close the session to release all resources sess.close(); }
The BGAgentStatus
object represents the current status of the Sync Agent.
The methods for the BGAgentStatus
are listed in Table 4-54.
Table 4-54 BGAgentStatus Class Public Method
Method | Description |
---|---|
|
Get language-specific name of a given status code. When you provide one of the status codes shown in Table 4-56, the appropriate name is returned. Translation dependent on the device language settings |
BGAgentStatus
provides status information on the Sync Agent. Table 4-55 lists and describes the status information fields within the BGAgentStatus
class.
Table 4-55 BGAgentStatus Class Fields
Parameters | Description |
---|---|
|
The name of the application or process that is executing the Sync Agent. On some platforms, such as Android, it is possible to execute the Sync Agent within an application process. |
|
Remaining percentage of battery life, if relevant. |
|
Sync user name. |
|
Name of the network currently used for synchronization, evaluated by Sync Agent. |
|
Network bandwidth in bits per second. |
|
Process id of the process that is executing the Sync Agent, if relevant for a given platform. |
|
Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 4-56. |
The BGAgentStatus
object defines the Sync Agent status codes, which are as follows:
Table 4-56 Sync Agent Status Codes
Status Code | Status Name | Description |
---|---|---|
0 |
|
Sync Agent application is not running. |
1 |
|
Sync Agent is in the process of starting. |
2 |
|
Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active. |
3 |
|
Sync Agent is in the process of being paused. |
4 |
|
Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed. |
5 |
|
Sync Agent is in the process of resuming. |
6 |
|
Sync Agent is in the process of stopping. |
The following provides an example of retrieving and processing the Sync Agent status:
/* retrieve the Sync Agent status */ BGAgentStatus as = bgSess.getAgentStatus(); /* Print Sync Agent status */ System.out.println("Agent Status: " + BGAgentStatus.statusName(as.statusCode)); if (as.statusCode == BGAgentStatus.STOPPED) return; /* Identify the client id, process id and name */ System.out.println("Client ID: " + as.clientId); System.out.println("Process Name: " + as.appName); System.out.println("Process ID: " + as.processId); /* network name and speed */ if (as.networkSpeed > 0) { System.out.println("Network Name: " + as.networkName); System.out.println("Network Speed: " + as.networkSpeed + " bps"); } else System.out.println("Network is not present"); /* battery power */ if (as.batteryPower > 0) System.out.println("Battery Power: " + as.batteryPower + "%"); else System.out.println("Battery is not present");
Current status of automatic synchronization. If automatic synchronization is in progress, startTime
will have a non-zero value and endTime
will be zero.
BGSyncStatus
provides status information on automatic synchronization in the fields listed in Table 4-57.
Table 4-57 BGSyncStatus Class Fields
Parameters | Description |
---|---|
|
End time of the last synchronization in milliseconds since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronzation is currently in progress or has not yet run. |
|
Exception object thrown during the last synchronization. Returns |
|
Priority of the current or last synchronization. |
|
Progress stage of synchronization if it is in progress. |
|
Progress value in percentage of synchronization, if it is in progress. |
|
Array of names of publications synchronized currently or during last synchronization. |
|
Start time of current or last synchronization, in milliseconds, since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronization has not yet started or the last synchronization time is unknown. |
The following provides an example of retrieving and processing the synchronization status:
/* Retrieve the synchronization status */ BGSyncStatus ss = bgSess.getSyncStatus(); /* start time */ if (ss.startTime == 0) return; System.out.println("Sync Started: " + time2str(ss.startTime)); /* end time */ if (ss.endTime != 0) System.out.println("Sync Finished: " + time2str(ss.endTime)); /* number of publications synchronized */ if (ss.pubs != NULL && ss.pubs.length != 0) { System.out.print("Publications synced: "); for(int i = 0; i < ss.pubs.length; i++) { System.out.print(ss.pubs[i]); if (i == ss.pubs.length - 1) System.out.println(); else System.out.print(", "); } } /* synchronization priority */ System.out.println("Sync Priority: " + (ss.prio == OSESession.PRIO_HIGH ? "High" : "Normal")); /* synchronization result */ System.out.print("Sync Result: "); if (ss.lastError == NULL) System.out.println("Success"); else System.out.println("Failure: " + ss.lastError.toString());
The BGMessageHandler
interface enables the Sync Agent and automatic synchronization message and error data to be trapped during synchronization.
Sync calls the handleLogMessage
method with a parameter message of type LogMessage
to report the current state and any errors for the Sync Agent or automatic synchronization. Within the handleLogMessage
method, you can perform the appropriate action for the errors returned in the LogMessage
structure.
For a complete description of the LogMessage
class, see Section 4.2.1.1.6, "LogMessage Class".
This example demonstrates how to implement the BGMessageHandler
.
class myMessageHandler implements BGMessageHandler; { public void handleLogMessage(message) { private PrintStream ps = new PrintStream(new FileOutputStream(FILE_NAME, false)); ps.println("Time: " + new Date(message.time)); ps.println("Type: " + (message.type == LogMessage.INFO ? "INFO" : (message.type == LogMessage.WARNING ? "WARNING" : "ERROR"))); ps.println("Id: " + message.id); if (message.text != NULL) ps.println("Text: " + message.text); if (message.cause != NULL) ps.println("Cause: " + message.cause); } }
The LogMessage
class contains error message information passed to handlers when an event occurs within the application. It exists in the oracle.opensync.util
package.
Name | Description |
---|---|
|
For error messages, optional cause of the error, which can be If the error has an underlying cause, the |
|
Error message number. |
|
Application-specific message number. |
|
Informational message number. |
|
|
|
Name of the application that created the message. |
|
Message text. |
|
Message creation time. Number in milliseconds since the epoch. |
|
Message type: |
|
Warning message. |
The following demonstrates how to print out the error information in the LogMessage
class:
private void printMsg(PrintStream ps, LogMessage m) { ps.println("Time: " + new Date(m.time)); ps.println("Type: " + (m.type == LogMessage.INFO ? "INFO" : (m.type == LogMessage.WARNING ? "WARNING" : "ERROR"))); ps.println("Id: " + m.id); if (m.text != NULL) ps.println("Text: " + m.text); if (m.cause != NULL) ps.println("Cause: " + m.cause); ps.println();
This class signals a non-recoverable error during the synchronization process. The BGException()
class constructs a clear
object. The parameters for the constructor are listed in Table 4-7:
BGException(int errCode)
BGException(int errCode, java.lang.Object arg)
BGException(int errCode, java.lang.Object[] args, java.lang.Throwable cause)
BGException(int errCode, java.lang.Object arg1, java.lang.Object arg2)
BGException(int errCode, java.lang.Object arg1, java.lang.Object arg2, java.lang.Object arg3)
BGException(int errCode, java.lang.Object arg, java.lang.Throwable cause)
Table 4-59 BGException Constructor Parameter Description
Parameter | Description |
---|---|
|
Error codes are provided within the The message handler returns an error message. For a complete list of the error messages that can be thrown in |
|
Return variables for information within the error message. |
|
The cause of this throwable or NULL if the cause is nonexistent or unknown. |
The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:
Once automatic synchronization for the mobile client is enabled, you can manage it locally through the Sync Agent APIs and remotely through the Mobile Manager UI controls. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is paused, the Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.
The native interface for controlling the Sync Agent and automatic synchronization are defined in the <ORACLE_HOME
>\Mobile\Sdk\include\bgsync.h
file and implemented in <ORACLE_HOME
>\Mobile\Sdk\bin\bgsync.dll
.
The native interface provides for the following functions:
Start, stop, pause, resume, enable or disable automatic synchronization.
Retrieve automatic synchronization status information.
Specify message handlers for retrieving information about automatic synchronization events.
The bgOpenSession
method initializes the automatic synchronization environment—which is passed to each subsequent call with the bgSess
handle.
In a multi-threaded environment, you cannot concurrently use a session from multiple threads, even with the same user. Instead, each thread should open its own session with the bgOpenSession
method.
Note:
Every time you invoke thebgOpenSession
method, you must also clean up with bgCloseSession
method. These methods should always be called in pairs. See Section 4.2.1.2.6, "Close the Synchronization Environment" for more information.bgError bgOpenSession(bgSess *sess);
Table 4-60 lists the bgOpenSession
parameters.
Table 4-60 bgOpenSession Parameters
Name | Description |
---|---|
|
Pointer to a session handle into which the new session is returned. Returns |
This call initializes the bgSess
automatic synchronization environment handle—which holds context information for the synchronization engine.
Returns zero if successful. Returns BG_ERR_INTERNAL
if a system error has occured.
You can retrieve the status of automatic synchronization events or of the Sync Agent. The following sections describe the methods for retrieving the status:
Get the Sync Agent operational status with the bgGetAgentStatus
method.
bgError bgGetAgentStatus(bgSess sess, bgAgentStatus *s);
Table 4-61 lists the bgGetAgentStatus
parameters.
Table 4-61 bgGetAgentStatus Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Pointer to the Sync Agent status structure in which the status is returned. This pointer cannot be |
Returns zero if the agent has reached specified status. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INTERNAL
if a system error has occured.
The bgAgentStatus
structure provides status information on the Sync Agent.
typedef struct _bgAgentStatus { ose1B statusCode; oseBool isExternal; oseU2B _reserved; /**< for alignment */ const char *clientId; const char *processName; const char *networkName; ose4B processId; ose4B networkSpeed; ose4B batteryPower; } bgAgentStatus;
Table 4-62 lists and describes the status information fields.
Table 4-62 bgAgentStatus Fields
Parameters | Description |
---|---|
|
Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 4-63. |
|
A boolean value that if |
|
Sync user name. |
|
Name of the process within which the Sync Agent is currently running. |
|
Name of the network currently used for synchronization, evaluated by Sync Agent. |
|
Process id of the process that is executing the Sync Agent, if relevant for a given platform. |
|
Network bandwidth in bits per second. |
|
Remaining percentage of battery life, if relevant. |
Table 4-63 lists the Sync Agent status codes:
Table 4-63 Sync Agent Status Codes
Code | Status Name | Description |
---|---|---|
0 |
|
Sync Agent application is not running. |
1 |
|
Sync Agent is in the process of starting. |
2 |
|
Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active. |
3 |
|
Sync Agent is in the process of being paused. |
4 |
|
Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed. |
5 |
|
Sync Agent is in the process of resuming. |
6 |
|
Sync Agent is in the process of stopping. |
Retrieve Status of the Current Automatic Synchronization Event
Get the current status of the automatic synchronization event within the Sync Agent with the bgGetSyncStatus
method.
bgError bgGetSyncStatus(bgSess sess, bgSyncStatus *s);
Table 4-64 lists the bgGetSyncStatus
parameters.
Table 4-64 bgGetSyncStatus Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Pointer to the synchronization status structure in which the status is returned. This pointer cannot be |
Returns zero if the agent has reached specified status. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INTERNAL
if a system error has occured.
The bgSyncStatus
structure provides status information on a current or the last automatic synchronization event in the Sync Agent.
typedef struct _bgSyncStatus { oseSize pubCnt; const char **pubs; osePrio prio; oseU1B _reserved[3]; /**< for alignment */ ose8B startTime; ose8B endTime; oseError res; const char *errMsg; const char *stateName; ose2B state; ose2B progress; } bgSyncStatus;
Table 4-65 describes the fields in bgSyncStatus
.
Table 4-65 bgSyncStatus Fields
Parameters | Description |
---|---|
|
Number of publications synchronized. |
|
Array of names of publications synchronized currently or during last synchronization. |
|
Priority of the current or last synchronization. |
|
Start time of current or last synchronization, in milliseconds, since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronization has not yet started or the last synchronization time is unknown. |
|
End time of the last synchronization in milliseconds since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronzation is currently in progress or has not yet run. |
|
Last synchronization error code. Returns zero if the last synchronization was successful or no synchronization has completed yet. |
|
Last synchronization error message or |
|
Current synchronization stage name. |
|
Current synchronization stage Returns |
|
Progress value in percentage of synchronization, if it is in progress. |
You can issue control commands to the Sync Agent with the bgControlAgent
method. This call returns immediately and does not wait for completion of command execution. Use the bgWaitForStatus
method to wait until the Sync Agent reaches a certain status.
Issue Sync Agent Control Commands
Returns zero if successful. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INVALID_COMMAND
if the control command code is invalid. Returns BG_ERR_CANNOT_ACCEPT_CTRL
if the Sync Agent is not able to execute the provided command in its current state.
bgError bgControlAgent(bgSess sess, int ctrl, int opt);
Table 4-66 lists the bgControlAgent
parameters.
Table 4-66 bgControlAgent Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Sync Agent control command codes, which are listed in Table 4-67. |
|
options for given command |
Table 4-67 lists the Sync Agent control command codes and options.
Table 4-67 Sync Agent Control Command Codes
Name | Description | Option Value |
---|---|---|
|
Start the Sync Agent. If the agent is running, pending or resume pending, this command has no effect. If the Sync Agent is paused, this command resumes the agent. |
By default, this starts the Sync Agent within a separate process named |
|
Stop the Sync Agent. If the agent is stopped or stop pending, this command has no effect. |
By default, stops the Sync Agent gracefully. However, if you set the option to |
|
Pause the Sync Agent. If the agent is paused or pause pending, this command has no effect. |
No options available. |
|
Resume the Sync Agent. If the agent is running, start pending, or resume pending, this command has no effect. |
No options available. |
Wait for Specific Sync Agent Status
Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.
This method is often used to wait for the Sync Agent to start. For example, the following code shows starting the Sync Agent and then waiting until the Sync Agent is up and running:
bgSess sess; bgOpenSession(&sess); bgControlAgent(sess, BG_CTRL_START, 0); bgWaitForStatus(sess, BG_STATUS_RUNNING);
bgError bgWaitForStatus(bgSess sess, int statusCode, long timeOut);
Table 4-68 lists the bgWaitForStatus
parameters.
Table 4-68 bgWaitForStatus Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
The status can be one of the following: |
|
The |
Returns zero if the agent has reached specified status. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_WAIT_TIMEOUT
if the timeout has expired. Returns BG_ERR_INVALID_WAIT_STATUS
if the status code is invalid. Other errors may also be returned.
You can set certain session parameters explicitly with the set session methods. The new parameter value takes effect only after the Sync Agent is restarted. When the session is created, the initial value for each option is loaded from the ose.ini
file.
Options are separated into boolean and numeric parameters:
Boolean options are those options that can only be set to OSE_TRUE
or OSE_FALSE
.
Numeric options are set to an integer value.
Use the bgSetNumParam
and bgGetNumParam
methods to set and get the boolean and numeric session options. The bgSetNumParam
method sets a parameter in the ose.ini
file.
bgError bgSetNumParam(bgSess sess, int param, long val);
Table 4-69 lists the bgSetNumParam
parameters.
Returns zero if the option is retrieved successfully. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INVALID_PARAM
if an invalid parameter code is specified. Returns BG_ERR_INTERNAL
if a system error has occured. Other errors may also be returned.
Table 4-69 bgSetNumParam Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Parameter code. See Table 4-12 for a list of all of the options that can bet set by this method. |
|
The parameter value to set. See Table 4-12 for potential values for this option. |
bgError bgGetNumParam(bgSess sess, int param, long *val);
Table 4-70 lists the bgGetNumParam
parameters.
Returns zero if the option is retrieved successfully. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INVALID_PARAM
if an invalid parameter code is specified. Returns BG_ERR_INTERNAL
if a system error has occured.
Table 4-70 bgGetNumParam Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Param code. See Table 4-71 for a list of all of the options that can bet retrieved by this method. |
|
Pointer to a variable into which to return the parameter value. The pointer cannot be |
Table 4-71 lists all boolean and numeric synchronization options and potential values. For all boolean options, the value can only be either OSE_TRUE
or OSE_FALSE
.
Table 4-71 Numeric and Boolean Session Options
Session Option | Description |
---|---|
|
Boolean parameter. If Refers to the |
|
Maximum number of log files to keep in the |
|
Maximum log file size in bytes. On Windows 32 and Linux, the default is 1 MB. On Windows CE, the default is 128 KB. Refers to the |
|
Time interval in milliseconds for the network manager to wait before evaluating the network state in absence of notifications. The network manager evaluates the network when a notification is received or the interval expires. The network is also evaluated periodically after each period of the said interval. The default is 10 minutes (600000 milliseconds). Refers to the |
Clears and performs a cleanup of the synchronization environment and resources. This function must be invoked for every bgOpenSession
.
Returns zero if successful. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid.
bgError bgCloseSession(bgSess sess);
Table 4-72 lists the bgCloseSession
parameters.
You can create a callback function that is called when Sync Agent messages are generated, which traps automatic synchronization messages and error data. You register or unregister this callback function with the bgAddMsgCallback
or bgRemoveMsgCallback
methods.
Register the Callback Function
Returns zero if successful. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INTERNAL
if a system error has occured.
bgError bgAddMsgCallback(bgSess sess, bgUserCtx ctx, bgMsgCallback cb);
Table 4-73 lists the bgAddMsgCallback
parameters.
Table 4-73 bgAddMsgCallback Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
A user-defined structure that contains the session environment settings. Since the |
|
The callback function handle. |
The Sync Agent invokes the callback function with a message to report the current state and any errors for the Sync Agent or automatic synchronization. Within the callback method, you can perform the appropriate action for the errors returned.
The message callback function is declared as follows:
typedef void (* bgMsgCallback)(bgUserCtx ctx, const bgMsg *msg);
Table 4-74 lists the bgMsgCallback
parameters.
Table 4-74 bgMsgCallback Parameters
Name | Description |
---|---|
|
A user-defined structure that contains the session environment settings. Since the |
|
Pointer for the message structure that reports on the current state and any errors for the Sync Agent or automatic synchronization. |
The bgMsg
structure contains error message information passed to handlers when an event occurs within the Sync Agent or automatic synchronization.
Note:
The memory forbgMsg
structure is allocated within the mobile client and should not be freed by the application.typedef struct _bgMsg { ose8B time; ose4B type; ose4B id; const char *txt; const bgErrorDesc *cause; } bgMsg;
Table 4-75 describes the fields of bgMsg
.
Name | Description |
---|---|
|
Message creation time. Number in milliseconds since the epoch. |
|
Message type: |
|
Application-specific message number. |
|
Message text. |
|
For error messages, optional cause of the error, which can be If the error has an underlying cause, the |
Unregister the Callback Function
Remove the message callback function from the Sync Agent, after which it will no longer be invoked.
Returns zero if successful. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INTERNAL
if a system error has occured.
bgError bgRemoveMsgCallback(bgSess sess, bgUserCtx ctx, bgMsgCallback cb);
Table 4-76 lists the bgRemoveMsgCallback
parameters.
Table 4-76 bgRemoveMsgCallback Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
A user-defined structure that contains the session environment settings. |
|
The callback function handle. |
Retrieves the last error of a call to one of the automatic synchronization APIs.
bgError bgGetLastError(bgSess sess, const bgErrorDesc **errDesc);
Table 4-77 lists the bgGetLastError
parameters.
Returns zero if successful. Returns the BG_ERR_INVALID_SESS
error if the session handle was invalid. Returns the BG_ERR_INTERNAL
error if a system error has occured.
Table 4-77 bgGetLastError Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. This handle can be |
|
A pointer to an |
The bgErrorDesc
structure is a typedef for oseErrorDesc
, which is defined as follows:
typedef struct _oseErrorDesc { oseError code; /* error code */ const char *type; /* a string describing the type of error */ const char *msg; /* error message */ struct _oseErrorDesc *cause; /* underlying cause, if present */ } oseErrorDesc;
If the error has an underlying cause, the oseErrorDesc.cause
points to another oseErrorDesc
structure, which in turn can have its own cause, and so on. This is useful if the OSE call returns an OSE_ERR_INTERNAL_ERROR
, which can be further defined within another oseErrorDesc
structure. If the cause is not present, oseErrorDesc.cause
is NULL
.
Note:
The memory foroseErrorDesc
structure is allocated within mobile server and should not be freed by the application.The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:
Note:
For more details on these classes, refer to the Oracle Database Mobile Server .Net API.Once automatic synchronization for the mobile client is enabled, you can manage it locally through the Sync Agent APIs and remotely through the Mobile Manager UI controls. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is paused, the Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.
The .Net interface for controlling the Sync Agent and automatic synchronization resides in the Oracle.OpenSync.SyncAgent
namespace. The .Net APIs are implemented in Oracle.OpenSync.dll
.
The .Net interface provides for the following functions:
Controlling the Sync Agent.
Retrieve the status of the Sync Agent and automatic synchronization events.
Specify custom handlers for events that occur in automatic synchronization.
The following are the classes and interface for the .Net API for controlling the Sync Agent and automatic synchronization:
BGStatusCode
Enumeration
BGSession
Class
BGAgentStatus
Class
BGSyncStatus
Class
BGMessageType
Enumeration
BGMessageHandler
Interface
The BGStatusCode
enumeration specifies the Sync Agent status codes.
public enum BGStatusCode { Stopped = 0, StartPending, Running, PausePending, Paused, ResumePending, StopPending }
Table 4-78 provides more information about these codes.
Table 4-78 Sync Agent Status Codes
Status Name | Value | Description |
---|---|---|
|
0 |
Sync Agent application is not running. |
|
1 |
Sync Agent is in the process of starting. |
|
2 |
Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active. |
|
3 |
Sync Agent is in the process of being paused. |
|
4 |
Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed. |
|
5 |
Sync Agent is in the process of resuming. |
|
6 |
Sync Agent is in the process of stopping. |
BGSession
is the main class for controlling automatic synchronization through the Sync Agent, as follows:
Start, stop, pause, resume, enable or disable automatic synchronization.
Retrieve automatic synchronization status information.
Specify message handlers for retrieving information about automatic synchronization events.
Note:
In a multi-threaded environment a singleBGSession
should not be used from multiple threads. Each thread should open its own session.The following documents the properties for the BGSession
class.
Read-write properties read or write the value of a field with get
and set
accessors.
Read-only properties read the value of a field with the get
accessor.
Write-only properties set the value of a field with the set
accessor.
Boolean properties get or set the value of a field to either true or false.
Table 4-79 lists all BGSession
properties. Section 4.2.1.3.2, "BGStatusCode Enumeration" lists all enumerations.
Table 4-79 BGSession Properties
Property | Description |
---|---|
|
Gets the Sync Agent status code from the |
|
Boolean property that gets or sets to |
BGSession( )
The public methods and their parameters for the BGSession
class are listed in Table 4-80:
Table 4-80 BGSession Class Public Method Parameters
Parameter | Description |
---|---|
|
Start the Sync Agent. If the agent is already running, starting, or resuming, this call is ignored. If the agent is paused, this call resumes the Sync Agent. This call is asynchronous and does not wait for the Sync Agent to be started before returning. Use the |
|
Same as |
|
Pauses the Sync Agent. If the agent is aready paused or being paused, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be paused before returning. Use the |
|
Resumes the Sync Agent. If the agent is already resumed or resuming, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be resumed before returning. Use the |
|
Stop the Sync Agent. If the agent is already stopped or stopping, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be stopped before returning. Use the |
|
Forcefully terminate the Sync Agent process instead of stopping it gracefully. Use this option as a last resort if the |
|
Closes the session and release all the resources used by the session. |
|
Retrieves the current Sync Agent status. See Section 4.2.1.3.4, "BGAgentStatus Object" for more details on the status information returned. |
|
Get current status of automatic synchronization managed by the Sync Agent. See Table 4-84 for more details on the status information returned. |
|
Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.
Returns |
The following example demonstrates how to start the Sync Agent, retrieve status of the Sync Agent and add a message handler for the session:
// Create the BGSession object using(BGsession sess = new BGSession()) { //Start the Sync Agent, which enables all automatic synchronization events sess.Start(); //Wait until the Sync Agent successfully starts sess.WaitForStatus(BGAgentStatus.RUNNING); //Retrieve the status of the Sync Agent BGAgentStatus s = sess.GetAgentStatus(); //Print out the user that is using automatic synchronization Console.WriteLine("User name: " + s.clientId); //Add a message handler sess.MessageReceived += new BGMessageHandler(myHandler); ... } //When finished, close the session to release all resources sess.Close();
The BGAgentStatus
object represents the current status of the Sync Agent.
The methods for the BGAgentStatus
are listed in Table 4-81.
Table 4-81 BGAgentStatus Class Public Method
Method | Description |
---|---|
|
Get language-specific name of a given status code. When you provide one of the status codes shown in Table 4-78, the appropriate name is returned. Translation dependent on the device language settings |
BGAgentStatus
provides status information on the Sync Agent. Table 4-82 lists and describes the status information fields within the BGAgentStatus
class.
Table 4-82 BGAgentStatus Class Fields
Parameters | Description |
---|---|
|
The name of the application or process that is executing the Sync Agent. On some platforms, such as Android, it is possible to execute the Sync Agent within an application process. |
|
Remaining percentage of battery life, if relevant. |
|
Sync user name. |
|
Name of the network currently used for synchronization, evaluated by Sync Agent. |
|
Network bandwidth in bits per second. |
|
Process id of the process that is executing the Sync Agent, if relevant for a given platform. |
|
Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 4-78. |
The following provides an example of retrieving and processing the Sync Agent status:
BGAgentStatus ags = bgSess.GetAgentStatus(); Console.WriteLine("Agent Status: " + BGAgentStatus.GetStatusName(ags.StatusCode)); if (ags.StatusCode == BGStatusCode.Stopped) return; Console.WriteLine("Client ID: " + ags.ClientId); Console.WriteLine("Process Name: " + ags.AppName); Console.WriteLine("Process ID: " + ags.ProcessId); if (ags.NetworkSpeed > 0) { Console.WriteLine("Network Name: " + ags.NetworkName); Console.WriteLine("Network Speed: " + ags.NetworkSpeed + " bps"); } else Console.WriteLine("Network is not present"); if (ags.BatteryPower > 0) Console.WriteLine("Battery Power: " + ags.BatteryPower + "%"); else Console.WriteLine("Battery is not present");
The BGSyncStatus
object provides status information on a current or the last automatic synchronization event in the Sync Agent.
The methods for the BGSyncStatus
are listed in Table 4-83.
Table 4-83 BGSyncStatus Class Public Method
Method | Description |
---|---|
|
Get language-specific name of a given sync status code. When you provide one of the status codes shown in Table 4-78, the appropriate name is returned. Translation dependent on the device language settings |
BGSyncStatus
provides status information on automatic synchronization in the fields listed in Table 4-84.
Table 4-84 BGSyncStatus Class Fields
Parameters | Description |
---|---|
|
End time of the last synchronization. |
|
Exception object thrown during the last synchronization. Returns |
|
Priority of the current or last synchronization. |
|
Progress stage of synchronization if it is in progress. |
|
Progress value in percentage of synchronization, if it is in progress. |
|
Array of names of publications synchronized currently or during last synchronization. |
|
Start time of the last synchronization. |
The following documents the properties for the BGSyncStatus
class.
Read-write properties read or write the value of a field with get
and set
accessors.
Read-only properties read the value of a field with the get
accessor.
Write-only properties set the value of a field with the set
accessor.
Boolean properties get or set the value of a field to either true or false.
Table 4-85 lists all BGSyncStatus
properties. Section 4.2.1.3.2, "BGStatusCode Enumeration" lists all enumerations.
Table 4-85 BGSyncStatus Properties
Property | Description |
---|---|
|
Read-only boolean property. If an automatic synchronizatoin has already occured, |
|
Read-only boolean property. If automatic synchronization is in progress, |
The following provides an example of retrieving and processing the synchronization status:
BGSyncStatus ss = bgSess.GetSyncStatus(); if (!ss.SyncOccured) return; Console.WriteLine(); Console.WriteLine("Sync Started: " + dt2str(ss.StartTime)); if (!ss.SyncInProgress) Console.WriteLine("Sync Finished: " + dt2str(ss.EndTime)); if (ss.Pubs != NULL && ss.Pubs.Length != 0) { Console.Write("Publications synced: "); for(int i = 0; i < ss.Pubs.Length; i++) { Console.Write(ss.Pubs[i]); if (i == ss.Pubs.Length - 1) Console.WriteLine(); else Console.Write(", "); } } Console.WriteLine("Sync Priority: " + ss.Prio.ToString()); Console.Write("Sync Result: "); if (ss.LastError == NULL) Console.WriteLine("Success"); else Console.WriteLine("Failure: " + ss.LastError.ToString()); Console.WriteLine();
The BGMessageHandler
interface enables the Sync Agent and automatic synchronization message and error data to be trapped during synchronization.
The message handler is defined as follows:
public delegate void BGMessageHandler(object sender, BGMsgEventArgs args);
You can implement a callback function with the same input parameters as the BGMessageHandler
and specify it as your callback function. The following is an example of a user-implemented callback function called msgCallback
. It processes the error message information available in the Msg
parameter that is contained within the BGMsgEventArgs
structure.
static void msgCallback(object sender, BGMsgEventArgs args) { Console.WriteLine("Time: " + dt2str(args.Msg.Time)); Console.WriteLine("Type " + args.Msg.Type); Console.WriteLine("Id " + args.Msg.Id); if (args.Msg.Text != NULL) Console.WriteLine("Text " + args.Msg.Text); if (args.Msg.Cause != NULL) Console.WriteLine("Cause " + args.Msg.Cause); Console.WriteLine(); }
The following event adds or removes a custom message handler to the Sync Agent.
public event BGMessageHandler MessageReceived
With the MessageReceived
event, you can add the message handler as follows:
sess.MessageReceived += new BGMessageHandler(msgCallback);
Sync calls the msgCallback
method with a message to report the current state and any errors for the Sync Agent or automatic synchronization. Within the msgCallback
method, you can perform the appropriate action for the errors returned in the Msg
variable of type BGMessage
, which is a public variable in the BGMsgEventArgs
structure. In addition, System.EventArgs
is the base class for BGMsgEventArgs
, which contains event data.
For a complete description of the BGMsgEventArgs
class, see Section 4.2.1.3.8, "BGMsgEventArgs Class".
The BGMessageType
enumeration contains the definitions for the different message types.
public enum BGMessageType { Info, Warning, Error }
Table 4-86 provides more details about these message types.
The BGMsgEventArgs
class contains the event arguments for the BGMessageHandler
interface. This class encapsulates the BGMessage
object. Both classes exist in the Oracle.OpenSync.SyncAgent
namespace.
public class BGMsgEventArgs : EventArgs { public readonly BGMessage Msg; }
The BGMessage
class contains error message information passed to handlers when an event occurs within the application.
Table 4-87 BGMessage Class Public Fields
Name | Description |
---|---|
|
Message creation time. |
|
Message type: |
|
Error message number. The error code can be one of the |
|
Message text. |
|
For error messages, optional cause of the error, which can be |
The BGException
class signals an error during execution of .Net Sync Agent Control API. The errors can be recoverable. In addition, the BGException
class can appear in the Cause
field in a BGMessage
object.
The BGException
class inherits from OSEException
, which is documented in Section 4.1.1.3.7, "OSEException Class".
The BGException
read-only properties are listed in Table 4-88.
Table 4-88 BGException Properties
Parameters | Description |
---|---|
|
Gets the exception error code. The error code can be one of the |
|
Gets the exception type name. |
|
Use the |
BGException(int errCode)
BGException(int errCode, string msg)
The parameters for the constructor are listed in Table 4-89:
Table 4-89 BGException Constructor Parameter Description
Parameter | Description |
---|---|
|
The error code can be one of the |
|
The error message. |
The following sections describe how to start/stop or enable/disable automatic synchronization from the OCAPI Sync Control API for the mobile client:
Section 4.2.1.4.1, "C/C++ Sync Control APIs to Start or Enable Automatic Synchronization"
Section 4.2.1.4.2, "C# Sync Control APIs to Start or Enable Automatic Synchronization"
Section 4.2.1.4.3, "Java Sync Control APIs to Start or Enable Automatic Synchronization"
Each of these APIs includes a stop method that has a timeout input parameter. You can supply one of the following values for the timeout, which is a long that specifies a time in milliseconds to wait for any current activity in the automatic synchronization to complete.
BG_STOP_TIMEOUT
: A value in seconds that allows the automatic synchronization process to complete before stopping the service. By default, this is set to 5 seconds.
BG_KILL_AGENT
: A value of -1 that makes the automatic synchronization service stop immediately, even if it is in the middle of a synchronization. If an automatic synchronization is in process, it will be terminated. NO errors or messages are returned.
Any long value in milliseconds: If the automatic synchronization does not stop within the time designated, the method returns with an error of BG_ERROR_TIMEOUT
. At this point, reissue the stop method to terminate the automatic synchronization immediately by supplying BG_KILL_AGENT
or -1 as the input value.
The following sections describe the Sync Control APIs for C/C++ applications.
To start or stop the Sync Agent, use the following APIs:
olError olStartSyncAgent() ; olError olStopSyncAgent(long timeout);
To enable or disable the Sync Agent, use the following APIs:
typedef struct _olSyncOpt { olBool bDisable; } olSyncOpt; olError olGetSyncOptions(olSyncOpt *opt); olError olSetSyncOptions(const olSyncOpt *opt);
The olGetSyncOptions
and olSetSyncOptions
methods take a pointer to the olSyncOpt
structure as a parameter. The olSyncOpt
structure contains the bDisable
boolean, which is true
if the Sync Agent is disabled.
To enable the Sync Agent, perform the following:
olSyncOpt opt.bDisable = FALSE; olSetSyncOptions(&opt);
To disable the Sync Agent, perform the following:
olSyncOpt opt.bDisable = TRUE; olSetSyncOptions(&opt);
Use olGetSyncOptions
method to retrieve the current value of the bDisable
boolean.
The following BGSyncControl
class has the following methods:
Start
—Start automatic synchronization that was previously stopped.
Stop
—Stop automatic synchronization. Normally, this is used to stop automatic synchronization before a manual synchronization is invoked. Then, use the start
method to restart automatic synchronization.
Enabled
property—Set Enable
to TRUE
to enable automatic synchronization that was previously disabled. Set to FALSE
to disable automatic synchronization. Even if the client is restarted, automatic synchronization is not enabled unless you enable synchronization. This property returns a boolean where true states that automatic synchronization is enabled and false that it is disabled.
public class BGSyncControl { public void Start(); public void Stop(int timeout); public bool Enabled{) }
All methods throw an OracleException
in case of failure.
The following BGSyncControl
class has the following methods:
start
—Start automatic synchronization that was previously stopped.
stop
—Stop automatic synchronization. Normally, this is used to stop automatic synchronization before a manual synchronization is invoked. Then, use the start
method to restart automatic synchronization.
enable
—Enables automatic synchronization that was previously disabled.
disable
—Disables automatic synchronization on a client. Even if the client is restarted, automatic synchronization is not enabled unless you enable synchronization.
isEnabled
—Returns a boolean where true states that automatic synchronization is enabled.
package oracle.lite.msync; class BGSyncControl { public void start() throws SyncException; public void stop(long timeout) throws SyncException; void enable(); void disable(); bool isEnabled(); }
Note:
The following OCAPI APIs are currently supported for the mobile client, but are not the direction recommended for future applications. To develop applications for future support, migrate existing applications to use the OSE APIs for Managing Automatic Synchronization.If you want to know at what stage the automatic synchronization cycle is, you can request status from the Sync Agent. In the client application, execute the get status API, which will return immediately with at what stage the automatic synchronization cycle is executing. This is different from the notification message API, which only returns when an event is completed within the synchronization cycle.
The get status API returns a structure that describes this event.
The following sections provide implementation details for each development language:
Section 4.2.2.1, "Retrieving Status for Automatic Synchronization in Java Applications"
Section 4.2.2.2, "Retrieving Status for Automatic Synchronization in C and C++ Applications"
Section 4.2.2.3, "Retrieving Status for Automatic Synchronization in C# Applications"
Use the getStatus
method in your Java client application to retrieve status on the automatic synchronization, as follows:
public BGSyncStatus getStatus() throws SyncException
This method returns the BGSyncStatus
class with the status information on the automatic synchronization, as follows:
public class BGSyncStatus { public String clientId; public short syncState; public String syncStateStr; public short syncProgress; public short lastSyncError; public short lastSyncType; public Date lastSyncTime; public short applyState; public String applyStateStr; public short applyProgress; public short lastApplyError; public Date lastApplyTime; public String networkName; public int networkSpeed; public int batteryPower; }
See Section 4.2.2.4, "Input Parameters for Retrieving Messages" for a description of the input parameters in the structure.
Use the olGetSyncStatus
method in your C/C++ client application to retrieve status on the automatic synchronization, as follows:
olError olGetSyncStatus(olSyncStatus *s);
The Sync Agent returns the olSyncStatus
class, which you provide as an input parameter, with the information on what happened, as follows:
typedef struct _olSyncStatus { char clientId[BG_MAX_USERNAME]; ol2B syncState; ol2B syncProgress; char syncStateStr[BG_MAX_STATUS_STR]; olError lastSyncError; ol2B lastSyncType; ol8B lastSyncTime; ol2B applyState; ol2B applyProgress; char applyStateStr[BG_MAX_STATUS_STR]; olError lastApplyError; olU2B _reserved; ol8B lastApplyTime; char networkName[BG_MAX_STATUS_STR]; ol4B networkSpeed; ol4B batteryPower; } olSyncStatus;
See Section 4.2.2.4, "Input Parameters for Retrieving Messages" for a description of the input parameters in the structure.
Use the GetStatus
method in your C/C++ client application to retrieve status on the automatic synchronization, as follows:
public BGSyncStatus GetStatus();
This method returns the BGSyncStatus
class with the status information on the automatic synchronization, as follows:
public class BGSyncStatus { public string clientId; public short syncState; public string syncStateStr; public short syncProgress; public short lastSyncError; public short lastSyncType; public long lastSyncTime; public short applyState; public string applyStateStr; public short applyProgress; public short lastApplyError; public ushort _reserved; public long lastApplyTime; public string networkName; public int networkSpeed; public int batteryPower; }
See Section 4.2.2.4, "Input Parameters for Retrieving Messages" for a description of the input parameters in the structure.
The input parameters in the input structure/class are as follows:
Table 4-90 Status Class Fields
Field | Description |
---|---|
|
User name |
|
A numeric value that denotes the current synchronization stage, such as compose, send, or receive. |
|
String describing the state, as denoted in the |
|
A percentage that indicates the current progress for the automatic synchronization. |
|
If an error occurred in the last synchronization, this is the error code. If no error, this value is zero. |
|
The priority of the data for the last synchronization. If 1, then high priority data; if 0, then regular priority data was synchronized. |
|
Time of the last automatic synchronization. |
|
Code that indicates the state for the apply phase. |
|
String describing the state for the apply phase, as denoted in the |
|
A percentage that indicates the current progress for the apply phase. |
|
If an error occurred in the last apply phase, this is the error code. If no error, this value is zero. |
|
Time of the last apply phase. |
|
The network name assigned to this network. |
|
Current bandwidth of the network. |
|
Current battery power percentage. |
Note:
The following OCAPI APIs are currently supported for the mobile client, but are not the direction recommended for future applications. To develop applications for future support, migrate existing applications to use the OSE APIs for Managing Automatic Synchronization.You can develop a mobile client application to be notified when an automatic synchronization cycle occurs. The application is notified from the Sync Agent when the automatic synchronization completes as well as when a critical event occurs in the client device. For example, when the device battery runs critically low, Oracle Database Mobile Server can notify the application.
In the client application, create a procedure that executes one of the following message APIs. When your application calls the get message API, it blocks until an event occurs within an automatic synchronization. It returns a structure that describes this event.
The following sections provide implementation details for each development language:
Section 4.2.3.1, "Automatic Synchronization Notification for C/C++ Application"
Section 4.2.3.2, "Automatic Synchronization Notification for C# Application"
Section 4.2.3.3, "Automatic Synchronization Notification for Java Applications"
Section 4.2.3.4, "Input Parameters for Automatic Synchronization Notification"
Use the olGetSyncMsg
method in your client application to receive the automatic synchronization notification when implementing for C/C++ applications. In order to block for the status, you need to perform the following:
Start the application messaging service with the olStartSyncMsg
method, providing a queue handle of type olAppMsgQ
. This message starts the messaging service and returns the queue handle in the olAppMsgQ
.
Execute the olGetSyncMsg
with the olAppMsgQ
message handle and the defined olSyncMsg
structure for the returned automatic synchronization information.
The following provides the method definitions:
typedef void *olAppMsgQ /* start application messaging, get queue handle */ olError olStartSyncMsg(olAppMsgQ *q); /*Provide the queue handle and block to retrieve automatic synchronization event */ olError olGetSyncMsg(olAppMsgQ q, olSyncMsg *m);
The olGetSyncMsg
method blocks until an event occurs, then the Sync Agent returns the olSyncMsg
class, which you provide as an input parameter, with the information on what happened, as follows:
typedef struct _olSyncMsg { ol2B type; ol2B id; char msg[BG_MAX_MSG]; } olSyncMsg;
See Section 4.2.3.4, "Input Parameters for Automatic Synchronization Notification" for a description of the input parameters in the structure.
The C/C++ application performs in a different manner than the Java and C# versions in that this creates a message service with its own message queue. Thus, when finished you must perform some cleanup to ensure that the message queue handle is released. Use the olStopSyncMsg
method to stop the messaging service and release the handle. This must be performed for every message queue that is opened with the olStartSyncMsg
method.
olError olStopSyncMsg(olAppMsgQ q);
If you want to force an existing olGetSyncMsg
to return, use the olCancelSyncMsg
from another thread in the application. This causes the olGetSyncMsg
to return with the BG_ERR_APP_MSG_CANCEL
error.
olError olCancelSyncMsg(olAppMsgQ q);
Use the GetMessage
method in your client application to receive the automatic synchronization notification when implementing for C# applications, as follows:
public BGSyncMsg GetMessage();
This method blocks until an event occurs, then the Sync Agent returns the BGSyncMsg
class with the information on what happened, as follows:
public class BGSyncMsg { public int Type; public int Id; public string Msg; }
See Section 4.2.3.4, "Input Parameters for Automatic Synchronization Notification" for a description of the input parameters in the class.
Use the getMessage
method in your client application to receive the automatic synchronization notification when implementing for Java applications, as follows:
public class BGSyncControl { public BGSyncMsg getMessage() throws SyncException; }
This method blocks until an event occurs, then the Sync Agent returns the BGSyncMsg
class with the information on what happened, as follows:
public class BGSyncMsg{ public int type; public int id; public String msg; }
See Section 4.2.3.4, "Input Parameters for Automatic Synchronization Notification" for a description of the input parameters in the class.
The input parameters in the input structure/class are as follows:
Table 4-91 The Sync Message Variables
Variable | Description |
---|---|
Event type |
The event can be of three types, each of which indicate the level of severity of this notification:
|
Event identifier for |
The INFO event identifer describes what occurred, as follows:
|
Event identifier for the |
The
|
Event identifier for the |
The
|
Event Message |
String message that expounds on the information provided by the event type and identifier. |