Walkthrough: Executing Synchronization for the Filtered Scope [SQL Express]
In this walkthrough you will create a console application that synchronizes the SyncExpressDB database with the SyncDB database. 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
In Solution Explorer, right-click Solution ‘SyncSQLServerAndSQLExpress’, point to Add, and click New Project.
Select Visual C# from Project Types, and select Console Application from Templates.
Type ExecuteExpressFilteredSync for project name.
Click OK to close the New Project dialog box.
In Solution Explorer window, right-click ExecuteExpressFilteredSync, and then click Add Reference.
Select Microsoft.Synchronization, Microsoft.Synchronization.Data, Microsoft.Synchronization.Data.SqlServer on the .NET tab and click OK to close the Add Reference dialog box.
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;
Add the following statement to the Main method to create a SQL connection to the express database.
Add the following statement to the Main method to create an SQL connection to the server database.
Importante
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.
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 express client database. The high level steps of creating an orchestrator for this scenario are:
Create an instance of the SyncOrchestrator class. The SyncOrchestrator class initiates and controls synchronization sessions.
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 that communicates with the client and shields the synchronization orchestrator from the specific implementation of the client database.
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.
Set the sync direction of sync orchestrator object to UploadAndDownload so that the client can download/upload changes from/to the server.
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 ((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);
Add the following statement to the Main method to execute the synchronization between SQL Server and SQL Express. This code invokes the Synchronize method on the SyncOrchestrator object to start the synchronization process between the SyncDB server database and SyncExpressDB express database.
Add the following statements to the Main method to display statistics from the sync session. The SyncOperationStatistics object returned by this method contains statistics about the synchronization session that was executed.
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); }
In Solution Explorer, right-click ExecuteExpressFilteredSync, and click Build.
In Solution Explorer, right-click ExecuteExpressFilteredSync again, and click Set as Startup Project.
Advertencia
If you do not perform this step and you press Ctrl+F5 again, the ProvisionFilteredScopeClient application is executed again, and you get an error message about the scope that already exists in the client database.
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: 2 Complete Time: 6/14/2010 6:24:22 PM Press any key to continue . . .
The two records with OriginalState column set to ‘NC’ are downloaded from the Orders table in the SyncDB server to the express client.
Press ENTER to close the command prompt window.
In SQL Server Management Studio, select .\SQLEXPRESS.
Click New Query on toolbar.
Type and execute (by pressing F5) the following SQL command to confirm that records are indeed downloaded to the express client.
select * from Orders
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.
Complete Code Example
using System;
using System.Data.SqlClient;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.SqlServer;
namespace ExecuteExpressFilteredSync
{
class Program
{
static void Main(string[] args)
{
// connect to the SQL Express database
SqlConnection clientConn = new SqlConnection(@"Data Source=.\SQLEXPRESS; Initial Catalog=SyncExpressDB; Trusted_Connection=Yes");
// connect to the server database
SqlConnection serverConn = new SqlConnection("Data Source=localhost; Initial Catalog=SyncDB; Integrated Security=True");
// create a sync orchestration object
SyncOrchestrator syncOrchestrator = new SyncOrchestrator();
// set the local provider of sync orchestrator to a sync provider that is
// associated with the OrdersScope-NC scope in the SyncExpressDB database
syncOrchestrator.LocalProvider = new SqlSyncProvider("OrdersScope-NC", clientConn);
// set the remote provider of sync orchestrator to a server sync provider that is
// associated with the OrdersScope-NC scope in the SyncDB database
syncOrchestrator.RemoteProvider = new SqlSyncProvider("OrdersScope-NC", serverConn);
// set the direction to Upload and Download
syncOrchestrator.Direction = SyncDirectionOrder.UploadAndDownload;
// subscribe for errors that occur when applying changes to the client
((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);
// starts the synchornization session
SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();
// prints statistics from the sync session
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);
}
}
}