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

レプリケーション管理オブジェクト (RMO) およびマネージ コードを使用してレプリケーション エージェント機能にアクセスすることで、プッシュ サブスクリプションをプログラムから同期できます。プッシュ サブスクリプションを同期する際に使用するクラスは、サブスクリプションが属しているパブリケーションの種類によって異なります。

注意

アプリケーションに影響を及ぼすことなく、自立的に実行される同期を開始するには、エージェントを非同期的に起動します。ただし、同期処理中に同期の結果を監視し、エージェントからのコールバックを受け取る場合 (たとえば、進行状況バーを表示する場合)、エージェントを同期的に起動する必要があります。Microsoft SQL Server 2005 Express Edition サブスクライバの場合、エージェントを同期的に起動する必要があります。

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

  1. ServerConnection クラスを使用して、ディストリビュータへの接続を作成します。

  2. TransSubscription クラスのインスタンスを作成し、次のプロパティを設定します。

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

    • PublicationName に、サブスクリプションが属しているパブリケーションの名前を設定します。

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

    • SubscriberName に、サブスクリプションの名前を設定します。

    • ConnectionContext に、手順 1. で作成した接続を設定します。

  3. LoadProperties メソッドを呼び出して、その他のサブスクリプション プロパティを取得します。このメソッドが false を返す場合、サブスクリプションが存在するかどうかを確認してください。

  4. 次のいずれかの方法で、ディストリビュータのディストリビューション エージェントを起動します。

    • 手順 2. で作成した TransSubscription のインスタンスに対して SynchronizeWithJob メソッドを呼び出します。このメソッドによりディストリビューション エージェントが非同期的に起動され、エージェント ジョブの実行中に制御が直ちにアプリケーションに戻されます。CreateSyncAgentByDefault に false を使用してサブスクリプションが作成された場合、このメソッドを呼び出すことはできません。

    • SynchronizationAgent プロパティから TransSynchronizationAgent クラスのインスタンスを取得し、Synchronize メソッドを呼び出します。このメソッドにより、エージェントが同期的に起動され、制御は実行中のエージェント ジョブに残ります。同期実行の間、エージェントの実行中に Status イベントを処理できます。

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

  1. ServerConnection クラスを使用して、ディストリビュータへの接続を作成します。

  2. MergeSubscription クラスのインスタンスを作成し、次のプロパティを設定します。

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

    • PublicationName に、サブスクリプションが属しているパブリケーションの名前を設定します。

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

    • SubscriberName に、サブスクリプションの名前を設定します。

    • ConnectionContext に、手順 1. で作成した接続を設定します。

  3. LoadProperties メソッドを呼び出して、その他のサブスクリプション プロパティを取得します。このメソッドが false を返す場合、サブスクリプションが存在するかどうかを確認してください。

  4. 次のいずれかの方法で、ディストリビュータのマージ エージェントを起動します。

    • 手順 2. で作成した MergeSubscription のインスタンスに対して SynchronizeWithJob メソッドを呼び出します。このメソッドによりマージ エージェントが非同期的に起動され、エージェント ジョブの実行中に制御が直ちにアプリケーションに戻されます。CreateSyncAgentByDefault に false を使用してサブスクリプションが作成された場合、このメソッドを呼び出すことはできません。

    • SynchronizationAgent プロパティから MergeSynchronizationAgent クラスのインスタンスを取得し、Synchronize メソッドを呼び出します。このメソッドにより、マージ エージェントが同期的に起動され、制御は実行中のエージェント ジョブに残ります。同期実行の間、エージェントの実行中に Status イベントを処理できます。

使用例

次の例では、トランザクション パブリケーションへのプッシュ サブスクリプションを同期します。エージェントはエージェント ジョブを使用して非同期的に起動されます。

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

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

            TransSubscription subscription;

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

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

                // If the push subscription and the job exists, start the agent job.
                if (subscription.LoadProperties() && subscription.AgentJobId != null)
                {
                    // Start the Distribution Agent asynchronously.
                    subscription.SynchronizeWithJob();
                }
                else
                {
                    // Do something here if the subscription does not exist.
                    throw new ApplicationException(String.Format(
                        "A subscription to '{0}' does not exists on {1}",
                        publicationName, subscriberName));
                }
            }
            catch (Exception ex)
            {
                // Implement appropriate error handling here.
                throw new ApplicationException("The subscription could not be synchronized.", ex);
            }
            finally
            {
                conn.Disconnect();
            }
