VB.NET  •  Implement Synchronization

Listing 1. This code allows you to create and maintain a synchronization with merge replication using the SqlCeReplication object. The object's properties should match those that you use to create the publication. You can use the InternetUrl and InternetPassword properties to match the required IIS virtual directory authentication credentials. If this is the first synchronization, use the Add.Subscription method, which creates a new local database. Subsequent calls to the Synchronize method synchronize changes with the remote Merge Agent (through IIS).

Imports System.Data.SqlServerCe
Imports System.Data.SqlServerCe.SqlCeException
Dim oRepl As New SqlCeReplication

' Set the values for the CE replication object
oRepl.Publisher = "<SQL Server Name>"
oRepl.PublisherDatabase = "ContactManagement"
oRepl.Publication = "CMMerge"
oRepl.PublisherLogin = "<Valid SQL Login>"
oRepl.PublisherPassword = "SQL Password"
oRepl.SubscriberConnectionString = _
   "Provider=Microsoft.SQLServer.OLEDB.CE.2.0; " & _
   "Data Source=\My Documents\ContactManagement.sdf;"
oRepl.Subscriber = "CEDevice"
oRepl.InternetUrl = "http://www.yoursever.com/sqlce"
oRepl.InternetLogin = _
   "<Username From Virtual Directory Security>"
oRepl.InternetPassword = "Password"

' Make sure we get updates as well as send them
oRepl.ExchangeType = ExchangeType.BiDirectional
Try
   ' If the local DB exists, then just synch to it
   If Not File.Exists( _
   "\My Documents\ContactManagement.sdf") Then
   ' Tell SQL CE to create the database
   oRepl.AddSubscription(AddOption.CreateDatabase)
   End If
   ' Now synchronize with the current snapshot 
   ' in Merge Replication
   oRepl.Synchronize()
   Catch ex As SqlCeException
   'TODO: Add Error handling code here
   End Try

   ' Cleanup
   oRepl.Dispose()