Vorgehensweise: Synchronisieren eines Pullabonnements (RMO-Programmierung)

Pullabonnements können programmgesteuert mithilfe von Replikationsverwaltungsobjekten (RMO, Replication Management Objects) und dem Zugriff mit verwaltetem Code auf Replikations-Agent-Funktionen synchronisiert werden. Die Klassen, die Sie zum Synchronisieren eines Pullabonnements verwenden, hängen vom Publikationstyp ab, zu dem das Abonnement gehört.

ms147890.note(de-de,SQL.90).gifHinweis:
Wenn Sie eine Synchronisierung starten möchten, die eigenständig ausgeführt wird, ohne dass Ihre Anwendung davon betroffen ist, starten Sie den Agent asynchron. Wenn Sie dagegen das Ergebnis der Synchronisierung überwachen und während des Synchronisierungsvorgangs Feedback vom Agent erhalten möchten (z. B., wenn eine Statusleiste angezeigt werden soll), sollten Sie den Agent synchron starten. Für Abonnenten von Microsoft SQL Server 2005 Express Edition müssen Sie den Agent synchron starten.

So synchronisieren Sie ein Pullabonnement für eine Snapshot- oder Transaktionspublikation

  1. Erstellen Sie mithilfe der ServerConnection-Klasse eine Verbindung mit dem Abonnenten.

  2. Erstellen Sie eine Instanz der TransPullSubscription-Klasse, und legen Sie die folgenden Eigenschaften fest:

  3. Rufen Sie die LoadProperties-Methode auf, um die restlichen Abonnementeigenschaften abzurufen. Falls diese Methode false zurückgibt, überprüfen Sie, ob das Abonnement vorhanden ist.

  4. Starten Sie mithilfe einer der folgenden Möglichkeiten den Verteilungs-Agent auf dem Abonnenten:

    • Rufen Sie die SynchronizeWithJob-Methode für die Instanz von TransPullSubscription aus Schritt 2 auf. Diese Methode startet den Verteilungs-Agent asynchron, und die Steuerung wird sofort an die Anwendung übergeben, während der Agentauftrag ausgeführt wird. Diese Methode kann nicht für Abonnenten von SQL Server 2005 Express Edition aufgerufen werden, oder wenn das Abonnement mit dem Wert false für CreateSyncAgentByDefault (Standard) erstellt wurde.
    • Rufen Sie eine Instanz der TransSynchronizationAgent-Klasse von der SynchronizationAgent-Eigenschaft ab, und rufen Sie die Synchronize-Methode auf. Diese Methode startet den Agent synchron, und die Steuerung verbleibt beim ausgeführten Agentauftrag. Bei der synchronen Ausführung können Sie das Status-Ereignis verarbeiten, während der Agent ausgeführt wird.
      ms147890.note(de-de,SQL.90).gifHinweis:
      Wenn Sie beim Erstellen des Pullabonnements den Wert false für CreateSyncAgentByDefault (Standard) angegeben haben, müssen Sie auch Distributor, DistributorSecurityMode sowie optional DistributorLogin und DistributorPassword angeben, weil die Metadaten im Zusammenhang mit dem Agentauftrag für das Abonnement nicht in MSsubscription_properties verfügbar sind.

So synchronisieren Sie ein Pullabonnement für eine Mergepublikation

  1. Erstellen Sie mithilfe der ServerConnection-Klasse eine Verbindung mit dem Abonnenten.

  2. Erstellen Sie eine Instanz der MergePullSubscription-Klasse, und legen Sie die folgenden Eigenschaften fest:

    • Den Namen der Abonnementdatenbank für DatabaseName.
    • Den Namen der Publikation, zu der das Abonnement gehört, für PublicationName.
    • Den Namen der veröffentlichten Datenbank für PublicationDBName.
    • Den Namen des Verlegers für PublisherName.
    • Die in Schritt 1 erstellte Verbindung für ConnectionContext.
  3. Rufen Sie die LoadProperties-Methode auf, um die restlichen Abonnementeigenschaften abzurufen. Falls diese Methode false zurückgibt, überprüfen Sie, ob das Abonnement vorhanden ist.

  4. Starten Sie mithilfe einer der folgenden Möglichkeiten den Merge-Agent auf dem Abonnenten:

Beispiel

Das folgende Beispiel synchronisiert ein Pullabonnement für eine Transaktionspublikation, wobei der Agent mithilfe des Agentauftrags asynchron gestartet wird.

// Define server, publication, and database names.
String subscriberName = subscriberInstance;
String publisherName = publisherInstance;
String publicationName = "AdvWorksProductTran";
String publicationDbName = "AdventureWorks";
String subscriptionDbName = "AdventureWorksReplica";

// Create a connection to the Subscriber.
ServerConnection conn = new ServerConnection(subscriberName);

TransPullSubscription subscription;

try
{
    // Connect to the Subscriber.
    conn.Connect();

    // Define subscription properties.
    subscription = new TransPullSubscription();
    subscription.ConnectionContext = conn;
    subscription.DatabaseName = subscriptionDbName;
    subscription.PublisherName = publisherName;
    subscription.PublicationDBName = publicationDbName;
    subscription.PublicationName = publicationName;

    // If the pull subscription and the job exists, start the agent job.
    if (subscription.LoadProperties() && subscription.AgentJobId != null)
    {
        subscription.SynchronizeWithJob();
    }
    else
    {
        // Do something here if the subscription does not exist.
        throw new ApplicationException(String.Format(
            "A subscription to '{0}' does not exists on {1}",
            publicationName, subscriberName));
    }
}
catch (Exception ex)
{
    // Do appropriate error handling here.
    throw new ApplicationException("The subscription could not be synchronized.", ex);
}
finally
{
    conn.Disconnect();
}
' Define server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksProductTran"
Dim publicationDbName As String = "AdventureWorks"
Dim subscriptionDbName As String = "AdventureWorksReplica"

' Create a connection to the Subscriber.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

Dim subscription As TransPullSubscription

Try
    ' Connect to the Subscriber.
    conn.Connect()

    ' Define subscription properties.
    subscription = New TransPullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

    ' If the pull subscription and the job exists, start the agent job.
    If subscription.LoadProperties() And Not subscription.AgentJobId Is Nothing Then
        subscription.SynchronizeWithJob()
    Else
        ' Do something here if the subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "A subscription to '{0}' does not exists on {1}", _
         publicationName, subscriberName))
    End If
Catch ex As Exception
    ' Do appropriate error handling here.
    Throw New ApplicationException("The subscription could not be synchronized.", ex)
Finally
    conn.Disconnect()
End Try

Das folgende Beispiel synchronisiert ein Pullabonnement für eine Transaktionspublikation, wobei der Agent synchron gestartet wird.

// Define the server, publication, and database names.
string subscriberName = subscriberInstance;
string publisherName = publisherInstance;
string publicationName = "AdvWorksProductTran";
string subscriptionDbName = "AdventureWorksReplica";
string publicationDbName = "AdventureWorks";

// Create a connection to the Subscriber.
ServerConnection conn = new ServerConnection(subscriberName);

TransPullSubscription subscription;

try
{
    // Connect to the Subscriber.
    conn.Connect();

    // Define the pull subscription.
    subscription = new TransPullSubscription();
    subscription.ConnectionContext = conn;
    subscription.DatabaseName = subscriptionDbName;
    subscription.PublisherName = publisherName;
    subscription.PublicationDBName = publicationDbName;
    subscription.PublicationName = publicationName;

    // If the pull subscription exists, then start the synchronization.
    if (subscription.LoadProperties())
    {
        // Check that we have enough metadata to start the agent.
        if (subscription.PublisherSecurity != null)
        {
            // Synchronously start the Distribution Agent for the subscription.
            subscription.SynchronizationAgent.Synchronize();
        }
        else
        {
            throw new ApplicationException("There is insufficent metadata to " +
                "synchronize the subscription. Recreate the subscription with " +
                "the agent job or supply the required agent properties at run time.");
        }
    }
    else
    {
        // Do something here if the pull subscription does not exist.
        throw new ApplicationException(String.Format(
            "A subscription to '{0}' does not exist on {1}",
            publicationName, subscriberName));
    }
}
catch (Exception ex)
{
    // Implement appropriate error handling here.
    throw new ApplicationException("The subscription could not be " +
        "synchronized. Verify that the subscription has " +
        "been defined correctly.", ex);
}
finally
{
    conn.Disconnect();
}
' Define the server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksProductTran"
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"

