Simple Example

The following example does a simple replication from a handheld database to the desktop database:

ReplicationExample.cs: Replicate
01public static void Replicate() 02 { 03 IObjectContainer desktop = Db4oFactory.OpenFile(DtFileName); 04 IObjectContainer handheld = Db4oFactory.OpenFile(HhFileName); 05 IReplicationSession replication = Db4objects.Drs.Replication.Begin(handheld, desktop); 06 07 /* 08 * There is no need to replicate all the objects each time. 09 * ObjectsChangedSinceLastReplication methods gives us 10 * a list of modified objects 11 */ 12 IObjectSet changed = replication.ProviderA().ObjectsChangedSinceLastReplication(); 13 //Iterate through changed objects, replicate them 14 while (changed.HasNext()) 15 { 16 replication.Replicate(changed .Next ()); 17 } 18 replication.Commit(); 19 }
ReplicationExample.vb: Replicate
01Public Shared Sub Replicate() 02 Dim desktop As IObjectContainer = Db4oFactory.OpenFile(DtFileName) 03 Dim handheld As IObjectContainer = Db4oFactory.OpenFile(HhFileName) 04 Dim replic As IReplicationSession = Replication.Begin(handheld, desktop) ' 05 ' There is no need to replicate all the objects each time. 06 ' ObjectsChangedSinceLastReplication methods gives us 07 ' a list of modified objects 08 Dim changed As IObjectSet = replic.ProviderA().ObjectsChangedSinceLastReplication() 09 'Iterate through the changed objects, replicate them 10 While changed.HasNext() 11 replic.Replicate(changed.Next()) 12 End While 13 replic.Commit() 14 End Sub
We start by opening two ObjectContainers. The next line creates the ReplicationSession. This object contains all of the replication-related logic.

After creating the session, there is an interesting line:

C#:

IObjectSet changed = replication.ProviderA().ObjectsChangedSinceLastReplication();

VB:

Dim changed As IObjectSet = replication.ProviderA().ObjectsChangedSinceLastReplication()

This line of code will get the provider associated with the first of our sources (the handheld ObjectContainer in this case). Then it finds all of the objects that have been updated or created. The new/modified objects will be returned in an enumerable ObjectSet.

After that comes a simple loop where the resulting objects are replicated one at a time.
The replication.commit() call at the end is important. This line will save all of the changes we have made, and end any needed transactions. Forgetting to make this call will result in your replication changes being discarded when your application ends, or your ObjectContainers are closed.
The #commit() calls also mark all objects as replicated. Therefore, changed/new objects that are not replicated in this session will be marked as replicated.