' Define the server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksProductTran"
Dim subscriptionDbName As String = "AdventureWorks2008R2Replica"
Dim publicationDbName As String = "AdventureWorks2008R2"

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

Dim subscription As TransSubscription

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

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

    ' If the push subscription and the job exists, start the agent job.
    If subscription.LoadProperties() And Not subscription.AgentJobId Is Nothing Then
        ' Start the Distribution Agent asynchronously.
        subscription.SynchronizeWithJob()
    Else
        ' Do something here if the subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "A subscription to '{0}' does not exists on {1}", _
         publicationName, subscriberName))
    End If
Catch ex As Exception
    ' Implement appropriate error handling here.
    Throw New ApplicationException("The subscription could not be synchronized.", ex)
Finally
    conn.Disconnect()
End Try

次の例では、トランザクション パブリケーションへのプッシュ サブスクリプションを同期します。エージェントは同期的に起動されます。

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

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

            TransSubscription subscription;

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

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

                // If the push subscription exists, start the synchronization.
                if (subscription.LoadProperties())
                {
                    // Check that we have enough metadata to start the agent.
                    if (subscription.SubscriberSecurity != null)
                    {
                        // Synchronously start the Distribution Agent for the subscription.
                        subscription.SynchronizationAgent.Synchronize();
                    }
                    else
                    {
                        throw new ApplicationException("There is insufficent metadata to " +
                            "synchronize the subscription. Recreate the subscription with " +
                            "the agent job or supply the required agent properties at run time.");
                    }
                }
                else
                {
                    // Do something here if the push subscription does not exist.
                    throw new ApplicationException(String.Format(
                        "The subscription to '{0}' does not exist on {1}",
                        publicationName, subscriberName));
                }
            }
            catch (Exception ex)
            {
                // Implement appropriate error handling here.
                throw new ApplicationException("The subscription could not be synchronized.", ex);
            }
            finally
            {
                conn.Disconnect();
            }
' Define the server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksProductTran"
Dim subscriptionDbName As String = "AdventureWorks2008R2Replica"
Dim publicationDbName As String = "AdventureWorks2008R2"

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

Dim subscription As TransSubscription

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

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

    ' If the push subscription exists, start the synchronization.
    If subscription.LoadProperties() Then
        ' Check that we have enough metadata to start the agent.
        If Not subscription.SubscriberSecurity Is Nothing Then

            ' Synchronously start the Distribution Agent for the subscription.
            subscription.SynchronizationAgent.Synchronize()
        Else
            Throw New ApplicationException("There is insufficent metadata to " + _
             "synchronize the subscription. Recreate the subscription with " + _
             "the agent job or supply the required agent properties at run time.")
        End If
    Else
        ' Do something here if the push subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "The subscription to '{0}' does not exist on {1}", _
         publicationName, subscriberName))
    End If
Catch ex As Exception
    ' Implement appropriate error handling here.
    Throw New ApplicationException("The subscription could not be synchronized.", ex)
Finally
    conn.Disconnect()
End Try

次の例では、マージ パブリケーションへのプッシュ サブスクリプションを同期します。エージェントはエージェント ジョブを使用して非同期的に起動されます。

         // Define the server, publication, and database names.
            string subscriberName = subscriberInstance;
            string publisherName = publisherInstance;
            string publicationName = "AdvWorksSalesOrdersMerge";
            string subscriptionDbName = "AdventureWorks2008R2Replica";
            string publicationDbName = "AdventureWorks2008R2";

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

            MergeSubscription subscription;

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

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

                // If the push subscription and the job exists, start the agent job.
                if (subscription.LoadProperties() && subscription.AgentJobId != null)
                {
                    // Start the Merge Agent asynchronously.
                    subscription.SynchronizeWithJob();
                }
                else
                {
                    // Do something here if the subscription does not exist.
                    throw new ApplicationException(String.Format(
                        "A subscription to '{0}' does not exists on {1}",
                        publicationName, subscriberName));
                }
            }
            catch (Exception ex)
            {
                // Implement appropriate error handling here.
                throw new ApplicationException("The subscription could not be synchronized.", ex);
            }
            finally
            {
                conn.Disconnect();
            }
