Поделиться через


Синхронизация подписки по запросу

В данном разделе описывается синхронизация подписки по запросу в SQL Server 2012 с помощью среды Среда SQL Server Management Studio, агентов репликации или объектов RMO.

В этом разделе

  • Для синхронизации подписки по запросу используется:

    Среда SQL Server Management Studio

    Агенты репликации

    объекты RMO;

Использование среды SQL Server Management Studio

Подписки синхронизируются агентом распространителя (для репликации моментальных снимков и репликации транзакций) или агентом слияния (для репликации слиянием). Агенты могут работать непрерывно, запускаться по запросу или по расписанию. Дополнительные сведения об указании расписаний синхронизации см. в разделе Указание расписаний синхронизации.

Синхронизируйте подписку по запросу из папки Локальные подписки в среде Среда SQL Server Management Studio.

Синхронизация по запросу подписки по запросу в среде Management Studio

  1. Подключитесь к подписчику в среде Среда Management Studio и раскройте узел сервера.

  2. Раскройте папку Репликация, а затем — папку Локальные подписки.

  3. Щелкните подписку правой кнопкой мыши и выберите Просмотреть состояние синхронизации.

  4. В диалоговом окне Просмотр состояния синхронизации — <подписчик>:<база данных подписки> нажмите кнопку Пуск. Когда синхронизация будет завершена, появится сообщение Синхронизация завершена.

  5. Нажмите кнопку Закрыть.

Значок стрелки, используемый со ссылкой «В начало»[Top]

Агенты репликации

Подписки по запросу могут синхронизироваться программно и по требованию, с помощью вызова из командной строки нужного исполняемого файла агента репликации. Вызываемый исполняемый файл агента репликации зависит от типа публикации, к которой принадлежит подписка по запросу. Дополнительные сведения см. в разделе Агенты репликации.

ПримечаниеПримечание

Агенты репликации подключаются к локальному серверу, используя учетные данные проверки подлинности Windows пользователя, запустившего агент из командной строки. Эти учетные данные Windows также применяются при соединении с удаленными серверами с использованием встроенной проверки подлинности Windows.

Запуск агента распространителя из командной строки или из пакетного файла

  • Из командной строки или из пакетного файла запустите агент распространения репликации, вызвав программу distrib.exe со следующими параметрами командной строки.

    • -Publisher

    • -PublisherDB

    • -Distributor

    • -DistributorSecurityMode = 1

    • -Subscriber

    • -SubscriberDB

    • -SubscriberSecurityMode = 1

    • -SubscriptionType = 1

    При использовании проверки подлинности SQL Server необходимо также указать следующие аргументы.

    • -DistributorLogin

    • -DistributorPassword

    • -DistributorSecurityMode = 0

    • -PublisherLogin

    • -PublisherPassword

    • -PublisherSecurityMode = 0

    • -SubscriberLogin

    • -SubscriberPassword

    • -SubscriberSecurityMode = 0

Запуск агента слияния из командной строки или из пакетного файла

  • Из командной строки или из пакетного файла запустите агент слияния репликации, вызвав программу replmerg.exe со следующими параметрами командной строки.

    • -Publisher

    • -PublisherDB

    • -PublisherSecurityMode = 1

    • -Publication

    • -Distributor

    • -DistributorSecurityMode = 1

    • -Subscriber

    • -SubscriberSecurityMode = 1

    • -SubscriberDB

    • -SubscriptionType = 1

    При использовании проверки подлинности SQL Server необходимо также указать следующие аргументы.

    • -DistributorLogin

    • -DistributorPassword

    • -DistributorSecurityMode = 0

    • -PublisherLogin

    • -PublisherPassword

    • -PublisherSecurityMode = 0

    • -SubscriberLogin

    • -SubscriberPassword

    • -SubscriberSecurityMode = 0

Примеры (агенты репликации)

В следующем примере запускается агент распространителя для синхронизации подписки по запросу. Все соединения устанавливаются с использованием проверки подлинности Windows.

