Vorgehensweise: Erstellen einer Veröffentlichung (RMO-Programmierung)

Sie können Veröffentlichungen mithilfe von Replikationsverwaltungsobjekten (RMO) programmgesteuert erstellen. Welche RMO-Klassen Sie zum Erstellen von Veröffentlichungen verwenden, hängt vom Typ der zu erstellenden Veröffentlichung ab.

SicherheitshinweisSicherheitshinweis

Benutzer sollten nach Möglichkeit dazu aufgefordert werden, Anmeldeinformationen zur Laufzeit einzugeben. Wenn Sie Anmeldeinformationen speichern müssen, verwenden Sie die Kryptografiedienste von Microsoft Windows .NET Framework.

So erstellen Sie eine Snapshot- oder Transaktionsveröffentlichung

  1. Erstellen Sie eine Verbindung mit dem Verleger, indem Sie die ServerConnection-Klasse verwenden.

  2. Erstellen Sie eine Instanz der ReplicationDatabase-Klasse für die Veröffentlichungsdatenbank, legen Sie die ConnectionContext-Eigenschaft auf die Instanz von ServerConnection aus Schritt 1 fest, und rufen Sie die LoadProperties-Methode auf. Wenn LoadProperties den Wert false zurückgibt, vergewissern Sie sich, dass die Datenbank vorhanden ist.

  3. Hat die EnabledTransPublishing-Eigenschaft den Wert false, dann legen Sie ihren Wert auf true fest.

  4. Überprüfen Sie für eine Transaktionsveröffentlichung den Wert der LogReaderAgentExists-Eigenschaft. Wenn diese Eigenschaft den Wert true hat, ist ein Protokolllese-Agentauftrag für diese Datenbank bereits vorhanden. Hat diese Eigenschaft den Wert false, gehen Sie wie folgt vor:

  5. Erstellen Sie eine Instanz der TransPublication-Klasse, und legen Sie die folgenden Eigenschaften für dieses Objekt fest:

  6. Rufen Sie die Create-Methode auf, um die Veröffentlichung zu erstellen.

    SicherheitshinweisSicherheitshinweis

     Beim Konfigurieren eines Verlegers mit einem Remoteverteiler werden die Werte, die für alle Eigenschaften einschließlich SnapshotGenerationAgentProcessSecurity bereitgestellt werden, als Nur-Text an den Verteiler gesendet. Sie sollten die Verbindung zwischen dem Verleger und dem zugehörigen Remoteverteiler verschlüsseln, bevor Sie die Create-Methode aufrufen. Weitere Informationen finden Sie unter Verschlüsseln von Verbindungen zu SQL Server.

  7. Rufen Sie die CreateSnapshotAgent-Methode auf, um den Snapshot-Agentauftrag für die Veröffentlichung zu erstellen.