' Define the server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim subscriptionDbName As String = "AdventureWorks2008R2Replica"
Dim publicationDbName As String = "AdventureWorks2008R2"

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

Dim subscription As MergeSubscription

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

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

    ' If the push subscription and the job exists, start the agent job.
    If subscription.LoadProperties() And Not subscription.AgentJobId Is Nothing Then
        ' Start the Merge Agent asynchronously.
        subscription.SynchronizeWithJob()
    Else
        ' Do something here if the subscription does not exist.
        Throw New ApplicationException(String.Format( _
            "A subscription to '{0}' does not exists on {1}", _
            publicationName, subscriberName))
    End If
Catch ex As Exception
    ' Implement appropriate error handling here.
    Throw New ApplicationException("The subscription could not be synchronized.", ex)
Finally
    conn.Disconnect()
End Try

次の例では、マージ パブリケーションへのプッシュ サブスクリプションを同期します。エージェントは同期的に起動されます。

         // Define the server, publication, and database names.
            string subscriberName = subscriberInstance;
            string publisherName = publisherInstance;
            string publicationName = "AdvWorksSalesOrdersMerge";
            string subscriptionDbName = "AdventureWorks2008R2Replica";
            string publicationDbName = "AdventureWorks2008R2";

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

            MergeSubscription subscription;

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

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

                // If the push subscription exists, start the synchronization.
                if (subscription.LoadProperties())
                {
                    // Check that we have enough metadata to start the agent.
                    if (subscription.SubscriberSecurity != null)
                    {
                        // Synchronously start the Merge Agent for the subscription.
                        subscription.SynchronizationAgent.Synchronize();
                    }
                    else
                    {
                        throw new ApplicationException("There is insufficent metadata to " +
                            "synchronize the subscription. Recreate the subscription with " +
                            "the agent job or supply the required agent properties at run time.");
                    }
                }
                else
                {
                    // Do something here if the push subscription does not exist.
                    throw new ApplicationException(String.Format(
                        "The subscription to '{0}' does not exist on {1}",
                        publicationName, subscriberName));
                }
            }
            catch (Exception ex)
            {
                // Implement appropriate error handling here.
                throw new ApplicationException("The subscription could not be synchronized.", ex);
            }
            finally
            {
                conn.Disconnect();
            }
' Define the server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim subscriptionDbName As String = "AdventureWorks2008R2Replica"
Dim publicationDbName As String = "AdventureWorks2008R2"

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

Dim subscription As MergeSubscription

Try
    ' Connect to the Publisher
    conn.Connect()

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

    ' If the push subscription exists, start the synchronization.
    If subscription.LoadProperties() Then
        ' Check that we have enough metadata to start the agent.
        If Not subscription.SubscriberSecurity Is Nothing Then
            ' Synchronously start the Merge Agent for the subscription.
            ' Log agent messages to an output file.
            subscription.SynchronizationAgent.Output = "mergeagent.log"
            subscription.SynchronizationAgent.OutputVerboseLevel = 2
            subscription.SynchronizationAgent.Synchronize()
        Else
            Throw New ApplicationException("There is insufficent metadata to " + _
             "synchronize the subscription. Recreate the subscription with " + _
             "the agent job or supply the required agent properties at run time.")
        End If
    Else
        ' Do something here if the push subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "The subscription to '{0}' does not exist on {1}", _
         publicationName, subscriberName))
    End If
Catch ex As Exception
    ' Implement appropriate error handling here.
    Throw New ApplicationException("The subscription could not be synchronized.", ex)
Finally
    conn.Disconnect()
End Try