Freigeben über


Vorgehensweise: Erstellen von Datensichten auf einem Client

In diesem Thema wird erläutert, wie Sie mit Sync Framework zwei oder mehr Servertabellen zu einer einzelnen Tabelle in der Clientdatenbank zusammenfassen können. Die Beispiele in diesem Thema beziehen sich auf die folgenden Sync Framework-Typen und -Ereignisse:

Informationen zum Ausführen von Beispielcode finden Sie unter "Beispielanwendungen in den Themen zur Vorgehensweise" in Programmieren von allgemeinen Client- und Serversynchronisierungsaufgaben.

Beispiel

In den folgenden Codebeispielen wird gezeigt, wie die Tabellen Customer und CustomerContact in der Sync Framework-Beispieldatenbank synchronisiert werden können. Bei der Erstsynchronisierung werden die Daten in den beiden Tabellen unter Verwendung des Befehls für inkrementelle Einfügungen ausgewählt, auf den Client heruntergeladen und dann in die CustomerInfo-Tabelle eingefügt. Bei der anschließenden Synchronisierung werden qualifizierende Änderungen zum Client heruntergeladen.

Schlüsselbestandteile der API

Sie finden in diesem Abschnitt Codebeispiele für diejenigen Schlüsselbestandteile der API, die zum Zusammenfassen von Tabellen verwendet werden. Die folgenden Codebeispiele geben die Objekte SyncTable und SyncAdapter an, die beide den Namen CustomerInfo verwenden. Durch die Angabe des Namens an beiden Stellen können der SyncAgent und die Anbieter Auswahlen aus den Tabellen Customer und CustomerContact in Einfügungen für die CustomerInfo-Tabelle übersetzen.

SyncTable customerInfoSyncTable = new SyncTable("CustomerInfo");
customerInfoSyncTable.CreationOption = TableCreationOption.DropExistingOrCreateNewTable;
customerInfoSyncTable.SyncDirection = SyncDirection.DownloadOnly;
this.Configuration.SyncTables.Add(customerInfoSyncTable);
SyncAdapter customerInfoSyncAdapter = new SyncAdapter("CustomerInfo");
Dim customerInfoSyncTable As New SyncTable("CustomerInfo")
customerInfoSyncTable.CreationOption = TableCreationOption.DropExistingOrCreateNewTable
customerInfoSyncTable.SyncDirection = SyncDirection.DownloadOnly
Me.Configuration.SyncTables.Add(customerInfoSyncTable)
Dim customerInfoSyncAdapter As New SyncAdapter("CustomerInfo")

Das folgende Codebeispiel enthält die Abfrage für die SelectIncrementalInsertsCommand-Eigenschaft. Die Abfrage verwendet einen Join, um sicherzustellen, dass bei der Erstsynchronisierung nur die Kunden auf den Client heruntergeladen werden, für die Kontaktinformationen vorhanden sind. Bei nachfolgenden Synchronisierungen werden die Einfügungen aus der CustomerContact-Tabelle heruntergeladen. Einfügungen für die Customer-Tabelle werden nur heruntergeladen, wenn in die CustomerContact-Tabelle auch eine Zeile für den Kunden eingefügt ist. Beachten Sie, dass die Auswahlliste nicht alle Spalten enthält. Für alle bei der Synchronisierung verwendeten Abfragen gilt, dass sich die Logik der jeweiligen Abfrage nach den Anforderungen der Anwendung richtet. So könnten Sie z. B. alle Kundeneinträge herunterladen, auch wenn für diese keine Kontaktinformationen vorhanden sind.

SqlCommand customerInfoIncrementalInsertsCommand = new SqlCommand();
customerInfoIncrementalInsertsCommand.CommandType = CommandType.Text;
customerInfoIncrementalInsertsCommand.CommandText =
    "SELECT c.CustomerId, c.CustomerName, c.SalesPerson, cc.PhoneNumber, cc.PhoneType " +
    "FROM Sales.Customer c JOIN Sales.CustomerContact cc ON " +
    "c.CustomerId = cc.CustomerId " +
    "WHERE ((c.InsertTimestamp > @sync_last_received_anchor " +
    "AND c.InsertTimestamp <= @sync_new_received_anchor) OR " +
    "(cc.InsertTimestamp > @sync_last_received_anchor " +
    "AND cc.InsertTimestamp <= @sync_new_received_anchor))";