REM -- Declare the variables.
SET Publisher=%instancename%
SET Subscriber=%instancename%
SET PublicationDB=AdventureWorks2012
SET SubscriptionDB=AdventureWorks2012Replica 
SET Publication=AdvWorksProductsTran

REM -- Start the Distribution Agent.
REM -- The following command must be supplied without line breaks.
"C:\Program Files\Microsoft SQL Server\110\COM\DISTRIB.EXE" -Subscriber %Subscriber% 
-SubscriberDB %SubscriptionDB% -SubscriberSecurityMode 1 -Publication %Publication% 
-Publisher %Publisher% -PublisherDB %PublicationDB% -Distributor %Publisher% 
-DistributorSecurityMode 1 -Continuous -SubscriptionType 1

В следующем примере запускается агент слияния для синхронизации подписки по запросу. Все соединения устанавливаются с использованием проверки подлинности Windows.

REM -- Declare the variables.
SET Publisher=%instancename%
SET Subscriber=%instancename%
SET PublicationDB=AdventureWorks2012
SET SubscriptionDB=AdventureWorks2012Replica 
SET Publication=AdvWorksSalesOrdersMerge

REM --Start the Merge Agent with concurrent upload and download processes.
REM -- The following command must be supplied without line breaks.
"C:\Program Files\Microsoft SQL Server\110\COM\REPLMERG.EXE" -Publication %Publication%  
-Publisher %Publisher%  -Subscriber  %Subscriber%  -Distributor %Publisher%  
-PublisherDB %PublicationDB%  -SubscriberDB %SubscriptionDB% -PublisherSecurityMode 1  
-OutputVerboseLevel 2  -SubscriberSecurityMode 1  -SubscriptionType 1 -DistributorSecurityMode 1  
-Validate 3  -ParallelUploadDownload 1 

Значок стрелки, используемый со ссылкой «В начало»[Top]

При помощи объектов RMO

Подписки по запросу можно синхронизировать программно с помощью объектов RMO и доступа к функциональности агента репликации из управляемого кода. Конкретные классы, используемые для синхронизации, зависят от типа публикации, к которой принадлежит подписка.

ПримечаниеПримечание

Если нужно выполнить синхронизацию, которая выполняется автономно и не влияет на ваше приложение, запустите агент асинхронно. Однако если нужно наблюдать за результатами синхронизации и получать обратные вызовы от агента во время процесса синхронизации (например, если нужно отображать индикатор выполнения), то следует запускать агент синхронно. Для подписчиков Microsoft SQL Server 2005 Express Edition также необходимо запускать агент синхронно.

Синхронизация подписки по запросу на публикацию моментальных снимков или транзакций

  1. Создайте соединение с подписчиком с помощью класса ServerConnection.

  2. Создайте экземпляр класса TransPullSubscription и укажите следующие свойства:

    • имя базы данных подписки в свойстве DatabaseName;

    • имя публикации, к которой принадлежит подписка, в свойстве PublicationName;

    • имя базы данных публикации в свойстве PublicationDBName;

    • имя издателя в свойстве PublisherName;

    • соединение, созданное на шаге 1, в свойстве ConnectionContext.

  3. Вызовите метод LoadProperties, чтобы получить остальные свойства подписки. Если этот метод возвращает значение false, проверьте, существует ли подписка.

  4. На распространителе запустите агент распространителя одним из следующих способов.

    • Вызовите метод SynchronizeWithJob экземпляра класса TransPullSubscription, созданного на шаге 2. Этот метод запускает агент распространителя асинхронно, а управление сразу после его вызова передается обратно приложению; задание агента при этом продолжает выполняться. Этот метод нельзя вызывать для подписчиков SQL Server 2005 Express Edition, а так же в том случае, если подписка была создана со значением false свойства CreateSyncAgentByDefault (значение по умолчанию).

    • Получите экземпляр класса TransSynchronizationAgent из свойства SynchronizationAgent и вызовите метод Synchronize. Этот метод запускает агент синхронно, и управление не возвращается приложению до тех пор, пока выполнение задания агента не будет завершено. При синхронном выполнении в процессе работы агента можно обрабатывать событие Status.

      ПримечаниеПримечание

      Если при создании подписки по запросу указано значение false свойства CreateSyncAgentByDefault (значение по умолчанию), необходимо также указать свойства Distributor, DistributorSecurityMode, а при необходимости также и свойствоDistributorLogin и DistributorPassword, так как метаданные подписки, относящиеся к заданию агента, в таблице MSsubscription_properties недоступны.

