Procedura: Sincronizzazione di una sottoscrizione pull (programmazione RMO)

È possibile sincronizzare le sottoscrizioni pull a livello di programmazione tramite gli oggetti RMO (Replication Management Objects) e l'accesso tramite codice gestito alle funzionalità dell'agente di replica. Le classi utilizzate per la sincronizzazione di una sottoscrizione pull dipendono dal tipo di pubblicazione a cui appartiene la sottoscrizione.

[!NOTA]

Se si desidera avviare una sincronizzazione eseguita in modo autonomo senza effetti sull'applicazione, avviare l'agente in modo asincrono. Se invece si desidera monitorare i risultati della sincronizzazione e ricevere callback dall'agente durante il processo di sincronizzazione (ad esempio per la visualizzazione di una barra di stato) è necessario avviare l'agente in modo sincrono. Per i Sottoscrittori MicrosoftSQL Server 2005 Express Edition l'agente deve essere avviato in modo sincrono.

Per sincronizzare una sottoscrizione pull di una pubblicazione snapshot o transazionale

  1. Creare una connessione al Sottoscrittore tramite la classe ServerConnection.

  2. Creare un'istanza della classe TransPullSubscription e impostare le proprietà seguenti:

  3. Chiamare il metodo LoadProperties per recuperare le proprietà rimanenti della sottoscrizione. Se il metodo restituisce false, verificare che la sottoscrizione esista.

  4. Avviare l'agente di distribuzione nel Sottoscrittore in uno dei modi seguenti:

    • Chiamare il metodo SynchronizeWithJob nell'istanza di TransPullSubscription creata nel passaggio 2. Questo metodo avvia l'agente di distribuzione in modo asincrono e il controllo viene restituito immediatamente all'applicazione durante l'esecuzione del processo dell'agente. Non è possibile chiamare questo metodo per i Sottoscrittori SQL Server 2005 Express Edition se la sottoscrizione è stata creata con il valore false per CreateSyncAgentByDefault (impostazione predefinita).

    • Recuperare un'istanza della classe TransSynchronizationAgent dalla proprietà SynchronizationAgent e chiamare il metodo Synchronize. Questo metodo avvia l'agente in modo sincrono e il controllo rimane al processo dell'agente in esecuzione. Nella modalità sincrona è possibile gestire l'evento Status durante l'esecuzione dell'agente.

      [!NOTA]

      Se al momento della creazione della sottoscrizione pull è stato specificato il valore false per CreateSyncAgentByDefault (impostazione predefinita), è inoltre necessario specificare Distributor, DistributorSecurityMode e facoltativamente DistributorLogin e DistributorPassword, perché i metadati per la sottoscrizione correlati al processo dell'agente non sono disponibili in MSsubscription_properties.

Per sincronizzare una sottoscrizione pull di una pubblicazione di tipo merge

  1. Creare una connessione al Sottoscrittore tramite la classe ServerConnection.

  2. Creare un'istanza della classe MergePullSubscription e impostare le proprietà seguenti:

  3. Chiamare il metodo LoadProperties per recuperare le proprietà rimanenti della sottoscrizione. Se il metodo restituisce false, verificare che la sottoscrizione esista.

  4. Avviare l'agente di merge nel Sottoscrittore in uno dei modi seguenti:

Esempio

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione transazionale, con avvio asincrono dell'agente utilizzando il processo dell'agente.

            // Define server, publication, and database names.
            String subscriberName = subscriberInstance;
            String publisherName = publisherInstance;
            String publicationName = "AdvWorksProductTran";
            String publicationDbName = "AdventureWorks";
            String subscriptionDbName = "AdventureWorksReplica";

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

            TransPullSubscription subscription;

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

                // Define subscription properties.
                subscription = new TransPullSubscription();
                subscription.ConnectionContext = conn;
                subscription.DatabaseName = subscriptionDbName;
                subscription.PublisherName = publisherName;
                subscription.PublicationDBName = publicationDbName;
                subscription.PublicationName = publicationName;

                // If the pull subscription and the job exists, start the agent job.
                if (subscription.LoadProperties() && subscription.AgentJobId != null)
                {
                    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)
            {
                // Do appropriate error handling here.
                throw new ApplicationException("The subscription could not be synchronized.", ex);
            }
            finally
            {
                conn.Disconnect();
            }
' Define server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksProductTran"
Dim publicationDbName As String = "AdventureWorks"
Dim subscriptionDbName As String = "AdventureWorksReplica"

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