customerInfoIncrementalInsertsCommand.Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp);
customerInfoIncrementalInsertsCommand.Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp);
customerInfoIncrementalInsertsCommand.Connection = serverConn;
customerInfoSyncAdapter.SelectIncrementalInsertsCommand = customerInfoIncrementalInsertsCommand;
Dim customerInfoIncrementalInsertsCommand As New SqlCommand()
With customerInfoIncrementalInsertsCommand
    .CommandType = CommandType.Text
    .CommandText = _
        "SELECT c.CustomerId, c.CustomerName, c.SalesPerson, cc.PhoneNumber, cc.PhoneType " _
      & "FROM Sales.Customer c JOIN Sales.CustomerContact cc ON " _
      & "c.CustomerId = cc.CustomerId " _
      & "WHERE ((c.InsertTimestamp > @sync_last_received_anchor " _
      & "AND c.InsertTimestamp <= @sync_new_received_anchor) OR " _
      & "(cc.InsertTimestamp > @sync_last_received_anchor " _
      & "AND cc.InsertTimestamp <= @sync_new_received_anchor))"
    .Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp)
    .Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp)
    .Connection = serverConn
End With
customerInfoSyncAdapter.SelectIncrementalInsertsCommand = customerInfoIncrementalInsertsCommand

Das folgende Codebeispiel enthält die Abfrage für die SelectIncrementalDeletesCommand-Eigenschaft. Die Abfrage verwendet zwei SELECT-Anweisungen und eine UNION-Anweisung, um Löschungen für die Tabellen Customer und CustomerContact auszuwählen. Die erste SELECT-Anweisung stellt einen Join zur CustomerContact-Tabelle her, um die PhoneType-Spalte abzurufen. Diese Spalte ist Teil des zusammengesetzten Schlüssels für die CustomerInfo-Tabelle. Die Logik lautet wie folgt:

  • Wenn ein Kunde gelöscht wurde, werden beim Client alle Zeilen für diesen Kunden gelöscht.

  • Wenn Kontaktinformationen gelöscht wurden, wird beim Client nur diese Zeile gelöscht.

  • Wenn sowohl eine Kundenzeile als auch Kontaktinformationen für diese Kunden gelöscht wurden, wird mindestens eine zusätzliche Löschung heruntergeladen. Dies verursacht keine Fehlermeldungen, wenn Änderungen für die Clientdatenbank übernommen werden.

SqlCommand customerInfoIncrementalDeletesCommand = new SqlCommand();
customerInfoIncrementalDeletesCommand.CommandType = CommandType.Text;
customerInfoIncrementalDeletesCommand.CommandText =
    "SELECT c.CustomerId, cc.PhoneType " +
    "FROM Sales.Customer_Tombstone c JOIN Sales.CustomerContact cc ON " +
    "c.CustomerId = cc.CustomerId " +
    "WHERE (@sync_initialized = 1 " +
    "AND (DeleteTimestamp > @sync_last_received_anchor " +
    "AND DeleteTimestamp <= @sync_new_received_anchor)) " +
    "UNION " +
    "SELECT CustomerId, PhoneType " +
    "FROM Sales.CustomerContact_Tombstone " +
    "WHERE (@sync_initialized = 1 " +
    "AND (DeleteTimestamp > @sync_last_received_anchor " +
    "AND DeleteTimestamp <= @sync_new_received_anchor))";