So erstellen Sie eine Mergeveröffentlichung

  1. Erstellen Sie eine Verbindung mit dem Verleger, indem Sie die ServerConnection-Klasse verwenden.

  2. Erstellen Sie eine Instanz der ReplicationDatabase-Klasse für die Veröffentlichungsdatenbank, legen Sie die ConnectionContext-Eigenschaft auf die Instanz von ServerConnection aus Schritt 1 fest, und rufen Sie die LoadProperties-Methode auf. Wenn LoadProperties den Wert false zurückgibt, vergewissern Sie sich, dass die Datenbank vorhanden ist.

  3. Wenn die EnabledMergePublishing-Eigenschaft den Wert false hat, legen Sie sie auf true fest, und rufen Sie CommitPropertyChanges auf.

  4. Erstellen Sie eine Instanz der MergePublication-Klasse, und legen Sie die folgenden Eigenschaften für dieses Objekt fest:

    • Die ServerConnection aus Schritt 1 für ConnectionContext.

    • Den Namen der veröffentlichten Datenbank für DatabaseName.

    • Einen Namen für die Veröffentlichung für Name.

    • Die Felder Login und Password von SnapshotGenerationAgentProcessSecurity, um die Anmeldeinformationen für das Windows-Konto bereitzustellen, unter dem der Snapshot-Agent ausgeführt wird. Dieses Konto wird auch verwendet, wenn der Snapshot-Agent Verbindungen mit dem lokalen Verteiler herstellt, sowie für alle Remoteverbindungen mithilfe der Windows-Authentifizierung.

      HinweisHinweis

      Wenn die Veröffentlichung von einem Mitglied der festen Serverrolle sysadmin erstellt wird, müssen Sie SnapshotGenerationAgentProcessSecurity nicht festlegen. Weitere Informationen finden Sie unter Sicherheitsmodell des Replikations-Agents.

    • (Optional) Verwenden Sie den inklusiven logischen OR-Operator (| in Visual C# und Or in Visual Basic) und den exklusiven logischen OR-Operator (^ in Visual C# und Xor in Visual Basic), um die PublicationAttributes-Werte für die Attributes-Eigenschaft festzulegen.

  5. Rufen Sie die Create-Methode auf, um die Veröffentlichung zu erstellen.

    SicherheitshinweisSicherheitshinweis

     Beim Konfigurieren eines Verlegers mit einem Remoteverteiler werden die Werte, die für alle Eigenschaften einschließlich SnapshotGenerationAgentProcessSecurity bereitgestellt werden, als Nur-Text an den Verteiler gesendet. Sie sollten die Verbindung zwischen dem Verleger und dem zugehörigen Remoteverteiler verschlüsseln, bevor Sie die Create-Methode aufrufen. Weitere Informationen finden Sie unter Verschlüsseln von Verbindungen zu SQL Server.

  6. Rufen Sie die CreateSnapshotAgent-Methode auf, um den Snapshot-Agentauftrag für die Veröffentlichung zu erstellen.

Beispiel

In diesem Beispiel wird die AdventureWorks-Datenbank für Transaktionsveröffentlichung aktiviert, ein Protokolllese-Agentauftrag definiert und die AdvWorksProductTran-Veröffentlichung erstellt. Für diese Veröffentlichung muss ein Artikel definiert sein. Die Anmeldeinformationen für das Windows-Konto, die für die Erstellung des Protokolllese-Agentauftrags erforderlich sind, werden zur Laufzeit übergeben. Informationen darüber, wie RMO verwendet wird, um Snapshot- und Transaktionsartikel zu definieren, finden Sie unter Vorgehensweise: Definieren eines Artikels (RMO-Programmierung).

            // Set the Publisher, publication database, and publication names.
            string publicationName = "AdvWorksProductTran";
            string publicationDbName = "AdventureWorks2008R2";
            string publisherName = publisherInstance;

            ReplicationDatabase publicationDb;
            TransPublication publication;

            // Create a connection to the Publisher using Windows Authentication.
            ServerConnection conn;
            conn = new ServerConnection(publisherName);


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

                // Enable the AdventureWorks database for transactional publishing.
                publicationDb = new ReplicationDatabase(publicationDbName, conn);

                // If the database exists and is not already enabled, 
                // enable it for transactional publishing.
                if (publicationDb.LoadProperties())
                {
                    if (!publicationDb.EnabledTransPublishing)
                    {
                        publicationDb.EnabledTransPublishing = true;
                    }

                    // If the Log Reader Agent does not exist, create it.
                    if (!publicationDb.LogReaderAgentExists)
                    {
                        // Specify the Windows account under which the agent job runs.
                        // This account will be used for the local connection to the 
                        // Distributor and all agent connections that use Windows Authentication.
                        publicationDb.LogReaderAgentProcessSecurity.Login = winLogin;
                        publicationDb.LogReaderAgentProcessSecurity.Password = winPassword;

                        // Explicitly set authentication mode for the Publisher connection
                        // to the default value of Windows Authentication.
                        publicationDb.LogReaderAgentPublisherSecurity.WindowsAuthentication = true;

                        // Create the Log Reader Agent job.
                        publicationDb.CreateLogReaderAgent();
                    }
                }
                else
                {
                    throw new ApplicationException(String.Format(
                        "The {0} database does not exist at {1}.",
                        publicationDb, publisherName));
                }

                // Set the required properties for the transactional publication.
                publication = new TransPublication();
                publication.ConnectionContext = conn;
                publication.Name = publicationName;
                publication.DatabaseName = publicationDbName;

                // Specify a transactional publication (the default).
                publication.Type = PublicationType.Transactional;

                // Activate the publication so that we can add subscriptions.
                publication.Status = State.Active;

                // Enable push and pull subscriptions and independent Distribition Agents.
                publication.Attributes |= PublicationAttributes.AllowPull;
                publication.Attributes |= PublicationAttributes.AllowPush;
                publication.Attributes |= PublicationAttributes.IndependentAgent;

                // Specify the Windows account under which the Snapshot Agent job runs.
                // This account will be used for the local connection to the 
                // Distributor and all agent connections that use Windows Authentication.
                publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin;
                publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword;

                // Explicitly set the security mode for the Publisher connection
                // Windows Authentication (the default).
                publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;

                if (!publication.IsExistingObject)
                {
                    // Create the transactional publication.
                    publication.Create();

                    // Create a Snapshot Agent job for the publication.
                    publication.CreateSnapshotAgent();
                }
                else
                {
                    throw new ApplicationException(String.Format(
                        "The {0} publication already exists.", publicationName));
                }
            }

            catch (Exception ex)
            {
                // Implement custom application error handling here.
                throw new ApplicationException(String.Format(
                    "The publication {0} could not be created.", publicationName), ex);
            }
            finally
            {
                conn.Disconnect();
            }
