プッシュ サブスクリプションを作成する方法 (RMO プログラミング)

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

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

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

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

  1. ServerConnection クラスを使用して、パブリッシャへの接続を作成します。

  2. 手順 1. のパブリッシャ接続を使用して、TransPublication クラスのインスタンスを作成します。NameDatabaseName、および ConnectionContext を指定します。

  3. LoadProperties メソッドを呼び出します。このメソッドが false を返す場合、手順 2. で指定したプロパティが誤っているか、サーバーにパブリケーションが存在していません。

  4. Attributes プロパティと AllowPush のビットごとの論理積演算 (Visual C# では &、Visual Basic では And) を実行します。結果が None の場合、AttributesAllowPush のビットごとの論理和演算 (Visual C# では |、Visual Basic では Or) の結果を Attributes に設定します。次に、CommitPropertyChanges を呼び出してプッシュ サブスクリプションを有効にします。

  5. サブスクリプション データベースが存在しない場合は、Database クラスを使用して作成します。詳細については、「データベースの作成、変更、および削除」を参照してください。

  6. TransSubscription クラスのインスタンスを作成します。

  7. 次のサブスクリプション プロパティを設定します。

    • 手順 1. で作成した、パブリッシャに対する ServerConnectionConnectionContext に指定します。

    • サブスクリプション データベース名を SubscriptionDBName に指定します。

    • サブスクライバ名を SubscriberName に指定します。

    • パブリケーション データベース名を DatabaseName に指定します。

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

    • SynchronizationAgentProcessSecurityLogin フィールドおよび Password (または SecurePassword) フィールド。これにより、ディストリビュータでディストリビューション エージェントを実行するときに使用される Microsoft Windows アカウントの資格情報が得られます。このアカウントは、ディストリビュータとのローカル接続を確立したり、Windows 認証を使用したリモート接続を確立するときに使用されます。

      注意

      サブスクリプションが sysadmin 固定サーバー ロールのメンバにより作成される場合、SynchronizationAgentProcessSecurity の設定は必須ではありませんが、推奨されます。この場合、エージェントは SQL Server エージェントのアカウントを借用します。詳細については、「レプリケーション エージェントのセキュリティ モデル」を参照してください。

    • (省略可) サブスクリプションを同期するために使用されるエージェント ジョブを作成する場合は、CreateSyncAgentByDefault に true (既定値) を指定します。false を指定した場合、サブスクリプションはプログラムでのみ同期が可能になります。

    • (省略可) SQL Server 認証を使用してサブスクライバに接続する場合、SubscriberSecuritySqlStandardLogin フィールドおよび SqlStandardPassword (または SecureSqlStandardPassword) フィールドを設定します。

  8. Create メソッドを呼び出します。

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

    リモート ディストリビュータを使用するパブリッシャ側でプッシュ サブスクリプションを作成する場合は、SynchronizationAgentProcessSecurity を含むすべてのプロパティに指定された値がディストリビュータにプレーン テキストとして送信されます。Create メソッドを呼び出す前に、パブリッシャとそのリモート ディストリビュータ間の接続を暗号化する必要があります。詳細については、「SQL Server への接続の暗号化」を参照してください。

マージ パブリケーションに対するプッシュ サブスクリプションを作成するには

  1. ServerConnection クラスを使用して、パブリッシャへの接続を作成します。

  2. 手順 1. のパブリッシャ接続を使用して、MergePublication クラスのインスタンスを作成します。NameDatabaseName、および ConnectionContext を指定します。

  3. LoadProperties メソッドを呼び出します。このメソッドが false を返す場合、手順 2. で指定したプロパティが誤っているか、サーバーにパブリケーションが存在していません。

  4. Attributes プロパティと AllowPush のビットごとの論理積演算 (Visual C# では &、Visual Basic では And) を実行します。結果が None の場合、AttributesAllowPush のビットごとの論理和演算 (Visual C# では |、Visual Basic では Or) の結果を Attributes に設定します。次に、CommitPropertyChanges を呼び出してプッシュ サブスクリプションを有効にします。

  5. サブスクリプション データベースが存在しない場合は、Database クラスを使用して作成します。詳細については、「データベースの作成、変更、および削除」を参照してください。

  6. MergeSubscription クラスのインスタンスを作成します。

  7. 次のサブスクリプション プロパティを設定します。

  8. Create メソッドを呼び出します。

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

    リモート ディストリビュータを使用するパブリッシャ側でプッシュ サブスクリプションを作成する場合は、SynchronizationAgentProcessSecurity を含むすべてのプロパティに指定された値がディストリビュータにプレーン テキストとして送信されます。Create メソッドを呼び出す前に、パブリッシャとそのリモート ディストリビュータ間の接続を暗号化する必要があります。詳細については、「SQL Server への接続の暗号化」を参照してください。

使用例

次の例では、トランザクション パブリケーションに対する新しいプッシュ サブスクリプションを作成します。ディストリビューション エージェント ジョブを実行するために使用される Windows アカウントの資格情報は、実行時に渡されます。

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

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

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

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

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

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

                    // Define the push subscription.
                    subscription = new TransSubscription();
                    subscription.ConnectionContext = conn;
                    subscription.SubscriberName = subscriberName;
                    subscription.PublicationName = publicationName;
                    subscription.DatabaseName = publicationDbName;
                    subscription.SubscriptionDBName = subscriptionDbName;

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

                    // 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 push subscription.
                    subscription.Create();
                }
                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
            {
                conn.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 = "AdventureWorks2008R2Replica"
Dim publicationDbName As String = "AdventureWorks2008R2"

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

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

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

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

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

        ' Define the push subscription.
        subscription = New TransSubscription()
        subscription.ConnectionContext = conn
        subscription.SubscriberName = subscriberName
        subscription.PublicationName = publicationName
        subscription.DatabaseName = publicationDbName
        subscription.SubscriptionDBName = subscriptionDbName

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

        ' 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 push subscription.
        subscription.Create()
    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
    conn.Disconnect()
End Try

次の例では、マージ パブリケーションに対する新しいプッシュ サブスクリプションを作成します。マージ エージェント ジョブを実行するために使用される Windows アカウントの資格情報は、実行時に渡されます。

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

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

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

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

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

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

                    // Define the push subscription.
                    subscription = new MergeSubscription();
                    subscription.ConnectionContext = conn;
                    subscription.SubscriberName = subscriberName;
                    subscription.PublicationName = publicationName;
                    subscription.DatabaseName = publicationDbName;
                    subscription.SubscriptionDBName = subscriptionDbName;
                    subscription.HostName = hostname;

                    // Set a schedule to synchronize the subscription every 2 hours
                    // during weekdays from 6am to 10pm.
                    subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Weekly;
                    subscription.AgentSchedule.FrequencyInterval = Convert.ToInt32(0x003E);
                    subscription.AgentSchedule.FrequencyRecurrenceFactor = 1;
                    subscription.AgentSchedule.FrequencySubDay = ScheduleFrequencySubDay.Hour;
                    subscription.AgentSchedule.FrequencySubDayInterval = 2;
                    subscription.AgentSchedule.ActiveStartDate = 20051108;
                    subscription.AgentSchedule.ActiveEndDate = 20071231;
                    subscription.AgentSchedule.ActiveStartTime = 060000;
                    subscription.AgentSchedule.ActiveEndTime = 100000;

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

                    // Create the push subscription.
                    subscription.Create();
                }
                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
            {
                conn.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 = "AdventureWorks2008R2Replica"
Dim publicationDbName As String = "AdventureWorks2008R2"
Dim hostname As String = "adventure-works\garrett1"

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

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

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

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

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

        ' Define the push subscription.
        subscription = New MergeSubscription()
        subscription.ConnectionContext = conn
        subscription.SubscriberName = subscriberName
        subscription.PublicationName = publicationName
        subscription.DatabaseName = publicationDbName
        subscription.SubscriptionDBName = subscriptionDbName
        subscription.HostName = hostname

        ' Set a schedule to synchronize the subscription every 2 hours
        ' during weekdays from 6am to 10pm.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Weekly
        subscription.AgentSchedule.FrequencyInterval = Convert.ToInt32("0x003E", 16)
        subscription.AgentSchedule.FrequencyRecurrenceFactor = 1
        subscription.AgentSchedule.FrequencySubDay = ScheduleFrequencySubDay.Hour
        subscription.AgentSchedule.FrequencySubDayInterval = 2
        subscription.AgentSchedule.ActiveStartDate = 20051108
        subscription.AgentSchedule.ActiveEndDate = 20071231
        subscription.AgentSchedule.ActiveStartTime = 60000
        subscription.AgentSchedule.ActiveEndTime = 100000

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

        ' Create the push subscription.
        subscription.Create()
    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
    conn.Disconnect()
End Try