customerInfoIncrementalDeletesCommand.Parameters.Add("@sync_initialized", SqlDbType.Bit);
customerInfoIncrementalDeletesCommand.Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp);
customerInfoIncrementalDeletesCommand.Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp);
customerInfoIncrementalDeletesCommand.Connection = serverConn;
customerInfoSyncAdapter.SelectIncrementalDeletesCommand = customerInfoIncrementalDeletesCommand;
Dim customerInfoIncrementalDeletesCommand As New SqlCommand()
With customerInfoIncrementalDeletesCommand
    .CommandType = CommandType.Text
    .CommandText = _
        "SELECT c.CustomerId, cc.PhoneType " _
      & "FROM Sales.Customer_Tombstone c JOIN Sales.CustomerContact cc ON " _
      & "c.CustomerId = cc.CustomerId " _
      & "WHERE (@sync_initialized = 1 " _
      & "AND (DeleteTimestamp > @sync_last_received_anchor " _
      & "AND DeleteTimestamp <= @sync_new_received_anchor)) " _
      & "UNION " _
      & "SELECT CustomerId, PhoneType " _
      & "FROM Sales.CustomerContact_Tombstone " _
      & "WHERE (@sync_initialized = 1 " _
      & "AND (DeleteTimestamp > @sync_last_received_anchor " _
      & "AND DeleteTimestamp <= @sync_new_received_anchor))"
    .Parameters.Add("@sync_initialized", SqlDbType.Bit)
    .Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp)
    .Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp)
    .Connection = serverConn
End With
customerInfoSyncAdapter.SelectIncrementalDeletesCommand = customerInfoIncrementalDeletesCommand

Das folgende Codebeispiel erstellt einen zusammengesetzten Primärschlüssel für die CustomerInfo-Tabelle. Dieser Schlüssel passt zum Schlüssel für die CustomerContact-Tabelle. Sync Framework kann zwar aus den Tabellen auf dem Server das Schema ableiten, der Schlüssel muss aber in diesem Fall angegeben werden. Sie können das Schema auch manuell erstellen. Dies wird unter Vorgehensweise: Initialisieren der Clientdatenbank und Arbeiten mit dem Tabellenschema beschrieben.

string[] customerInfoPrimaryKey = new string[2];
customerInfoPrimaryKey[0] = "CustomerId";
customerInfoPrimaryKey[1] = "PhoneType";
e.Schema.Tables["CustomerInfo"].PrimaryKey = customerInfoPrimaryKey;
Dim customerInfoPrimaryKey(1) As String
customerInfoPrimaryKey(0) = "CustomerId"
customerInfoPrimaryKey(1) = "PhoneType"
e.Schema.Tables("CustomerInfo").PrimaryKey = customerInfoPrimaryKey

Vollständiges Codebeispiel

Das folgende vollständige Codebeispiel enthält die Codebeispiele, die weiter oben beschrieben wurden, sowie zusätzlichen Code zum Ausführen der Synchronisierung. Für das Beispiel wird die in 'Utility'-Klasse für Datenbankanbieter - Themen zur Vorgehensweise enthaltene Utility-Klasse benötigt. Beachten Sie, dass die Einfügung in die Customer-Tabelle in der Utility-Klasse bei nachfolgenden Synchronisierungen nicht heruntergeladen wird, da es in der CustomerContact-Tabelle keine entsprechende Zeile gibt.

using System;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.Server;
using Microsoft.Synchronization.Data.SqlServerCe;

namespace Microsoft.Samples.Synchronization
{
    class Program
    {
        static void Main(string[] args)
        {

            //The SampleStats class handles information from the SyncStatistics
            //object that the Synchronize method returns.
            SampleStats sampleStats = new SampleStats();

            //Request a password for the client database, and delete
            //and re-create the database. The client synchronization
            //provider also enables you to create the client database 
            //if it does not exist.
            Utility.SetPassword_SqlCeClientSync();
            Utility.DeleteAndRecreateCompactDatabase(Utility.ConnStr_SqlCeClientSync, true);

            //Initial synchronization. Instantiate the SyncAgent
            //and call Synchronize.
            SampleSyncAgent sampleSyncAgent = new SampleSyncAgent();
            SyncStatistics syncStatistics = sampleSyncAgent.Synchronize();
            sampleStats.DisplayStats(syncStatistics, "initial");

            //Make changes on the server.
            Utility.MakeDataChangesOnServer("Customer");
            Utility.MakeDataChangesOnServer("CustomerContact");

            //Subsequent synchronization.
            syncStatistics = sampleSyncAgent.Synchronize();
            sampleStats.DisplayStats(syncStatistics, "subsequent");

            //Return server data back to its original state.
            Utility.CleanUpServer();

            //Exit.
            Console.Write("\nPress Enter to close the window.");
            Console.ReadLine();
        }
    }

