Walkthrough: Executing Synchronization

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 ‘SyncSQLServerAndSQLCompact’, point to Add, and click New Project.

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

  3. Type ExecuteCompactSync for project name.

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

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

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

  7. Repeat previous two steps to add a reference to System.Data.SqlServerCe assembly.

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

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

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

    重要说明重要提示

    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.

  11. Add the following code to the Main method to create a sync orchestrator, which initiates and controls synchronization sessions. The sync orchestrator contains two sync providers that will participate in a synchronization session. In our scenario, you will need to use a provider object for the server database and a provider object for the compact client database. The high level steps of creating an orchestrator for this scenario are:

    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 SqlCeSyncProvider object associated with the SyncCompactDB client database. The SqlCeSyncProvider class encapsulates a synchronization provider for SQL Server Compact 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.

  12. 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);
    
  13. Add the following code 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 SyncCompactDB compact database.

  14. 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.

  15. 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);
    }
    
  16. In Solution Explorer, right-click ExecuteCompactSync, and click Build.

  17. In Solution Explorer, right-click ExecuteCompactSync again, and click Set as Startup Project.

    备注

    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.

  18. 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 compact client.

  19. Press ENTER to close the command prompt window.

  20. In SQL Server Management Studio, right-click SQL Server Compact [My Computer\...\SyncCompactDB] node, and click New Query to open a query window.

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

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

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

  24. 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.

  25. 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.

  26. In SQL Server Management Studio, select SQL Server Compact [My Computer\...\SyncCompactDB] node.

  27. Click New Query from the toolbar.

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

    select * from products
    
  29. 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.

  30. 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;
using System.Data.SqlClient;
using System.Data.SqlServerCe;

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

namespace ExecuteCompactSync
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a connection to the SyncCompactDB database
            SqlCeConnection clientConn = new SqlCeConnection(@"Data Source='C:\SyncSQLServerAndSQLCompact\SyncCompactDB.sdf'");

            // create a connection to the SyncDB server database
            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 CE sync provider associated with the 
            // ProductsScope in the SyncCompactDB compact client database
            syncOrchestrator.LocalProvider = new SqlCeSyncProvider("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);
        }
    }
}

请参阅

其他资源

How to: Execute Database Synchronization (SQL Server)