如何创建发布(RMO 编程)

通过使用复制管理对象 (RMO),能够以编程方式创建发布。 用于创建发布的 RMO 类取决于所创建发布的类型。

安全说明安全说明

如果可能,请在运行时提示用户输入安全凭据。 如果必须存储凭据,请使用 Microsoft Windows .NET Framework 提供的 Cryptographic Services(加密服务)。

创建快照发布或事务发布

  1. 使用 ServerConnection 类创建与发布服务器的连接。

  2. 为发布数据库创建 ReplicationDatabase 类的实例,将 ConnectionContext 属性设置为步骤 1 中的 ServerConnection 的实例,然后调用 LoadProperties 方法。 如果 LoadProperties 返回 false,请验证该数据库是否存在。

  3. 如果 EnabledTransPublishing 属性为 false,请将其设置为 true。

  4. 对于事务发布,请检查 LogReaderAgentExists 属性的值。 如果该属性为 true,说明已经存在一个针对此数据库的日志读取器代理作业。 如果该属性为 false,请执行如下操作:

  5. 创建 TransPublication 类的实例,并设置此对象的以下属性:

  6. 调用 Create 方法来创建发布。

    安全说明安全说明

     在使用远程分发服务器配置发布服务器时,为所有属性提供的值(包括 SnapshotGenerationAgentProcessSecurity)都会以纯文本形式发送到该分发服务器。 在调用 Create 方法之前,应该对发布服务器与其远程分发服务器之间的连接进行加密。 有关详细信息,请参阅加密与 SQL Server 的连接

  7. 调用 CreateSnapshotAgent 方法,为发布创建快照代理作业。

创建合并发布

  1. 使用 ServerConnection 类创建与发布服务器的连接。

  2. 为发布数据库创建 ReplicationDatabase 类的实例,将 ConnectionContext 属性设置为步骤 1 中的 ServerConnection 的实例,然后调用 LoadProperties 方法。 如果 LoadProperties 返回 false,请验证该数据库是否存在。

  3. 如果 EnabledMergePublishing 属性为 false,请将其设置为 true,然后调用 CommitPropertyChanges

  4. 创建 MergePublication 类的实例,并设置此对象的以下属性:

  5. 调用 Create 方法来创建发布。

    安全说明安全说明

     在使用远程分发服务器配置发布服务器时,为所有属性提供的值(包括 SnapshotGenerationAgentProcessSecurity)都会以纯文本形式发送到该分发服务器。 在调用 Create 方法之前,应该对发布服务器与其远程分发服务器之间的连接进行加密。 有关详细信息,请参阅加密与 SQL Server 的连接

  6. 调用 CreateSnapshotAgent 方法,为发布创建快照代理作业。

示例

本例将 AdventureWorks 数据库设置为支持事务发布,定义了一个日志读取器代理作业,并且创建了 AdvWorksProductTran 发布。 必须为此发布定义一个项目。 创建日志读取器代理作业和快照代理作业所需的 Windows 帐户凭据在运行时进行传递。 若要了解如何使用 RMO 定义快照项目和事务项目,请参阅如何定义项目(RMO 编程)

         // Set the Publisher, publication database, and publication names.
            string publicationName = "AdvWorksProductTran";
            string publicationDbName = "AdventureWorks";
            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 = "AdventureWorks"
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

本例将 AdventureWorks 数据库设置为支持合并发布,并且创建了 AdvWorksSalesOrdersMerge 发布。 仍然必须为此发布定义项目。 创建快照代理作业所需的 Windows 帐户凭据在运行时进行传递。 若要了解如何使用 RMO 定义合并项目,请参阅如何定义项目(RMO 编程)

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

            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 = "AdventureWorks"

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