    //Create a class that is derived from 
    //Microsoft.Synchronization.SyncAgent.
    public class SampleSyncAgent : SyncAgent
    {
        public SampleSyncAgent()
        {
            //Instantiate a client synchronization provider and specify it
            //as the local provider for this synchronization agent.
            this.LocalProvider = new SampleClientSyncProvider();

            //Instantiate a server synchronization provider and specify it
            //as the remote provider for this synchronization agent.
            this.RemoteProvider = new SampleServerSyncProvider();

            //Add the Customer table: specify a synchronization direction of
            //DownloadOnly, and that an existing table should be dropped.
            SyncTable customerInfoSyncTable = new SyncTable("CustomerInfo");
            customerInfoSyncTable.CreationOption = TableCreationOption.DropExistingOrCreateNewTable;
            customerInfoSyncTable.SyncDirection = SyncDirection.DownloadOnly;
            this.Configuration.SyncTables.Add(customerInfoSyncTable);
            
        }
    }

    //Create a class that is derived from 
    //Microsoft.Synchronization.Server.DbServerSyncProvider.
    public class SampleServerSyncProvider : DbServerSyncProvider
    {
        public SampleServerSyncProvider()
        {
            //Create a connection to the sample server database.
            Utility util = new Utility();
            SqlConnection serverConn = new SqlConnection(Utility.ConnStr_DbServerSync);
            this.Connection = serverConn;

            //Create a command to retrieve a new anchor value from
            //the server. In this case, we use a timestamp value
            //that is retrieved and stored in the client database.
            //During each synchronization, the new anchor value and
            //the last anchor value from the previous synchronization
            //are used: the set of changes between these upper and
            //lower bounds is synchronized.
            //
            //SyncSession.SyncNewReceivedAnchor is a string constant; 
            //you could also use @sync_new_received_anchor directly in 
            //your queries.
            SqlCommand selectNewAnchorCommand = new SqlCommand();
            string newAnchorVariable = "@" + SyncSession.SyncNewReceivedAnchor;
            selectNewAnchorCommand.CommandText =
                "SELECT " + newAnchorVariable + " = min_active_rowversion() - 1";
            selectNewAnchorCommand.Parameters.Add(newAnchorVariable, SqlDbType.Timestamp);
            selectNewAnchorCommand.Parameters[newAnchorVariable].Direction = ParameterDirection.Output;
            selectNewAnchorCommand.Connection = serverConn;
            this.SelectNewAnchorCommand = selectNewAnchorCommand;

            //Create a SyncAdapter for the CustomerInfo table. The CustomerInfo 
            //table on the client is a combination of the Customer and CustomerContact
            //tables on the server. This table is download-only, as specified in 
            //SampleSyncAgent.
            SyncAdapter customerInfoSyncAdapter = new SyncAdapter("CustomerInfo");

            //Specify synchronization commands. The CustomerInfo table 
            //is download-only, so we do not define commands to apply changes to 
            //the server. Each command joins the base tables or tombstone tables
            //to select the appropriate incremental changes. For this application,
            //the logic is as follows:
            //* Select all inserts for customers that have contact information.
            //  This results in more than one row for a customer if that customer 
            //  has more than one phone number.
            //* Select all updates for customer and contact information that has 
            //  already been downloaded.
            //* Select all deletes for customer and contact information that has 
            //  already been downloaded. If a customer has been deleted, delete
            //  all of the rows for that customer. If a phone number has been
            //  deleted, delete only that row.

            //Select inserts.
            SqlCommand customerInfoIncrementalInsertsCommand = new SqlCommand();
            customerInfoIncrementalInsertsCommand.CommandType = CommandType.Text;
            customerInfoIncrementalInsertsCommand.CommandText =
                "SELECT c.CustomerId, c.CustomerName, c.SalesPerson, cc.PhoneNumber, cc.PhoneType " +
                "FROM Sales.Customer c JOIN Sales.CustomerContact cc ON " +
                "c.CustomerId = cc.CustomerId " +
                "WHERE ((c.InsertTimestamp > @sync_last_received_anchor " +
                "AND c.InsertTimestamp <= @sync_new_received_anchor) OR " +
                "(cc.InsertTimestamp > @sync_last_received_anchor " +
                "AND cc.InsertTimestamp <= @sync_new_received_anchor))";
            customerInfoIncrementalInsertsCommand.Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp);
            customerInfoIncrementalInsertsCommand.Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp);
            customerInfoIncrementalInsertsCommand.Connection = serverConn;
            customerInfoSyncAdapter.SelectIncrementalInsertsCommand = customerInfoIncrementalInsertsCommand;