' Create a connection to the Subscriber.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

Dim subscription As TransPullSubscription

Try
    ' Connect to the Subscriber.
    conn.Connect()

    ' Define the pull subscription.
    subscription = New TransPullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

    ' If the pull subscription exists, then start the synchronization.
    If subscription.LoadProperties() Then
        ' Check that we have enough metadata to start the agent.
        If Not subscription.PublisherSecurity Is Nothing Then

            ' Write agent output to a log file.
            subscription.SynchronizationAgent.Output = "distagent.log"
            subscription.SynchronizationAgent.OutputVerboseLevel = 2

            ' Synchronously start the Distribution Agent for the subscription.
            subscription.SynchronizationAgent.Synchronize()
        Else
            Throw New ApplicationException("There is insufficent metadata to " + _
             "synchronize the subscription. Recreate the subscription with " + _
             "the agent job or supply the required agent properties at run time.")
        End If
    Else
        ' Do something here if the pull subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "A subscription to '{0}' does not exist on {1}", _
         publicationName, subscriberName))
    End If
Catch ex As Exception
    ' Implement appropriate error handling here.
    Throw New ApplicationException("The subscription could not be " + _
     "synchronized. Verify that the subscription has " + _
     "been defined correctly.", ex)
Finally
    conn.Disconnect()
End Try

Das folgende Beispiel synchronisiert ein Pullabonnement für eine Mergepublikation, wobei der Agent mithilfe des Agentauftrags asynchron gestartet wird.

// Define server, publication, and database names.
String subscriberName = subscriberInstance;
String publisherName = publisherInstance;
String publicationName = "AdvWorksSalesOrdersMerge";
String publicationDbName = "AdventureWorks";
String subscriptionDbName = "AdventureWorksReplica";

// Create a connection to the Subscriber.
ServerConnection conn = new ServerConnection(subscriberName);

MergePullSubscription subscription;

try
{
    // Connect to the Subscriber.
    conn.Connect();

    // Define subscription properties.
    subscription = new MergePullSubscription();
    subscription.ConnectionContext = conn;
    subscription.DatabaseName = subscriptionDbName;
    subscription.PublisherName = publisherName;
    subscription.PublicationDBName = publicationDbName;
    subscription.PublicationName = publicationName;

    // If the pull subscription and the job exists, start the agent job.
    if (subscription.LoadProperties() && subscription.AgentJobId != null)
    {
        subscription.SynchronizeWithJob();
    }
    else
    {
        // Do something here if the subscription does not exist.
        throw new ApplicationException(String.Format(
            "A subscription to '{0}' does not exists on {1}",
            publicationName, subscriberName));
    }
}
catch (Exception ex)
{
    // Do appropriate error handling here.
    throw new ApplicationException("The subscription could not be synchronized.", ex);
}
finally
{
    conn.Disconnect();
}
' Define server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks"
Dim subscriptionDbName As String = "AdventureWorksReplica"

' Create a connection to the Subscriber.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

Dim subscription As MergePullSubscription

Try
    ' Connect to the Subscriber.
    conn.Connect()

    ' Define subscription properties.
    subscription = New MergePullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

    ' If the pull subscription and the job exists, start the agent job.
    If subscription.LoadProperties() And Not subscription.AgentJobId Is Nothing Then
        subscription.SynchronizeWithJob()
    Else
        ' Do something here if the subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "A subscription to '{0}' does not exists on {1}", _
         publicationName, subscriberName))
    End If
Catch ex As Exception
    ' Do appropriate error handling here.
    Throw New ApplicationException("The subscription could not be synchronized.", ex)
Finally
    conn.Disconnect()
End Try

Das folgende Beispiel synchronisiert ein Pullabonnement für eine Mergepublikation, wobei der Agent synchron gestartet wird.