Dim subscription As TransPullSubscription

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

    ' Define subscription properties.
    subscription = New TransPullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

    ' If the pull subscription and the job exists, start the agent job.
    If subscription.LoadProperties() And Not subscription.AgentJobId Is Nothing Then
        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
    ' Do appropriate error handling here.
    Throw New ApplicationException("The subscription could not be synchronized.", ex)
Finally
    conn.Disconnect()
End Try

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione transazionale, con avvio sincrono dell'agente.

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

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

            TransPullSubscription subscription;

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

                // Define the pull subscription.
                subscription = new TransPullSubscription();
                subscription.ConnectionContext = conn;
                subscription.DatabaseName = subscriptionDbName;
                subscription.PublisherName = publisherName;
                subscription.PublicationDBName = publicationDbName;
                subscription.PublicationName = publicationName;

                // If the pull subscription exists, then start the synchronization.
                if (subscription.LoadProperties())
                {
                    // Check that we have enough metadata to start the agent.
                    if (subscription.PublisherSecurity != 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 pull subscription does not exist.
                    throw new ApplicationException(String.Format(
                        "A 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. Verify that the subscription has " +
                    "been defined correctly.", 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 = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"

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

Dim subscription As TransPullSubscription

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

    ' Define the pull subscription.
    subscription = New TransPullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

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

            ' Write agent output to a log file.
            subscription.SynchronizationAgent.Output = "distagent.log"
            subscription.SynchronizationAgent.OutputVerboseLevel = 2

            ' 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 pull subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "A 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. Verify that the subscription has " + _
     "been defined correctly.", ex)
Finally
    conn.Disconnect()
End Try

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione di tipo merge, con avvio asincrono dell'agente utilizzando il processo dell'agente.

         // Define server, publication, and database names.
            String subscriberName = subscriberInstance;
            String publisherName = publisherInstance;
            String publicationName = "AdvWorksSalesOrdersMerge";
            String publicationDbName = "AdventureWorks";
            String subscriptionDbName = "AdventureWorksReplica";

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

            MergePullSubscription subscription;

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

                // Define subscription properties.
                subscription = new MergePullSubscription();
                subscription.ConnectionContext = conn;
                subscription.DatabaseName = subscriptionDbName;
                subscription.PublisherName = publisherName;
                subscription.PublicationDBName = publicationDbName;
                subscription.PublicationName = publicationName;

                // If the pull subscription and the job exists, start the agent job.
                if (subscription.LoadProperties() && subscription.AgentJobId != null)
                {
                    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)
            {
                // Do appropriate error handling here.
                throw new ApplicationException("The subscription could not be synchronized.", ex);
            }
            finally
            {
                conn.Disconnect();
            }
' Define server, publication, and database names.
Dim subscriberName As String = subscriberInstance
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks"
Dim subscriptionDbName As String = "AdventureWorksReplica"

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

Dim subscription As MergePullSubscription

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

    ' Define subscription properties.
    subscription = New MergePullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

    ' If the pull subscription and the job exists, start the agent job.
    If subscription.LoadProperties() And Not subscription.AgentJobId Is Nothing Then
        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
    ' Do appropriate error handling here.
    Throw New ApplicationException("The subscription could not be synchronized.", ex)
Finally
    conn.Disconnect()
End Try

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione di tipo merge, con avvio sincrono dell'agente.

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

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

            MergePullSubscription subscription;

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

                // Define the pull subscription.
                subscription = new MergePullSubscription();
                subscription.ConnectionContext = conn;
                subscription.DatabaseName = subscriptionDbName;
                subscription.PublisherName = publisherName;
                subscription.PublicationDBName = publicationDbName;
                subscription.PublicationName = publicationName;

                // If the pull subscription exists, then start the synchronization.
                if (subscription.LoadProperties())
                {
                    // Check that we have enough metadata to start the agent.
                    if (subscription.PublisherSecurity != null || subscription.DistributorSecurity != 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 pull subscription does not exist.
                    throw new ApplicationException(String.Format(
                        "A 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. Verify that the subscription has " +
                    "been defined correctly.", 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 = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"

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

Dim subscription As MergePullSubscription

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

    ' Define the pull subscription.
    subscription = New MergePullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

    ' If the pull subscription exists, then start the synchronization.
    If subscription.LoadProperties() Then
        ' Check that we have enough metadata to start the agent.
        If Not subscription.PublisherSecurity Is Nothing Or subscription.DistributorSecurity Is Nothing Then

            ' Output agent messages to the console. 
            subscription.SynchronizationAgent.OutputVerboseLevel = 1
            subscription.SynchronizationAgent.Output = ""

            ' 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.")
        End If
    Else
        ' Do something here if the pull subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "A 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. Verify that the subscription has " + _
     "been defined correctly.", ex)
Finally
    conn.Disconnect()
End Try

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione di tipo merge con la sincronizzazione tramite il Web. La sottoscrizione è stata creata senza il processo dell'agente e i metadati correlati, pertanto l'agente deve essere avviato in modo sincrono e vengono fornite informazioni aggiuntive sulla sottoscrizione.

          // Define the server, publication, and database names.
            string subscriberName = subscriberInstance;
            string publisherName = publisherInstance;
            string distributorName = distributorInstance;
            string publicationName = "AdvWorksSalesOrdersMerge";
            string subscriptionDbName = "AdventureWorksReplica";
            string publicationDbName = "AdventureWorks";
            string hostname = @"adventure-works\garrett1";
            string webSyncUrl = "https://" + publisherInstance + "/SalesOrders/replisapi.dll";

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

            MergePullSubscription subscription;
            MergeSynchronizationAgent agent;

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

                // Define the pull subscription.
                subscription = new MergePullSubscription();
                subscription.ConnectionContext = conn;
                subscription.DatabaseName = subscriptionDbName;
                subscription.PublisherName = publisherName;
                subscription.PublicationDBName = publicationDbName;
                subscription.PublicationName = publicationName;

                // If the pull subscription exists, then start the synchronization.
                if (subscription.LoadProperties())
                {
                    // Get the agent for the subscription.
                    agent = subscription.SynchronizationAgent;

                    // Check that we have enough metadata to start the agent.
                    if (agent.PublisherSecurityMode == null)
                    {
                        // Set the required properties that could not be returned
                        // from the MSsubscription_properties table. 
                        agent.PublisherSecurityMode = SecurityMode.Integrated;
                        agent.DistributorSecurityMode = SecurityMode.Integrated;
                        agent.Distributor = publisherName;
                        agent.HostName = hostname;

                        // Set optional Web synchronization properties.
                        agent.UseWebSynchronization = true;
                        agent.InternetUrl = webSyncUrl;
                        agent.InternetSecurityMode = SecurityMode.Standard;
                        agent.InternetLogin = winLogin;
                        agent.InternetPassword = winPassword;
                    }
                    // Enable agent output to the console.
                    agent.OutputVerboseLevel = 1;
                    agent.Output = "";

                    // Synchronously start the Merge Agent for the subscription.
                    agent.Synchronize();
                }
                else
                {
                    // Do something here if the pull subscription does not exist.
                    throw new ApplicationException(String.Format(
                        "A 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. Verify that the subscription has " +
                    "been defined correctly.", 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 = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
Dim hostname As String = "adventure-works\garrett1"
Dim webSyncUrl As String = "https://" + publisherInstance + "/SalesOrders/replisapi.dll"

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

Dim subscription As MergePullSubscription
Dim agent As MergeSynchronizationAgent

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

    ' Define the pull subscription.
    subscription = New MergePullSubscription()
    subscription.ConnectionContext = conn
    subscription.DatabaseName = subscriptionDbName
    subscription.PublisherName = publisherName
    subscription.PublicationDBName = publicationDbName
    subscription.PublicationName = publicationName

    ' If the pull subscription exists, then start the synchronization.
    If subscription.LoadProperties() Then
        ' Get the agent for the subscription.
        agent = subscription.SynchronizationAgent

        ' Check that we have enough metadata to start the agent.
        If agent.PublisherSecurityMode = Nothing Then
            ' Set the required properties that could not be returned
            ' from the MSsubscription_properties table. 
            agent.PublisherSecurityMode = SecurityMode.Integrated
            agent.Distributor = publisherInstance
            agent.DistributorSecurityMode = SecurityMode.Integrated
            agent.HostName = hostname

            ' Set optional Web synchronization properties.
            agent.UseWebSynchronization = True
            agent.InternetUrl = webSyncUrl
            agent.InternetSecurityMode = SecurityMode.Standard
            agent.InternetLogin = winLogin
            agent.InternetPassword = winPassword
        End If

        ' Enable agent logging to the console.
        agent.OutputVerboseLevel = 1
        agent.Output = ""

        ' Synchronously start the Merge Agent for the subscription.
        agent.Synchronize()
    Else
        ' Do something here if the pull subscription does not exist.
        Throw New ApplicationException(String.Format( _
         "A 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. Verify that the subscription has " + _
     "been defined correctly.", ex)
Finally
    conn.Disconnect()
End Try