' Set the Publisher, publication database, and publication names.
Dim publicationName As String = "AdvWorksProductTran"
Dim publicationDbName As String = "AdventureWorks2008R2"
Dim publisherName As String = publisherInstance

Dim publicationDb As ReplicationDatabase
Dim publication As TransPublication

' Create a connection to the Publisher using Windows Authentication.
Dim conn As ServerConnection
conn = New ServerConnection(publisherName)

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

    ' Enable the AdventureWorks database for transactional publishing.
    publicationDb = New ReplicationDatabase(publicationDbName, conn)

    ' If the database exists and is not already enabled, 
    ' enable it for transactional publishing.
    If publicationDb.LoadProperties() Then
        If Not publicationDb.EnabledTransPublishing Then
            publicationDb.EnabledTransPublishing = True
        End If

        ' If the Log Reader Agent does not exist, create it.
        If Not publicationDb.LogReaderAgentExists Then
            ' Specify the Windows account under which the agent job runs.
            ' This account will be used for the local connection to the 
            ' Distributor and all agent connections that use Windows Authentication.
            publicationDb.LogReaderAgentProcessSecurity.Login = winLogin
            publicationDb.LogReaderAgentProcessSecurity.Password = winPassword

            ' Explicitly set authentication mode for the Publisher connection
            ' to the default value of Windows Authentication.
            publicationDb.LogReaderAgentPublisherSecurity.WindowsAuthentication = True

            ' Create the Log Reader Agent job.
            publicationDb.CreateLogReaderAgent()
        End If
    Else
        Throw New ApplicationException(String.Format( _
         "The {0} database does not exist at {1}.", _
         publicationDb, publisherName))
    End If

    ' Set the required properties for the transactional publication.
    publication = New TransPublication()
    publication.ConnectionContext = conn
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName

    ' Specify a transactional publication (the default).
    publication.Type = PublicationType.Transactional

    'Enable push and pull subscriptions and independent Distribition Agents.
    publication.Attributes = _
    publication.Attributes Or PublicationAttributes.AllowPull
    publication.Attributes = _
    publication.Attributes Or PublicationAttributes.AllowPush
    publication.Attributes = _
    publication.Attributes Or PublicationAttributes.IndependentAgent

    ' Activate the publication so that we can add subscriptions.
    publication.Status = State.Active

    ' Specify the Windows account under which the Snapshot Agent job runs.
    ' This account will be used for the local connection to the 
    ' Distributor and all agent connections that use Windows Authentication.
    publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin
    publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword

    ' Explicitly set the security mode for the Publisher connection
    ' Windows Authentication (the default).
    publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = True

    If Not publication.IsExistingObject Then
        ' Create the transactional publication.
        publication.Create()

        ' Create a Snapshot Agent job for the publication.
        publication.CreateSnapshotAgent()
    Else
        Throw New ApplicationException(String.Format( _
            "The {0} publication already exists.", publicationName))
    End If
Catch ex As Exception
    ' Implement custom application error handling here.
    Throw New ApplicationException(String.Format( _
        "The publication {0} could not be created.", publicationName), ex)
Finally
    conn.Disconnect()
End Try

