Share via


パブリケーションを作成する方法 (RMO プログラミング)

レプリケーション管理オブジェクト (RMO) を使用することで、プログラムによってパブリケーションを作成できます。パブリケーションの作成に使用する RMO クラスは、作成するパブリケーションの種類によって異なります。

セキュリティに関する注意セキュリティに関する注意

可能であれば、実行時にセキュリティ資格情報の入力を求めるメッセージを表示します。資格情報を保存する必要がある場合は、Microsoft Windows .NET Framework に用意されている暗号化サービスを使用します。

スナップショット パブリケーションまたはトランザクション パブリケーションを作成するには

  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 クラスのインスタンスを作成し、このオブジェクトに次のプロパティを設定します。

    • 手順 1. の ServerConnectionConnectionContext に指定します。

    • パブリッシュするデータベースの名前を DatabaseName に指定します。

    • Name にパブリケーションの名前を指定します。

    • SnapshotGenerationAgentProcessSecurityLogin フィールドおよび Password フィールドに、スナップショット エージェントの実行に使用する Windows アカウントの資格情報を指定します。このアカウントは、Windows 認証を使用している場合に、スナップショット エージェントがローカル ディストリビュータへの接続や任意のリモート接続を行うときにも使用されます。

      注意

      パブリケーションが sysadmin 固定サーバー ロールのメンバにより作成される場合、SnapshotGenerationAgentProcessSecurity の設定は不要です。詳細については、「レプリケーション エージェントのセキュリティ モデル」を参照してください。

    • (省略可) 包括的論理和演算子 (Visual C# では |、Visual Basic では Or) および排他的論理和演算子 (Visual C# では ^、Visual Basic では Xor) を使用して、Attributes プロパティに PublicationAttributes の値を設定します。

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

次の例では、AdventureWorks データベースでマージ パブリッシュを有効にし、AdvWorksSalesOrdersMerge パブリケーションを作成します。このパブリケーションには、アーティクルを定義する必要があります。スナップショット エージェント ジョブの作成に必要な Windows アカウントの資格情報は、実行時に渡されます。RMO を使用してマージ アーティクルを定義する方法については、「アーティクルを定義する方法 (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