            //Select updates.
            SqlCommand customerInfoIncrementalUpdatesCommand = new SqlCommand();
            customerInfoIncrementalUpdatesCommand.CommandType = CommandType.Text;
            customerInfoIncrementalUpdatesCommand.CommandText =
                "SELECT c.CustomerId, c.CustomerName, c.SalesPerson, cc.PhoneNumber, cc.PhoneType " +
                "FROM Sales.Customer c JOIN Sales.CustomerContact cc ON " +
                "c.CustomerId = cc.CustomerId " +
                "WHERE ((c.UpdateTimestamp > @sync_last_received_anchor " +
                "AND c.UpdateTimestamp <= @sync_new_received_anchor " +
                "AND c.InsertTimestamp <= @sync_last_received_anchor) " +
                "OR (cc.UpdateTimestamp > @sync_last_received_anchor " +
                "AND cc.UpdateTimestamp <= @sync_new_received_anchor " +
                "AND cc.InsertTimestamp <= @sync_last_received_anchor))";
            customerInfoIncrementalUpdatesCommand.Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp);
            customerInfoIncrementalUpdatesCommand.Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp);
            customerInfoIncrementalUpdatesCommand.Connection = serverConn;
            customerInfoSyncAdapter.SelectIncrementalUpdatesCommand = customerInfoIncrementalUpdatesCommand;

            //Select deletes.
            SqlCommand customerInfoIncrementalDeletesCommand = new SqlCommand();
            customerInfoIncrementalDeletesCommand.CommandType = CommandType.Text;
            customerInfoIncrementalDeletesCommand.CommandText =
                "SELECT c.CustomerId, cc.PhoneType " +
                "FROM Sales.Customer_Tombstone c JOIN Sales.CustomerContact cc ON " +
                "c.CustomerId = cc.CustomerId " +
                "WHERE (@sync_initialized = 1 " +
                "AND (DeleteTimestamp > @sync_last_received_anchor " +
                "AND DeleteTimestamp <= @sync_new_received_anchor)) " +
                "UNION " +
                "SELECT CustomerId, PhoneType " +
                "FROM Sales.CustomerContact_Tombstone " +
                "WHERE (@sync_initialized = 1 " +
                "AND (DeleteTimestamp > @sync_last_received_anchor " +
                "AND DeleteTimestamp <= @sync_new_received_anchor))";
            customerInfoIncrementalDeletesCommand.Parameters.Add("@sync_initialized", SqlDbType.Bit);
            customerInfoIncrementalDeletesCommand.Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp);
            customerInfoIncrementalDeletesCommand.Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp);
            customerInfoIncrementalDeletesCommand.Connection = serverConn;
            customerInfoSyncAdapter.SelectIncrementalDeletesCommand = customerInfoIncrementalDeletesCommand;

            //Add the SyncAdapter to the provider.
            this.SyncAdapters.Add(customerInfoSyncAdapter);

        }
    }

    //Create a class that is derived from 
    //Microsoft.Synchronization.Data.SqlServerCe.SqlCeClientSyncProvider.
    //You can just instantiate the provider directly and associate it
    //with the SyncAgent, but here we use this class to handle client 
    //provider events.
    public class SampleClientSyncProvider : SqlCeClientSyncProvider
    {

        public SampleClientSyncProvider()
        {
            //Specify a connection string for the sample client database.
            Utility util = new Utility();
            this.ConnectionString = Utility.ConnStr_SqlCeClientSync;

            //Handle the two schema-related events.
            this.CreatingSchema += new EventHandler<CreatingSchemaEventArgs>(SampleClientSyncProvider_CreatingSchema);
            this.SchemaCreated += new EventHandler<SchemaCreatedEventArgs>(SampleClientSyncProvider_SchemaCreated);
        }

        private void SampleClientSyncProvider_CreatingSchema(object sender, CreatingSchemaEventArgs e)
        {
            Console.Write("Creating schema for " + e.Table.TableName + " | ");

            //Create a compostite primary key for the CustomerInfo table.
            string[] customerInfoPrimaryKey = new string[2];
            customerInfoPrimaryKey[0] = "CustomerId";
            customerInfoPrimaryKey[1] = "PhoneType";
            e.Schema.Tables["CustomerInfo"].PrimaryKey = customerInfoPrimaryKey;
        }

        private void SampleClientSyncProvider_SchemaCreated(object sender, SchemaCreatedEventArgs e)
        {
            Console.WriteLine("Schema created for " + e.Table.TableName);
        }
    }

    //Handle the statistics that are returned by the SyncAgent.
    public class SampleStats
    {
        public void DisplayStats(SyncStatistics syncStatistics, string syncType)
        {
            Console.WriteLine(String.Empty);
            if (syncType == "initial")
            {
                Console.WriteLine("****** Initial Synchronization ******");
            }
            else if (syncType == "subsequent")
            {
                Console.WriteLine("***** Subsequent Synchronization ****");
            }

            Console.WriteLine("Start Time: " + syncStatistics.SyncStartTime);
            Console.WriteLine("Total Changes Downloaded: " + syncStatistics.TotalChangesDownloaded);
            Console.WriteLine("Complete Time: " + syncStatistics.SyncCompleteTime);
            Console.WriteLine(String.Empty);
        }
    }
}
Imports System
Imports System.IO
Imports System.Text
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlServerCe
Imports Microsoft.Synchronization
Imports Microsoft.Synchronization.Data
Imports Microsoft.Synchronization.Data.Server
Imports Microsoft.Synchronization.Data.SqlServerCe

