Procédure : créer une publication (programmation RMO)

Vous pouvez créer des publications par programme à l'aide d'objets RMO (Replication Management Objects). Les classes RMO que vous utilisez pour créer une publication dépendent du type de publication créé.

Remarque relative à la sécuritéRemarque relative à la sécurité

Si possible, demandez aux utilisateurs de fournir les informations d'identification de sécurité au moment de l'exécution. Si vous devez stocker ces informations, utilisez les services de chiffrement fournis par Microsoft Windows .NET Framework.

Pour créer une publication transactionnelle ou de capture instantanée

  1. Créez une connexion au serveur de publication en utilisant la classe ServerConnection.

  2. Créez une instance de la classe ReplicationDatabase pour la base de données de publication, affectez à la propriété ConnectionContext l'instance de ServerConnection créée à l'étape 1, puis appelez la méthode LoadProperties. Si LoadProperties retourne false, vérifiez que la base de données existe.

  3. Si la propriété EnabledTransPublishing a la valeur false, affectez-lui la valeur true.

  4. Pour une publication transactionnelle, vérifiez la valeur de la propriété LogReaderAgentExists. Si elle a la valeur true, un travail de l'Agent de lecture du journal existe déjà pour cette base de données. Si elle a la valeur false, procédez comme suit :

  5. Créez une instance de la classe TransPublication et définissez les propriétés suivantes pour cet objet :

  6. Appelez la méthode Create pour créer la publication.

    Remarque relative à la sécuritéRemarque relative à la sécurité

     Lors de la configuration d'un serveur de publication avec un serveur de distribution distant, les valeurs fournies pour toutes les propriétés, y compris SnapshotGenerationAgentProcessSecurity, sont envoyées sous forme de texte brut au serveur de distribution. Vous devez chiffrer la connexion entre le serveur de publication et son serveur de distribution distant avant d'appeler la méthode Create. Pour plus d'informations, consultez Chiffrement des connexions à SQL Server.

  7. Appelez la méthode CreateSnapshotAgent pour créer le travail de l'Agent de capture instantanée pour le serveur de publication.

Pour créer une publication de fusion

  1. Créez une connexion au serveur de publication en utilisant la classe ServerConnection.

  2. Créez une instance de la classe ReplicationDatabase pour la base de données de publication, affectez à la propriété ConnectionContext l'instance de ServerConnection créée à l'étape 1, puis appelez la méthode LoadProperties. Si LoadProperties retourne false, vérifiez que la base de données existe.

  3. Si la propriété EnabledMergePublishing a la valeur false, affectez-lui la valeur true et appelez CommitPropertyChanges.

  4. Créez une instance de la classe MergePublication et définissez les propriétés suivantes pour cet objet :

    • La classe ServerConnection créée à l'étape 1 pour la propriété ConnectionContext.

    • Le nom de la base de données publiée pour DatabaseName.

    • Le nom de la publication pour Name.

    • Les champs Login et Password de SnapshotGenerationAgentProcessSecurity pour fournir les informations d'identification pour le compte Windows sous lequel le travail de l'Agent de capture instantanée s'exécute. Ce compte est également utilisé lorsque l'Agent de capture instantanée établit des connexions au serveur de distribution local et pour toute connexion distante lors de l'utilisation de l'authentification Windows.

      Notes

      Il n'est pas nécessaire de définir SnapshotGenerationAgentProcessSecurity lorsque la publication est créée par un membre du rôle serveur fixe sysadmin. Pour plus d'informations, consultez Modèle de sécurité de l'Agent de réplication.

    • (Facultatif) Utilisez l'opérateur OR logique inclusif (| en Visual C# et Or en Visual Basic) et l'opérateur OR logique exclusif (^ en Visual C# et Xor en Visual Basic) pour définir les valeurs PublicationAttributes de la propriété Attributes.

  5. Appelez la méthode Create pour créer la publication.

    Remarque relative à la sécuritéRemarque relative à la sécurité

     Lors de la configuration d'un serveur de publication avec un serveur de distribution distant, les valeurs fournies pour toutes les propriétés, y compris SnapshotGenerationAgentProcessSecurity, sont envoyées sous forme de texte brut au serveur de distribution. Vous devez chiffrer la connexion entre le serveur de publication et son serveur de distribution distant avant d'appeler la méthode Create. Pour plus d'informations, consultez Chiffrement des connexions à SQL Server.

  6. Appelez la méthode CreateSnapshotAgent pour créer le travail de l'Agent de capture instantanée pour le serveur de publication.

Exemple

Cet exemple active la base de données AdventureWorks pour une publication transactionnelle, définit un travail de l'Agent de lecture du journal et crée la publication AdvWorksProductTran. Un article doit être défini pour cette publication. Les informations d'identification du compte Windows nécessaires pour créer le travail de l'Agent de lecture du journal et de l'Agent de capture instantanée sont passées au moment de l'exécution. Pour savoir comment utiliser des objets RMO pour définir des articles de capture instantanée et des articles transactionnels, consultez Procédure : définir un article (programmation RMO).

            // 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

Cet exemple active la base de données AdventureWorks pour la publication de fusion et crée la publication AdvWorksSalesOrdersMerge. Des articles doivent encore être définis pour cette publication. Les informations d'identification du compte Windows nécessaires pour créer le travail de l'Agent de capture instantanée sont passées au moment de l'exécution. Pour savoir comment utiliser des objets RMO pour définir des articles de fusion, consultez Procédure : définir un article (programmation RMO).

            // 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