Bi-Directional Replication


The previous example copied all new or modified objects from the handheld device to the desktop database. What if we want to go the other way? Well, we only have to add one more loop:

ReplicationExample.cs: replicateBiDirectional
01public static void ReplicateBiDirectional() 02 { 03 IObjectContainer desktop = Db4oFactory.OpenFile(DtFileName); 04 IObjectContainer handheld = Db4oFactory.OpenFile(HhFileName); 05 IReplicationSession replication = Db4objects.Drs.Replication.Begin(handheld, desktop); 06 IObjectSet changed = replication.ProviderA().ObjectsChangedSinceLastReplication(); 07 while (changed.HasNext()) 08 { 09 replication.Replicate(changed.Next()); 10 } 11 12 // Add one more loop for bi-directional replication 13 changed = replication.ProviderB().ObjectsChangedSinceLastReplication(); 14 while (changed.HasNext()) 15 { 16 replication.Replicate(changed.Next()); 17 } 18 replication.Commit(); 19 }

ReplicationExample.vb: replicateBiDirectional
01Public Shared Sub ReplicateBiDirectional() 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 Dim changed As IObjectSet = replic.ProviderA().ObjectsChangedSinceLastReplication() 06 'Iterate changed objects, replicate them 07 While changed.HasNext() 08 replic.Replicate(changed.Next()) 09 End While 10 11 changed = replic.ProviderB().ObjectsChangedSinceLastReplication() 12 ' Add one more loop for bi-directional replication 13 While changed.HasNext() 14 replic.Replicate(changed.Next()) 15 End While 16 replic.Commit() 17 End Sub

Now our handheld contains all of the new and modified records from our desktop.

Easy, isn't it? Now, if there had been any modifications made to the destination database, the two are now both in sync with each other.