Vorgehensweise: Erstellen eines Pullabonnements (RMO-Programmierung)

Pullabonnements können mithilfe von Replikationsverwaltungsobjekten (RMO, Replication Management Objects) programmgesteuert erstellt werden. Die RMO-Klassen, die Sie zum Erstellen eines Pullabonnements verwenden, hängen vom Publikationstyp ab, zu dem das Abonnement gehört.

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

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

  2. Erstellen Sie mithilfe der Verlegerverbindung aus Schritt 1 eine Instanz der TransPublication-Klasse. Geben Sie Name, DatabaseName und ConnectionContext an.

  3. Rufen Sie die LoadProperties-Methode auf. Falls diese Methode false zurückgibt, sind entweder die in Schritt 2 angegebenen Eigenschaften falsch, oder die Publikation ist auf dem Server nicht vorhanden.

  4. Führen Sie ein bitweises logisches AND (& in Visual C# und And in Visual Basic) zwischen der Attributes-Eigenschaft und AllowPull aus. Falls das Ergebnis None lautet, legen Sie für Attributes das Ergebnis eines bitweisen logischen OR (| in Visual C# und Or in Visual Basic) zwischen Attributes und AllowPull fest. Rufen Sie anschließend CommitPropertyChanges auf, um Pullabonnements zu aktivieren.

  5. Falls die Abonnementdatenbank nicht vorhanden ist, erstellen Sie sie mithilfe der Database-Klasse. Weitere Informationen finden Sie unter Creating, Altering, and Removing Databases.

  6. Erstellen Sie eine Instanz der TransPullSubscription-Klasse.

  7. Legen Sie die folgenden Abonnementeigenschaften fest:

    • ServerConnection auf den in Schritt 1 erstellten Abonnenten für ConnectionContext.
    • Den Namen der Abonnementdatenbank für DatabaseName.
    • Den Namen des Verlegers für PublisherName.
    • Den Namen der Publikationsdatenbank für PublicationDBName.
    • Den Namen der Publikation für PublicationName.
    • Das Feld Login, Password oder SecurePassword von SynchronizationAgentProcessSecurity, um die Anmeldeinformationen für das Microsoft Windows-Konto bereitzustellen, unter dem der Verteilungs-Agent auf dem Abonnenten ausgeführt wird. Mithilfe dieses Kontos werden lokale Verbindungen mit dem Abonnenten sowie Remoteverbindungen mithilfe der Windows-Authentifizierung hergestellt.
      ms147314.note(de-de,SQL.90).gifHinweis:
      SynchronizationAgentProcessSecurity muss zwar nicht festgelegt werden, wenn das Abonnement von einem Mitglied der festen Serverrolle sysadmin erstellt wird, aber es empfiehlt sich. In diesem Fall nimmt der Agent die Identität des SQL Server-Agent-Kontos an. Weitere Informationen finden Sie unter Sicherheitsmodell des Replikations-Agents.
    • (Optional) Den Wert true für CreateSyncAgentByDefault, um einen Agentauftrag zu erstellen, mit dem das Abonnement synchronisiert wird. Wenn Sie false angeben (Standard), kann das Abonnement nur programmgesteuert synchronisiert werden, und Sie müssen zusätzliche Eigenschaften von TransSynchronizationAgent angeben, wenn Sie über die SynchronizationAgent-Eigenschaft auf dieses Objekt zugreifen. Weitere Informationen finden Sie unter Vorgehensweise: Synchronisieren eines Pullabonnements (RMO-Programmierung).
      ms147314.note(de-de,SQL.90).gifHinweis:
      Der SQL Server-Agent wird von Microsoft SQL Server Express Edition nicht unterstützt. Wenn Sie den Wert true für Express Edition-Abonnenten angeben, wird der Agentauftrag nicht erstellt. Wichtige Metadaten im Zusammenhang mit Abonnements werden jedoch auf dem Abonnenten gespeichert.
    • (Optional) Legen Sie das Feld SqlStandardLogin, SqlStandardPassword oder SecureSqlStandardPassword von DistributorSecurity fest, wenn Sie die SQL Server-Authentifizierung zum Herstellen einer Verbindung mit dem Verteiler verwenden.
  8. Rufen Sie die Create-Methode auf.

  9. Rufen Sie mithilfe der Instanz der TransPublication-Klasse aus Schritt 2 die MakePullSubscriptionWellKnown-Methode auf, um das Pullabonnement beim Verleger zu registrieren. Falls diese Registrierung bereits vorhanden ist, tritt eine Ausnahme auf.

So erstellen Sie ein Pullabonnement für eine Mergepublikation

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

  2. Erstellen Sie mithilfe der Verlegerverbindung aus Schritt 1 eine Instanz der MergePublication-Klasse. Geben Sie Name, DatabaseName und ConnectionContext an.

  3. Rufen Sie die LoadProperties-Methode auf. Falls diese Methode false zurückgibt, sind entweder die in Schritt 2 angegebenen Eigenschaften falsch, oder die Publikation ist auf dem Server nicht vorhanden.

  4. Führen Sie ein bitweises logisches AND (& in Visual C# und And in Visual Basic) zwischen der Attributes-Eigenschaft und AllowPull aus. Falls das Ergebnis None lautet, legen Sie für Attributes das Ergebnis eines bitweisen logischen OR (| in Visual C# und Or in Visual Basic) zwischen Attributes und AllowPull fest. Rufen Sie anschließend CommitPropertyChanges auf, um Pullabonnements zu aktivieren.

  5. Falls die Abonnementdatenbank nicht vorhanden ist, erstellen Sie sie mithilfe der Database-Klasse. Weitere Informationen finden Sie unter Creating, Altering, and Removing Databases.

  6. Erstellen Sie eine Instanz der MergePullSubscription-Klasse.

  7. Legen Sie die folgenden Abonnementeigenschaften fest:

    • ServerConnection auf den in Schritt 1 erstellten Abonnenten für ConnectionContext.
    • Den Namen der Abonnementdatenbank für DatabaseName.
    • Den Namen des Verlegers für PublisherName.
    • Den Namen der Publikationsdatenbank für PublicationDBName.
    • Den Namen der Publikation für PublicationName.
    • Das Feld Login, Password oder SecurePassword von SynchronizationAgentProcessSecurity, um die Anmeldeinformationen für das Microsoft Windows-Konto bereitzustellen, unter dem der Merge-Agent auf dem Abonnenten ausgeführt wird. Mithilfe dieses Kontos werden lokale Verbindungen mit dem Abonnenten sowie Remoteverbindungen mithilfe der Windows-Authentifizierung hergestellt.
      ms147314.note(de-de,SQL.90).gifHinweis:
      SynchronizationAgentProcessSecurity muss zwar nicht festgelegt werden, wenn das Abonnement von einem Mitglied der festen Serverrolle sysadmin erstellt wird, aber es empfiehlt sich. In diesem Fall nimmt der Agent die Identität des SQL Server-Agent-Kontos an. Weitere Informationen finden Sie unter Sicherheitsmodell des Replikations-Agents.
    • (Optional) Den Wert true für CreateSyncAgentByDefault, um einen Agentauftrag zu erstellen, mit dem das Abonnement synchronisiert wird. Wenn Sie false angeben (Standard), kann das Abonnement nur programmgesteuert synchronisiert werden, und Sie müssen zusätzliche Eigenschaften von MergeSynchronizationAgent angeben, wenn Sie über die SynchronizationAgent-Eigenschaft auf dieses Objekt zugreifen. Weitere Informationen finden Sie unter Vorgehensweise: Synchronisieren eines Pullabonnements (RMO-Programmierung).
    • (Optional) Legen Sie das Feld SqlStandardLogin, SqlStandardPassword oder SecureSqlStandardPassword von DistributorSecurity fest, wenn Sie die SQL Server-Authentifizierung zum Herstellen einer Verbindung mit dem Verteiler verwenden.
    • (Optional) Legen Sie das Feld SqlStandardLogin, SqlStandardPassword oder SecureSqlStandardPassword von PublisherSecurity fest, wenn Sie die SQL Server-Authentifizierung zum Herstellen einer Verbindung mit dem Verleger verwenden.
  8. Rufen Sie die Create-Methode auf.

  9. Rufen Sie mithilfe der Instanz der MergePublication-Klasse aus Schritt 2 die MakePullSubscriptionWellKnown-Methode auf, um das Pullabonnement beim Verleger zu registrieren. Falls diese Registrierung bereits vorhanden ist, tritt eine Ausnahme auf.

Beispiel

Das folgende Beispiel erstellt ein Pullabonnement für eine Transaktionspublikation. Die Anmeldeinformationen für das Microsoft Windows-Konto, mit dem der Verteilungs-Agent-Auftrag erstellt wird, werden zur Laufzeit übergeben.

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

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
TransPublication publication;
TransPullSubscription subscription;

try
{
    // Connect to the Publisher and Subscriber.
    subscriberConn.Connect();
    publisherConn.Connect();

    // Ensure that the publication exists and that 
    // it supports pull subscriptions.
    publication = new TransPublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.IsExistingObject)
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

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

        // Specify the Windows login credentials for the Distribution Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = true;

        // By default, subscriptions to transactional publications are synchronized 
        // continuously, but in this case we only want to synchronize on demand.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.OnDemand;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (TransSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                TransSubscriberType.ReadOnly);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksProductTran"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As TransPublication
Dim subscription As TransPullSubscription

Try
    ' Connect to the Publisher and Subscriber.
    subscriberConn.Connect()
    publisherConn.Connect()

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions.
    publication = New TransPublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.IsExistingObject Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

        ' Define the pull subscription.
        subscription = New TransPullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.Description = "Pull subscription to " + publicationDbName _
        + " on " + subscriberName + "."

        ' Specify the Windows login credentials for the Distribution Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = True

        ' By default, subscriptions to transactional publications are synchronized 
        ' continuously, but in this case we only want to synchronize on demand.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.OnDemand

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As TransSubscription In publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName And _
                existing.SubscriptionDBName = subscriptionDbName Then
                registered = True
            End If
        Next existing
        If Not registered Then
            ' Register the subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             TransSubscriberType.ReadOnly)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
        "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

Das folgende Beispiel erstellt ein Pullabonnement für eine Mergepublikation. Die Anmeldeinformationen für das Windows-Konto, mit dem der Verteilungs-Agent-Auftrag erstellt wird, werden zur Laufzeit übergeben.

// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksSalesOrdersMerge";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorksReplica";
string publicationDbName = "AdventureWorks";
string hostname = @"adventure-works\garrett1";

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergePullSubscription subscription;

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

    // Ensure that the publication exists and that 
    // it supports pull subscriptions.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

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

        // Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = true;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
Dim hostname As String = "adventure-works\garrett1"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergePullSubscription

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

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

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

        ' Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = True

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
        "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

Das folgende Beispiel erstellt ein Pullabonnement für eine Mergepublikation, ohne dass ein zugehöriger Agentauftrag und Abonnementmetadaten in MSsubscription_properties erstellt werden. Die Anmeldeinformationen für das Windows-Konto, mit dem der Merge-Agent-Auftrag erstellt wird, werden zur Laufzeit übergeben.

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

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergePullSubscription subscription;

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

    // Ensure that the publication exists and that 
    // it supports pull subscriptions.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

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

        // Specify that an agent job not be created for this subscription. The
        // subscription can only be synchronized by running the Merge Agent directly.
        // Subscripition metadata stored in MSsubscription_properties will not
        // be available and must be specified at run time.
        subscription.CreateSyncAgentByDefault = false;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergePullSubscription

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

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

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

        ' Specify that an agent job not be created for this subscription. The
        ' subscription can only be synchronized by running the Merge Agent directly.
        ' Subscripition metadata stored in MSsubscription_properties will not
        ' be available and must be specified at run time.
        subscription.CreateSyncAgentByDefault = False

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
     "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

Das folgende Beispiel erstellt ein Pullabonnement für eine Mergepublikation, das mithilfe der Websynchronisierung über das Internet synchronisiert werden kann. Die Anmeldeinformationen für das Windows-Konto, mit dem der Merge-Agent-Auftrag erstellt wird, werden zur Laufzeit übergeben. Weitere Informationen finden Sie unter How to: Configure Web Synchronization for Merge Replication (RMO Programming).

// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksSalesOrdersMerge";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorksReplica";
string publicationDbName = "AdventureWorks";
string hostname = @"adventure-works\garrett1";
string webSyncUrl = "https://" + publisherInstance + "/WebSync/replisapi.dll";

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergePullSubscription subscription;

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

    // Ensure that the publication exists and that 
    // it supports pull subscriptions and Web synchronization.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }
        if ((publication.Attributes & PublicationAttributes.AllowWebSynchronization) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowWebSynchronization;
        }

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

        // Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Enable Web synchronization.
        subscription.UseWebSynchronization = true;
        subscription.InternetUrl = webSyncUrl;

        // Specify the same Windows credentials to use when connecting to the
        // Web server using HTTPS Basic Authentication.
        subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication;
        subscription.InternetLogin = winLogin;
        subscription.InternetPassword = winPassword;

        // Ensure that we create a job for this subscription.
        subscription.CreateSyncAgentByDefault = true;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
Dim hostname As String = "adventure-works\garrett1"
Dim webSyncUrl As String = "https://" + publisherInstance + "/WebSync/replisapi.dll"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergePullSubscription

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

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions and Web synchronization.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If
        If (publication.Attributes And PublicationAttributes.AllowWebSynchronization) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowWebSynchronization
        End If

        ' Define the pull subscription.
        subscription = New MergePullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.HostName = hostname
        subscription.CreateSyncAgentByDefault = True

        ' Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Enable Web synchronization.
        subscription.UseWebSynchronization = True
        subscription.InternetUrl = webSyncUrl

        ' Specify the same Windows credentials to use when connecting to the
        ' Web server using HTTPS Basic Authentication.
        subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication
        subscription.InternetLogin = winLogin
        subscription.InternetPassword = winPassword

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
     "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

Siehe auch

Aufgaben

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

Andere Ressourcen

Programming with Replication Management Objects
How to: Create a Publication (RMO Programming)
Abonnieren von Publikationen

Hilfe und Informationen

Informationsquellen für SQL Server 2005