Class Program

    Shared Sub Main(ByVal args() As String)

        'The SampleStats class handles information from the SyncStatistics
        'object that the Synchronize method returns.
        Dim sampleStats As New SampleStats()

        'Request a password for the client database, and delete
        'and re-create the database. The client synchronization
        'provider also enables you to create the client database 
        'if it does not exist.
        Utility.SetPassword_SqlCeClientSync()
        Utility.DeleteAndRecreateCompactDatabase(Utility.ConnStr_SqlCeClientSync, True)

        'Initial synchronization. Instantiate the SyncAgent
        'and call Synchronize.
        Dim sampleSyncAgent As New SampleSyncAgent()
        Dim syncStatistics As SyncStatistics = sampleSyncAgent.Synchronize()
        sampleStats.DisplayStats(syncStatistics, "initial")

        'Make changes on the server.
        Utility.MakeDataChangesOnServer("Customer")
        Utility.MakeDataChangesOnServer("CustomerContact")

        'Subsequent synchronization.
        syncStatistics = sampleSyncAgent.Synchronize()
        sampleStats.DisplayStats(syncStatistics, "subsequent")

        'Return server data back to its original state.
        Utility.CleanUpServer()

        'Exit.
        Console.Write(vbLf + "Press Enter to close the window.")
        Console.ReadLine()

    End Sub 'Main
End Class 'Program

'Create a class that is derived from 
'Microsoft.Synchronization.SyncAgent.
Public Class SampleSyncAgent
    Inherits SyncAgent

    Public Sub New()
        'Instantiate a client synchronization provider and specify it
        'as the local provider for this synchronization agent.
        Me.LocalProvider = New SampleClientSyncProvider()

        'Instantiate a server synchronization provider and specify it
        'as the remote provider for this synchronization agent.
        Me.RemoteProvider = New SampleServerSyncProvider()

        'Add the Customer table: specify a synchronization direction of
        'DownloadOnly, and that an existing table should be dropped.
        Dim customerInfoSyncTable As New SyncTable("CustomerInfo")
        customerInfoSyncTable.CreationOption = TableCreationOption.DropExistingOrCreateNewTable
        customerInfoSyncTable.SyncDirection = SyncDirection.DownloadOnly
        Me.Configuration.SyncTables.Add(customerInfoSyncTable)

    End Sub 'New 
End Class 'SampleSyncAgent