// Define the server, publication, and database names.
string subscriberName = subscriberInstance;
string publisherName = publisherInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string subscriptionDbName = "AdventureWorksReplica";
string publicationDbName = "AdventureWorks";

// Create a connection to the Subscriber.
ServerConnection conn = new ServerConnection(subscriberName);

MergePullSubscription subscription;

try
{
    // Connect to the Subscriber.
    conn.Connect();

    // Define the pull subscription.
    subscription = new MergePullSubscription();
    subscription.ConnectionContext = conn;
    subscription.DatabaseName = subscriptionDbName;
    subscription.PublisherName = publisherName;
    subscription.PublicationDBName = publicationDbName;
    subscription.PublicationName = publicationName;

    // If the pull subscription exists, then start the synchronization.
    if (subscription.LoadProperties())
    {
        // Check that we have enough metadata to start the agent.
        if (subscription.PublisherSecurity != null || subscription.DistributorSecurity != null)
        {
            // Synchronously start the Merge Agent for the subscription.
            subscription.SynchronizationAgent.Synchronize();
        }
        else
        {
            throw new ApplicationException("There is insufficent metadata to " +
                "synchronize the subscription. Recreate the subscription with " +
                "the agent job or supply the required agent properties at run time.");
        }
    }
    else
    {
        // Do something here if the pull subscription does not exist.
        throw new ApplicationException(String.Format(
            "A subscription to '{0}' does not exist on {1}",
            publicationName, subscriberName));
    }
}
catch (Exception ex)
{
    // Implement appropriate error handling here.
    throw new ApplicationException("The subscription could not be " +
        "synchronized. Verify that the subscription has " +
        "been defined correctly.", ex);
}
finally
{
    conn.Disconnect();
}
' Define the server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"

' Create a connection to the Subscriber.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

Dim subscription As MergePullSubscription

Try
    ' Connect to the Subscriber.
    conn.Connect()

    ' Define the pull subscription.
    subscription = New MergePullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

    ' If the pull subscription exists, then start the synchronization.
    If subscription.LoadProperties() Then
        ' Check that we have enough metadata to start the agent.
        If Not subscription.PublisherSecurity Is Nothing Or subscription.DistributorSecurity Is Nothing Then

            ' Output agent messages to the console. 
            subscription.SynchronizationAgent.OutputVerboseLevel = 1
            subscription.SynchronizationAgent.Output = ""

            ' Synchronously start the Merge Agent for the subscription.
            subscription.SynchronizationAgent.Synchronize()
        Else
            Throw New ApplicationException("There is insufficent metadata to " + _
             "synchronize the subscription. Recreate the subscription with " + _
             "the agent job or supply the required agent properties at run time.")
        End If
    Else
        ' Do something here if the pull subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "A subscription to '{0}' does not exist on {1}", _
         publicationName, subscriberName))
    End If
Catch ex As Exception
    ' Implement appropriate error handling here.
    Throw New ApplicationException("The subscription could not be " + _
     "synchronized. Verify that the subscription has " + _
     "been defined correctly.", ex)
Finally
    conn.Disconnect()
End Try

Das folgende Beispiel synchronisiert ein Pullabonnement für eine Mergepublikation mithilfe der Websynchronisierung. Das Abonnement wurde ohne den Agentauftrag und zugehörige Abonnementmetadaten erstellt. Deshalb muss der Agent synchron gestartet werden, und zusätzliche Abonnementinformationen werden bereitgestellt.

// Define the server, publication, and database names.
string subscriberName = subscriberInstance;
string publisherName = publisherInstance;
string distributorName = distributorInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string subscriptionDbName = "AdventureWorksReplica";
string publicationDbName = "AdventureWorks";
string hostname = @"adventure-works\garrett1";
string webSyncUrl = "https://" + publisherInstance + "/SalesOrders/replisapi.dll";

// Create a connection to the Subscriber.
ServerConnection conn = new ServerConnection(subscriberName);

MergePullSubscription subscription;
MergeSynchronizationAgent agent;

