Como sincronizar uma assinatura push (Programação RMO)

É possível sincronizar as assinaturas push programaticamente usando o RMO (Replication Management Objects) e o acesso de código gerenciado para as funcionalidades do agente de replicação. As classes usadas para sincronizar uma assinatura push dependem do tipo de publicação ao qual a assinatura pertence.

ObservaçãoObservação

Se quiser iniciar uma sincronização que executa de forma autônoma sem afetar seu aplicativo, inicie o agente em modo assíncrono. Porém, se quiser monitorar o resultado da sincronização e receber retornos de chamada do agente durante o processo de sincronização (por exemplo, se quiser exibir a barra de andamento), inicie o agente de forma síncrona. Para os Assinantes da Microsoft SQL Server 2005 Express Edition, você deve iniciar o agente de forma síncrona.

Para sincronizar uma assinatura push a um instantâneo ou publicação transacional

  1. Crie uma conexão com o Distribuidor usando a classe ServerConnection.

  2. Crie uma instância da classe TransSubscription e defina as propriedades a seguir:

  3. Chame o método LoadProperties para obter as demais propriedades da assinatura. Se este método retornar false, verifique se a assinatura existe.

  4. Inicie o Distribution Agent no Distribuidor de uma das seguintes maneiras:

    • Chame o método SynchronizeWithJob na instância de TransSubscription da etapa 2. Este método inicia o Distribution Agent de forma assíncrona e o controle retorna imediatamente para o seu aplicativo com o trabalho do agente em execução. Você não poderá chamar este método se a assinatura foi criada com um valor de false para CreateSyncAgentByDefault.

    • Obtenha uma instância de classe TransSynchronizationAgent da propriedade SynchronizationAgent e chame o método Synchronize. Este método inicia o agente de forma síncrona e o controle permanece com o trabalho do agente em execução. Durante a execução síncrona você pode manipular o evento Status com o agente em execução.

Para sincronizar uma assinatura push a uma publicação de mesclagem

  1. Crie uma conexão com o Distribuidor usando a classe ServerConnection.

  2. Crie uma instância de classe MergeSubscription e defina as propriedades a seguir:

  3. Chame o método LoadProperties para obter as demais propriedades da assinatura. Se este método retornar false, verifique se a assinatura existe.

  4. Inicie o Merge Agent no Distribuidor de uma das seguintes maneiras:

    • Chame o método SynchronizeWithJob na instância de MergeSubscription da etapa 2. Este método inicia o Merge Agent de forma assíncrona e o controle retorna imediatamente para o seu aplicativo com o trabalho do agente em execução. Você não poderá chamar este método se a assinatura foi criada com um valor de false para CreateSyncAgentByDefault.

    • Obtenha uma instância de classe MergeSynchronizationAgent da propriedade SynchronizationAgent e chame o método Synchronize. Este método inicia o Merge Agent de forma síncrona e o controle permanece com o trabalho do agente em execução. Durante execução síncrona, você pode manipular o evento Status com o agente em execução.

Exemplo

Este exemplo sincroniza a assinatura push a uma publicação transacional, onde o agente é iniciado de forma assíncrona usando o trabalho do agente.

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

Este exemplo sincroniza a assinatura push a uma publicação transacional, onde o agente é iniciado de forma síncrona.

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

Este exemplo sincroniza a assinatura push a uma publicação de mesclagem, onde o agente é iniciado de forma assíncrona usando o trabalho do agente.

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

Este exemplo sincroniza a assinatura push a uma publicação de mesclagem, onde o agente é iniciado de forma síncrona.

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