'Create a class that is derived from 
'Microsoft.Synchronization.Server.DbServerSyncProvider.
Public Class SampleServerSyncProvider
    Inherits DbServerSyncProvider

    Public Sub New()
        'Create a connection to the sample server database.
        Dim util As New Utility()
        Dim serverConn As New SqlConnection(Utility.ConnStr_DbServerSync)
        Me.Connection = serverConn

        'Create a command to retrieve a new anchor value from
        'the server. In this case, we use a timestamp value
        'that is retrieved and stored in the client database.
        'During each synchronization, the new anchor value and
        'the last anchor value from the previous synchronization
        'are used: the set of changes between these upper and
        'lower bounds is synchronized.
        '
        'SyncSession.SyncNewReceivedAnchor is a string constant; 
        'you could also use @sync_new_received_anchor directly in 
        'your queries.
        Dim selectNewAnchorCommand As New SqlCommand()
        Dim newAnchorVariable As String = "@" + SyncSession.SyncNewReceivedAnchor
        With selectNewAnchorCommand
            .CommandText = "SELECT " + newAnchorVariable + " = min_active_rowversion() - 1"
            .Parameters.Add(newAnchorVariable, SqlDbType.Timestamp)
            .Parameters(newAnchorVariable).Direction = ParameterDirection.Output
            .Connection = serverConn
        End With
        Me.SelectNewAnchorCommand = selectNewAnchorCommand

        'Create a SyncAdapter for the CustomerInfo table. The CustomerInfo 
        'table on the client is a combination of the Customer and CustomerContact
        'tables on the server. This table is download-only, as specified in 
        'SampleSyncAgent.
        Dim customerInfoSyncAdapter As New SyncAdapter("CustomerInfo")

        'Specify synchronization commands. The CustomerInfo table 
        'is download-only, so we do not define commands to apply changes to 
        'the server. Each command joins the base tables or tombstone tables
        'to select the appropriate incremental changes. For this application,
        'the logic is as follows:
        '* Select all inserts for customers that have contact information.
        '  This results in more than one row for a customer if that customer 
        '  has more than one phone number.
        '* Select all updates for customer and contact information that has 
        '  already been downloaded.
        '* Select all deletes for customer and contact information that has 
        '  already been downloaded. If a customer has been deleted, delete
        '  all of the rows for that customer. If a phone number has been
        '  deleted, delete only that row.
        'Select inserts.
        Dim customerInfoIncrementalInsertsCommand As New SqlCommand()
        With customerInfoIncrementalInsertsCommand
            .CommandType = CommandType.Text
            .CommandText = _
                "SELECT c.CustomerId, c.CustomerName, c.SalesPerson, cc.PhoneNumber, cc.PhoneType " _
              & "FROM Sales.Customer c JOIN Sales.CustomerContact cc ON " _
              & "c.CustomerId = cc.CustomerId " _
              & "WHERE ((c.InsertTimestamp > @sync_last_received_anchor " _
              & "AND c.InsertTimestamp <= @sync_new_received_anchor) OR " _
              & "(cc.InsertTimestamp > @sync_last_received_anchor " _
              & "AND cc.InsertTimestamp <= @sync_new_received_anchor))"
            .Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp)
            .Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp)
            .Connection = serverConn
        End With
        customerInfoSyncAdapter.SelectIncrementalInsertsCommand = customerInfoIncrementalInsertsCommand

        'Select updates.
        Dim customerInfoIncrementalUpdatesCommand As New SqlCommand()
        With customerInfoIncrementalUpdatesCommand
            .CommandType = CommandType.Text
            .CommandText = _
                "SELECT c.CustomerId, c.CustomerName, c.SalesPerson, cc.PhoneNumber, cc.PhoneType " _
              & "FROM Sales.Customer c JOIN Sales.CustomerContact cc ON " _
              & "c.CustomerId = cc.CustomerId " _
              & "WHERE ((c.UpdateTimestamp > @sync_last_received_anchor " _
              & "AND c.UpdateTimestamp <= @sync_new_received_anchor " _
              & "AND c.InsertTimestamp <= @sync_last_received_anchor) " _
              & "OR (cc.UpdateTimestamp > @sync_last_received_anchor " _
              & "AND cc.UpdateTimestamp <= @sync_new_received_anchor " _
              & "AND cc.InsertTimestamp <= @sync_last_received_anchor))"
            .Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp)
            .Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp)
            .Connection = serverConn
        End With
        customerInfoSyncAdapter.SelectIncrementalUpdatesCommand = customerInfoIncrementalUpdatesCommand

        'Select deletes.
        Dim customerInfoIncrementalDeletesCommand As New SqlCommand()
        With customerInfoIncrementalDeletesCommand
            .CommandType = CommandType.Text
            .CommandText = _
                "SELECT c.CustomerId, cc.PhoneType " _
              & "FROM Sales.Customer_Tombstone c JOIN Sales.CustomerContact cc ON " _
              & "c.CustomerId = cc.CustomerId " _
              & "WHERE (@sync_initialized = 1 " _
              & "AND (DeleteTimestamp > @sync_last_received_anchor " _
              & "AND DeleteTimestamp <= @sync_new_received_anchor)) " _
              & "UNION " _
              & "SELECT CustomerId, PhoneType " _
              & "FROM Sales.CustomerContact_Tombstone " _
              & "WHERE (@sync_initialized = 1 " _
              & "AND (DeleteTimestamp > @sync_last_received_anchor " _
              & "AND DeleteTimestamp <= @sync_new_received_anchor))"
            .Parameters.Add("@sync_initialized", SqlDbType.Bit)
            .Parameters.Add("@sync_last_received_anchor", SqlDbType.Timestamp)
            .Parameters.Add("@sync_new_received_anchor", SqlDbType.Timestamp)
            .Connection = serverConn
        End With
        customerInfoSyncAdapter.SelectIncrementalDeletesCommand = customerInfoIncrementalDeletesCommand

        'Add the SyncAdapter to the provider.
        Me.SyncAdapters.Add(customerInfoSyncAdapter)

    End Sub 'New 