In diesem Beispiel wird die AdventureWorks-Datenbank für Mergepublishing aktiviert und die AdvWorksSalesOrdersMerge-Veröffentlichung erstellt. Für diese Veröffentlichung müssen ebenfalls Artikel definiert sein. Die Anmeldeinformationen für das Windows-Konto, die für die Erstellung des Snapshot-Agentauftrags erforderlich sind, werden zur Laufzeit übergeben. Informationen darüber, wie RMO verwendet wird, um Mergeartikel zu definieren, finden Sie unter Vorgehensweise: Definieren eines Artikels (RMO-Programmierung).

         // Set the Publisher, publication database, and publication names.
            string publisherName = publisherInstance;
            string publicationName = "AdvWorksSalesOrdersMerge";
            string publicationDbName = "AdventureWorks2008R2";

            ReplicationDatabase publicationDb;
            MergePublication publication;

            // Create a connection to the Publisher.
            ServerConnection conn = new ServerConnection(publisherName);

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

                // Enable the database for merge publication.               
                publicationDb = new ReplicationDatabase(publicationDbName, conn);
                if (publicationDb.LoadProperties())
                {
                    if (!publicationDb.EnabledMergePublishing)
                    {
                        publicationDb.EnabledMergePublishing = true;
                    }
                }
                else
                {
                    // Do something here if the database does not exist. 
                    throw new ApplicationException(String.Format(
                        "The {0} database does not exist on {1}.",
                        publicationDb, publisherName));
                }

                // Set the required properties for the merge publication.
                publication = new MergePublication();
                publication.ConnectionContext = conn;
                publication.Name = publicationName;
                publication.DatabaseName = publicationDbName;

                // Enable precomputed partitions.
                publication.PartitionGroupsOption = PartitionGroupsOption.True;

                // Specify the Windows account under which the Snapshot Agent job runs.
                // This account will be used for the local connection to the 
                // Distributor and all agent connections that use Windows Authentication.
                publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin;
                publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword;

                // Explicitly set the security mode for the Publisher connection
                // Windows Authentication (the default).
                publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;

                // Enable Subscribers to request snapshot generation and filtering.
                publication.Attributes |= PublicationAttributes.AllowSubscriberInitiatedSnapshot;
                publication.Attributes |= PublicationAttributes.DynamicFilters;

                // Enable pull and push subscriptions.
                publication.Attributes |= PublicationAttributes.AllowPull;
                publication.Attributes |= PublicationAttributes.AllowPush;

                if (!publication.IsExistingObject)
                {
                    // Create the merge publication.
                    publication.Create();
                    
                    // Create a Snapshot Agent job for the publication.
                    publication.CreateSnapshotAgent();
                }
                else
                {
                    throw new ApplicationException(String.Format(
                        "The {0} publication already exists.", publicationName));
                }
            }

            catch (Exception ex)
            {
                // Implement custom application error handling here.
                throw new ApplicationException(String.Format(
                    "The publication {0} could not be created.", publicationName), ex);
            }
            finally
            {
                conn.Disconnect();
            }
' Set the Publisher, publication database, and publication names.
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2008R2"

Dim publicationDb As ReplicationDatabase
Dim publication As MergePublication

' Create a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(publisherName)

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

    ' Enable the database for merge publication.                
    publicationDb = New ReplicationDatabase(publicationDbName, conn)
    If publicationDb.LoadProperties() Then
        If Not publicationDb.EnabledMergePublishing Then
            publicationDb.EnabledMergePublishing = True
        End If
    Else
        ' Do something here if the database does not exist. 
        Throw New ApplicationException(String.Format( _
         "The {0} database does not exist on {1}.", _
         publicationDb, publisherName))
    End If

    ' Set the required properties for the merge publication.
    publication = New MergePublication()
    publication.ConnectionContext = conn
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName

    ' Enable precomputed partitions.
    publication.PartitionGroupsOption = PartitionGroupsOption.True

    ' Specify the Windows account under which the Snapshot Agent job runs.
    ' This account will be used for the local connection to the 
    ' Distributor and all agent connections that use Windows Authentication.
    publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin
    publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword

    ' Explicitly set the security mode for the Publisher connection
    ' Windows Authentication (the default).
    publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = True

    ' Enable Subscribers to request snapshot generation and filtering.
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowSubscriberInitiatedSnapshot
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.DynamicFilters

    ' Enable pull and push subscriptions
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowPull
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowPush

    If Not publication.IsExistingObject Then
        ' Create the merge publication.
        publication.Create()

        ' Create a Snapshot Agent job for the publication.
        publication.CreateSnapshotAgent()
    Else
        Throw New ApplicationException(String.Format( _
            "The {0} publication already exists.", publicationName))
    End If
Catch ex As Exception
    ' Implement custom application error handling here.
    Throw New ApplicationException(String.Format( _
        "The publication {0} could not be created.", publicationName), ex)
Finally
    conn.Disconnect()
End Try