Синхронизация подписки по запросу на публикацию слиянием

  1. Создайте соединение с подписчиком с помощью класса ServerConnection.

  2. Создайте экземпляр класса MergePullSubscription и укажите следующие свойства:

    • имя базы данных подписки в свойстве DatabaseName;

    • имя публикации, к которой принадлежит подписка, в свойстве PublicationName;

    • имя опубликованной базы данных в свойстве PublicationDBName;

    • имя издателя в свойстве PublisherName;

    • соединение, созданное на шаге 1, в свойстве ConnectionContext.

  3. Вызовите метод LoadProperties, чтобы получить остальные свойства подписки. Если этот метод возвращает значение false, проверьте, существует ли подписка.

  4. На подписчике запустите агент слияния одним из следующих способов:.

    • Вызовите метод SynchronizeWithJob экземпляра класса MergePullSubscription, созданного на шаге 2. Этот метод запускает агент слияния асинхронно, а управление сразу после его вызова передается обратно приложению, задание агента при этом продолжает выполняться. Этот метод нельзя вызывать для подписчиков SQL Server 2005 Express Edition, а так же в том случае, если подписка была создана со значением false свойства CreateSyncAgentByDefault (значение по умолчанию).

    • Получите экземпляр класса MergeSynchronizationAgent из свойства SynchronizationAgent и вызовите метод Synchronize. Этот метод запускает агент слияния синхронно, и управление не возвращается приложению до тех пор, пока не будет закончено выполнение задания агента. При синхронном выполнении в процессе работы агента можно обрабатывать событие Status.

      ПримечаниеПримечание

      Если при создании подписки по запросу было указано значение false для свойства CreateSyncAgentByDefault (по умолчанию), необходимо также указать свойства Distributor, DistributorSecurityMode, PublisherSecurityMode, HostName, SubscriptionType, ExchangeType, а при необходимости также и свойства DistributorLogin, DistributorPassword, PublisherLogin и PublisherPassword, так как метаданные подписки, относящиеся к заданию агента, в таблице MSsubscription_properties недоступны.

Примеры (объекты RMO)

В следующем примере синхронизируется подписка по запросу на публикацию транзакций, в которой агент запускается асинхронно через задание агента.

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

            // 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 = "AdventureWorks2012"
Dim subscriptionDbName As String = "AdventureWorks2012Replica"

' 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

В следующем примере синхронизируется подписка по запросу на публикацию транзакций, в которой агент запускается синхронно.

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

            // 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 = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"

' 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

В следующем примере синхронизируется подписка по запросу на публикацию слиянием, в которой агент запускается асинхронно через задание агента.

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

            // 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 = "AdventureWorks2012"
Dim subscriptionDbName As String = "AdventureWorks2012Replica"

' 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

В следующем примере синхронизируется подписка по запросу на публикацию слиянием, в которой агент запускается синхронно.

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

            // 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 = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"

' 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

В следующем примере синхронизируется подписка по запросу на публикацию слиянием с использованием веб-синхронизации. Данная подписка создается без задания агента и соответствующих метаданных подписки, поэтому агент должен быть запущен синхронно с указанием дополнительных сведений о подписке.

          // Define the server, publication, and database names.
            string subscriberName = subscriberInstance;
            string publisherName = publisherInstance;
            string distributorName = distributorInstance;
            string publicationName = "AdvWorksSalesOrdersMerge";
            string subscriptionDbName = "AdventureWorks2012Replica";
            string publicationDbName = "AdventureWorks2012";
            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 = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"
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

Значок стрелки, используемый со ссылкой «В начало»[Top]

См. также

Основные понятия

Синхронизация данных

Создание подписки по запросу

Рекомендации по защите репликации