Walkthrough: Executing Synchronization [SQL Express]

In previous two walkthroughs you prepared the server database SyncDB and the compact database SyncCompactDB for synchronization. In this walkthrough, you will create a console application that kicks off synchronization process between these two databases. For in-depth technical details about provisioning servers/clients and executing the synchronization process, see How to: Execute Database Synchronization (SQL Server).

To execute synchronization

  1. In Visual Studio, In Solution Explorer, right-click Solution ‘SyncSQLServerAndSQLExpress’, point to Add, and click New Project.

  2. Select Visual C# from Project Types, and select Console Application from Templates.

  3. Type ExecuteExpressSync for project name.

  4. Click OK to close the New Project dialog box.

  5. In Solution Explorer window, right-click ExecuteExpressSync, and click Add Reference.

  6. Select Microsoft.Synchronization, Microsoft.Synchronization.Data, Microsoft.Synchronization.Data.SqlServer, Microsoft.Synchronization.Data.SqlServerCeand click OK to close the Add Reference dialog box.

  7. Add the following using statements to the beginning of the Program.cs file after the existing using statements.

    using System.Data.SqlClient;
    using Microsoft.Synchronization;
    using Microsoft.Synchronization.Data;
    using Microsoft.Synchronization.Data.SqlServer;
    using Microsoft.Synchronization.Data.SqlServerCe;
    
  8. Add the following statement to the Main method to create a SQL connection to the express database.

  9. Add the following statement to the Main method to create a SQL connection to the server database.

    Important

    In the above statement, replace the server name with your server’s instance name, if you are not using the default instance. For example: if your SQL Server instance is called MYSQLINSTANCE, replace (local) with .\MYSQLINSTANCE.

  10. Add the following statement to the Main method to create a Sync Orchestrator. This code creates a sync orchestrator, sets the local provider of sync orchestrator to a provider object associated with the express database, sets the remote provider of sync orchestrator to a provider object associated with the server database, and sets the direction of sync session to upload-and-download.

    1. Create an instance of the SyncOrchestrator class. The SyncOrchestrator class initiates and controls synchronization sessions.

    2. Set the local provider of the sync orchestrator object to a SqlSyncProvider object associated with the SyncExpressDB client database. The SqlSyncProvider class encapsulates a synchronization provider for SQL Express database that communicates with the client and shields the synchronization orchestrator from the specific implementation of the client database.

    3. Set the remote provider of the sync orchestrator to a SqlSyncProvider object associated with the SyncDB server database. The SqlSyncProvider class represents a synchronization provider that communicates with a SQL Server database and shields other Sync Framework components from the specific implementation of the database.

    4. Set the sync direction of sync orchestrator object to UploadAndDownload so that the client can download/upload changes from/to the server.

  11. Add the following code to subscribe for any errors that occur when applying changes to the client. The ApplyChangeFailed event is raised when a row could not be applied at a client. You will be defining the handler for the error event later in this walkthrough.

    // subscribe for errors that occur when applying changes to the client
    ((SqlCeSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);
    
  12. Add the following statement to the Main method. This code invokes the Synchronize method on the SyncOrchestrator object to start the synchronization process between the SyncDB server database and SyncExpressDB express database.

  13. Add the following statements to the Main method to display statistics returned by the Synchronize method. The SyncOperationStatistics object returned by this method contains statistics about the synchronization session that was executed.

  14. Add the following event handler method to the Program class after the Main method to handle the ApplyChangeFailed event. The DbApplyChangeFailedEventArgs parameter provides information about the error or conflict that caused the failure. In a handler for the event, you can respond to the event in several ways, including specifying whether the synchronization provider should try to apply the row again. The Error property of the object contains metadata about any exceptions that occurred during synchronization. The following sample code displays this error and the type of conflict (of type DbConflictType) occurred during synchronization.

    static void Program_ApplyChangeFailed(object sender, DbApplyChangeFailedEventArgs e)
    {
        // display conflict type
        Console.WriteLine(e.Conflict.Type);
    
        // display error message 
        Console.WriteLine(e.Error);
    }
    
  15. In Solution Explorer, right-click ExecuteExpressSync, and click Build.

  16. In Solution Explorer, right-click ExecuteExpressSync again, and click Set as Startup Project.

    Warning

    If you do not perform this step and you press Ctrl+F5 again, the ProvisionClient application is executed again, and you get an error message about the scope that already exists in the client database.

  17. Press Ctrl+F5 to execute the program. You should see output similar to the following:

    Start Time: 6/14/2010 6:24:19 PM
    Total Changes Uploaded: 0
    Total Changes Downloaded: 3
    Complete Time: 6/14/2010 6:24:22 PM
    
    Press any key to continue . . .
    

    The three records that were in the Products table in the SyncDB server databases are downloaded to the express client.

  18. Press ENTER to close the command prompt window.

  19. In SQL Server Management Studio, right-click .\SQLEXPRESS node, and click New Query to open a query window.

  20. Type and execute (by pressing F5) the following SQL command to confirm that records are indeed downloaded to the express client.

    select * from products
    
  21. In the SQL Server Management Studio, expand (local) SQL Server, expand Databases, expand SyncDB, and expand Tables.

  22. Right-click dbo.Products, and click Edit Top 200 Rows.

  23. Add a record at the end with 4 as ID, Wireless Mouse for Name, and 45 for ListPrice. Make sure the record is saved by pressing TAB after entering the last value.

  24. Now, in Visual Studio, press Ctrl+F5 to execute the client program again. You should see output similar to the following output.

    Start Time: 6/14/2010 6:32:44 PM
    Total Changes Uploaded: 0
    Total Changes Downloaded: 1
    Complete Time: 6/14/2010 6:32:47 PM
    
    Press any key to continue . . .
    

    The one record you added to the server should be downloaded to the client now. You can verify this by using the following steps.

  25. In SQL Server Management Studio, select .\SQLEXPRESS node.

  26. Click New Query from the toolbar.

  27. Type and execute (by pressing F5) the following SQL command to confirm that records are indeed downloaded to the express client.

    select * from products
    
  28. You can play around to become familiar with the Sync Framework technology by adding/updating/deleting records from the server/client. For example, if you delete a record from the server, the corresponding record in the client database should be deleted next time you sync client with the server.

  29. Keep Visual Studio and SQL Server Management Studio open if you want to perform walkthroughs that follow this walkthrough in the tutorial.

Complete Code Example

using System;
using System.Data.SqlClient;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.SqlServer;
using Microsoft.Synchronization.Data.SqlServerCe;

namespace ExecuteExpressSync
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection clientConn = new SqlConnection(@"Data Source=.\SQLEXPRESS; Initial Catalog=SyncExpressDB; Trusted_Connection=Yes");

            SqlConnection serverConn = new SqlConnection("Data Source=localhost; Initial Catalog=SyncDB; Integrated Security=True");

            // create the sync orhcestrator
            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();

            // set local provider of orchestrator to a sync provider associated with the 
            // ProductsScope in the SyncExpressDB express client database
            syncOrchestrator.LocalProvider = new SqlSyncProvider("ProductsScope", clientConn);

            // set the remote provider of orchestrator to a server sync provider associated with
            // the ProductsScope in the SyncDB server database
            syncOrchestrator.RemoteProvider = new SqlSyncProvider("ProductsScope", serverConn);

            // set the direction of sync session to Upload and Download
            syncOrchestrator.Direction = SyncDirectionOrder.UploadAndDownload;

            // subscribe for errors that occur when applying changes to the client
            ((SqlCeSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);

            // execute the synchronization process
            SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();

            // print statistics
            Console.WriteLine("Start Time: " + syncStats.SyncStartTime);
            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);
            Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);
            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);
            Console.WriteLine(String.Empty);
        }

        static void Program_ApplyChangeFailed(object sender, DbApplyChangeFailedEventArgs e)
        {
            // display conflict type
            Console.WriteLine(e.Conflict.Type);

            // display error message 
            Console.WriteLine(e.Error);
        }
    }
}

See Also

Concepts

How to: Execute Database Synchronization (SQL Server)