try
{
    // Connect to the Subscriber.
    conn.Connect();

    // Define the pull subscription.
    subscription = new MergePullSubscription();
    subscription.ConnectionContext = conn;
    subscription.DatabaseName = subscriptionDbName;
    subscription.PublisherName = publisherName;
    subscription.PublicationDBName = publicationDbName;
    subscription.PublicationName = publicationName;

    // If the pull subscription exists, then start the synchronization.
    if (subscription.LoadProperties())
    {
        // Get the agent for the subscription.
        agent = subscription.SynchronizationAgent;

        // Check that we have enough metadata to start the agent.
        if (agent.PublisherSecurityMode == null)
        {
            // Set the required properties that could not be returned
            // from the MSsubscription_properties table. 
            agent.PublisherSecurityMode = SecurityMode.Integrated;
            agent.DistributorSecurityMode = SecurityMode.Integrated;
            agent.Distributor = publisherName;
            agent.HostName = hostname;

            // Set optional Web synchronization properties.
            agent.UseWebSynchronization = true;
            agent.InternetUrl = webSyncUrl;
            agent.InternetSecurityMode = SecurityMode.Standard;
            agent.InternetLogin = winLogin;
            agent.InternetPassword = winPassword;
        }
        // Enable agent output to the console.
        agent.OutputVerboseLevel = 1;
        agent.Output = "";

        // Synchronously start the Merge Agent for the subscription.
        agent.Synchronize();
    }
    else
    {
        // Do something here if the pull subscription does not exist.
        throw new ApplicationException(String.Format(
            "A subscription to '{0}' does not exist on {1}",
            publicationName, subscriberName));
    }
}
catch (Exception ex)
{
    // Implement appropriate error handling here.
    throw new ApplicationException("The subscription could not be " +
        "synchronized. Verify that the subscription has " +
        "been defined correctly.", ex);
}
finally
{
    conn.Disconnect();
}
' Define the server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
Dim hostname As String = "adventure-works\garrett1"
Dim webSyncUrl As String = "https://" + publisherInstance + "/SalesOrders/replisapi.dll"

' Create a connection to the Subscriber.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

Dim subscription As MergePullSubscription
Dim agent As MergeSynchronizationAgent

Try
    ' Connect to the Subscriber.
    conn.Connect()

    ' Define the pull subscription.
    subscription = New MergePullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

    ' If the pull subscription exists, then start the synchronization.
    If subscription.LoadProperties() Then
        ' Get the agent for the subscription.
        agent = subscription.SynchronizationAgent

        ' Check that we have enough metadata to start the agent.
        If agent.PublisherSecurityMode = Nothing Then
            ' Set the required properties that could not be returned
            ' from the MSsubscription_properties table. 
            agent.PublisherSecurityMode = SecurityMode.Integrated
            agent.Distributor = publisherInstance
            agent.DistributorSecurityMode = SecurityMode.Integrated
            agent.HostName = hostname

            ' Set optional Web synchronization properties.
            agent.UseWebSynchronization = True
            agent.InternetUrl = webSyncUrl
            agent.InternetSecurityMode = SecurityMode.Standard
            agent.InternetLogin = winLogin
            agent.InternetPassword = winPassword
        End If

        ' Enable agent logging to the console.
        agent.OutputVerboseLevel = 1
        agent.Output = ""

        ' Synchronously start the Merge Agent for the subscription.
        agent.Synchronize()
    Else
        ' Do something here if the pull subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "A subscription to '{0}' does not exist on {1}", _
         publicationName, subscriberName))
    End If
Catch ex As Exception
    ' Implement appropriate error handling here.
    Throw New ApplicationException("The subscription could not be " + _
     "synchronized. Verify that the subscription has " + _
     "been defined correctly.", ex)
Finally
    conn.Disconnect()
End Try

Siehe auch

Aufgaben

Vorgehensweise: Erstellen eines Pullabonnements (RMO-Programmierung)
Vorgehensweise: Synchronisieren eines Pullabonnements (Replikationsprogrammierung)

Andere Ressourcen

Synchronisieren von Daten
Programming with Replication Management Objects

Hilfe und Informationen

Informationsquellen für SQL Server 2005