End Class 'SampleServerSyncProvider

'Create a class that is derived from 
'Microsoft.Synchronization.Data.SqlServerCe.SqlCeClientSyncProvider.
'You can just instantiate the provider directly and associate it
'with the SyncAgent, but here we use this class to handle client 
'provider events.
Public Class SampleClientSyncProvider
    Inherits SqlCeClientSyncProvider


    Public Sub New()
        'Specify a connection string for the sample client database.
        Dim util As New Utility()
        Me.ConnectionString = Utility.ConnStr_SqlCeClientSync

        'Handle the two schema-related events.
        AddHandler Me.CreatingSchema, AddressOf SampleClientSyncProvider_CreatingSchema
        AddHandler Me.SchemaCreated, AddressOf SampleClientSyncProvider_SchemaCreated

    End Sub 'New


    Private Sub SampleClientSyncProvider_CreatingSchema(ByVal sender As Object, ByVal e As CreatingSchemaEventArgs)

        Console.Write("Creating schema for " + e.Table.TableName + " | ")

        'Create a compostite primary key for the CustomerInfo table.
        Dim customerInfoPrimaryKey(1) As String
        customerInfoPrimaryKey(0) = "CustomerId"
        customerInfoPrimaryKey(1) = "PhoneType"
        e.Schema.Tables("CustomerInfo").PrimaryKey = customerInfoPrimaryKey

    End Sub 'SampleClientSyncProvider_CreatingSchema


    Private Sub SampleClientSyncProvider_SchemaCreated(ByVal sender As Object, ByVal e As SchemaCreatedEventArgs)

        Console.WriteLine("Schema created for " + e.Table.TableName)

    End Sub 'SampleClientSyncProvider_SchemaCreated
End Class 'SampleClientSyncProvider

'Handle the statistics that are returned by the SyncAgent.
Public Class SampleStats

    Public Sub DisplayStats(ByVal syncStatistics As SyncStatistics, ByVal syncType As String)
        Console.WriteLine(String.Empty)
        If syncType = "initial" Then
            Console.WriteLine("****** Initial Synchronization ******")
        ElseIf syncType = "subsequent" Then
            Console.WriteLine("***** Subsequent Synchronization ****")
        End If

        Console.WriteLine("Start Time: " & syncStatistics.SyncStartTime)
        Console.WriteLine("Total Changes Downloaded: " & syncStatistics.TotalChangesDownloaded)
        Console.WriteLine("Complete Time: " & syncStatistics.SyncCompleteTime)
        Console.WriteLine(String.Empty)

    End Sub 'DisplayStats
End Class 'SampleStats

Siehe auch

Konzepte

Programmieren von allgemeinen Client- und Serversynchronisierungsaufgaben