Примечание.
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Область применения: SQL Server Управляемый экземпляр SQL Azure
В этом разделе описывается, как синхронизировать подписку с запросом на получение в SQL Server с помощью SQL Server Management Studio, агентов репликации или объектов управления репликацией (RMO).
Использование среды SQL Server Management Studio
Подписки синхронизируются агентом распространения (для репликации снимков и репликации транзакций) или агентом слияния (для репликации слиянием). Агенты могут работать непрерывно, запускаться по запросу или по расписанию. Дополнительные сведения о настройке расписаний синхронизации см. в этой статье.
Синхронизация подписки по запросу из папки локальных подписок в SQL Server Management Studio.
Синхронизировать подписку по запросу в Management Studio
Подключитесь к подписчику в Management Studio и разверните узел сервера.
Раскройте папку Репликация , а затем — папку Локальные подписки .
Щелкните подписку правой кнопкой мыши и выберите Просмотреть состояние синхронизации.
В диалоговом окне «Просмотр состояния синхронизации — <Подписчик>:<SubscriptionDatabase>» нажмите кнопку «Запуск». Когда синхронизация будет завершена, появится сообщение Синхронизация завершена .
Нажмите кнопку Закрыть.
Агенты репликации
Подписки по запросу могут синхронизироваться программно и по требованию, с помощью вызова из командной строки нужного исполняемого файла агента репликации. Вызываемый исполняемый файл агента репликации зависит от типа публикации, к которой принадлежит подписка по запросу. Дополнительные сведения см. в разделе Replication Agents.
Примечание.
Агенты репликации подключаются к локальному серверу, используя учетные данные проверки подлинности Windows пользователя, запустившего агент из командной строки. Эти учетные данные Windows также применяются при соединении с удаленными серверами с использованием встроенной проверки подлинности Windows.
Запуск агента распространителя из командной строки или из пакетного файла
Из командной строки или из пакетного файла запустите агент распространения репликации , вызвав программу distrib.exeсо следующими параметрами командной строки.
-Publisher
-PublisherDB
-Дистрибьютор
-РежимБезопасностиРаспространителя = 1
-Подписчик
-SubscriberDB
-Режим безопасности абонента = 1
-ТипПодписки = 1
При использовании проверки подлинности SQL Server необходимо также указать следующие аргументы.
-DistributorLogin
-DistributorPassword
-РежимБезопасностиРаспространителя = 0
-PublisherLogin
-PublisherPassword
-Режим безопасности издателя = 0
-SubscriberLogin
-SubscriberPassword
-Режим безопасности абонента = 0
Запуск агента слияния из командной строки или из пакетного файла
Из командной строки или из пакетного файла запустите агент слияния репликации , вызвав программу replmerg.exeсо следующими параметрами командной строки.
-Publisher
-PublisherDB
-Режим безопасности издателя = 1
-Публикация
-Дистрибьютор
-РежимБезопасностиРаспространителя = 1
-Подписчик
-Режим безопасности абонента = 1
-SubscriberDB
-ТипПодписки = 1
При использовании проверки подлинности SQL Server необходимо также указать следующие аргументы.
-DistributorLogin
-DistributorPassword
-РежимБезопасностиРаспространителя = 0
-PublisherLogin
-PublisherPassword
-Режим безопасности издателя = 0
-SubscriberLogin
-SubscriberPassword
-Режим безопасности абонента = 0
Примеры (агенты репликации)
В следующем примере запускается агент распространителя для синхронизации подписки по запросу. Все соединения устанавливаются с использованием проверки подлинности Windows.
-- Declare the variables.
SET Publisher=%instancename%
SET Subscriber=%instancename%
SET PublicationDB=AdventureWorks
SET SubscriptionDB=AdventureWorksReplica
SET Publication=AdvWorksProductsTran
-- Start the Distribution Agent.
-- The following command must be supplied without line breaks.
"C:\Program Files\Microsoft SQL Server\100\COM\DISTRIB.EXE" -Subscriber %Subscriber%
-SubscriberDB %SubscriptionDB% -SubscriberSecurityMode 1 -Publication %Publication%
-Publisher %Publisher% -PublisherDB %PublicationDB% -Distributor %Publisher%
-DistributorSecurityMode 1 -Continuous -SubscriptionType 1;
В следующем примере запускается агент слияния для синхронизации подписки по запросу. Все соединения устанавливаются с использованием проверки подлинности Windows.
-- Declare the variables.
SET Publisher=%instancename%
SET Subscriber=%instancename%
SET PublicationDB=AdventureWorks
SET SubscriptionDB=AdventureWorksReplica
SET Publication=AdvWorksSalesOrdersMerge
--Start the Merge Agent with concurrent upload and download processes.
-- The following command must be supplied without line breaks.
"C:\Program Files\Microsoft SQL Server\100\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 ;
Использование объектов управления репликацией (RMO)
Подписки по запросу можно синхронизировать программно с помощью объектов управления репликацией (RMO) и доступа из управляемого кода к функциям агента репликации. Конкретные классы, используемые для синхронизации, зависят от типа публикации, к которой принадлежит подписка.
Примечание.
Если нужно выполнить синхронизацию, которая выполняется автономно и не влияет на ваше приложение, запустите агент асинхронно. Однако если нужно наблюдать за результатами синхронизации и получать обратные вызовы от агента во время процесса синхронизации (например, если нужно отображать индикатор выполнения), то следует запускать агент синхронно. Для подписчиков Microsoft SQL Server 2005 Express необходимо запустить агент синхронно.
Синхронизировать подписку по запросу с публикацией моментальных снимков или транзакционной публикацией
Создайте соединение с подписчиком с помощью класса ServerConnection .
Создайте экземпляр класса TransPullSubscription и укажите следующие свойства:
Имя базы данных подписки для DatabaseName.
Имя публикации, к которой относится подписка для PublicationName.
Название базы данных публикаций для PublicationDBName.
Имя издателя для PublisherName.
Соединение, созданное на шаге 1 для ConnectionContext.
Вызовите метод LoadProperties , чтобы получить остальные свойства подписки. Если этот метод возвращает значение false, проверьте, существует ли подписка.
Запустите агент распространения на подписчике одним из следующих способов:
Вызовите метод SynchronizeWithJob экземпляра класса TransPullSubscription , созданного на шаге 2. Этот метод запускает агент распространителя асинхронно, а управление сразу после его вызова передается обратно приложению; задание агента при этом продолжает выполняться. Этот метод нельзя вызвать для подписчиков выпуска SQL Server 2005 Express или если подписка была создана со значением false ( CreateSyncAgentByDefault по умолчанию).
Получите экземпляр класса TransSynchronizationAgent из свойства SynchronizationAgent и вызовите метод Synchronize . Этот метод запускает агент синхронно, и управление остаётся у выполняющегося задания агента до его завершения. При синхронном выполнении в процессе работы агента можно обрабатывать событие Status .
Примечание.
Если при создании подписки по запросу для CreateSyncAgentByDefault было указано значение false (значение по умолчанию), необходимо также указать Distributor, DistributorSecurityMode и, при необходимости, DistributorLogin и DistributorPassword, так как метаданные подписки, относящиеся к заданию агента, недоступны в таблице MSsubscription_properties.
Синхронизация подписки по запросу на публикацию слиянием
Создайте соединение с подписчиком с помощью класса ServerConnection .
Создайте экземпляр класса MergePullSubscription и укажите следующие свойства:
Имя базы данных подписки для DatabaseName.
Имя публикации, к которой относится подписка для PublicationName.
Имя опубликованной базы данных для PublicationDBName.
Имя издателя для PublisherName.
Соединение, созданное на шаге 1 для ConnectionContext.
Вызовите метод LoadProperties , чтобы получить остальные свойства подписки. Если этот метод возвращает значение false, проверьте, существует ли подписка.
На подписчике запустите агент слияния одним из следующих способов:
Вызовите метод SynchronizeWithJob экземпляра класса MergePullSubscription , созданного на шаге 2. Этот метод запускает агент слияния асинхронно, а управление сразу после его вызова передается обратно приложению, задание агента при этом продолжает выполняться. Этот метод нельзя вызвать для подписчиков выпуска SQL Server 2005 Express или если подписка была создана со значением false ( CreateSyncAgentByDefault по умолчанию).
Получите экземпляр класса MergeSynchronizationAgent из свойства SynchronizationAgent и вызовите метод Synchronize . Этот метод запускает агент слияния синхронно, и управление остаётся у выполняющегося задания агента. При синхронном выполнении в процессе работы агента можно обрабатывать событие Status .
Примечание.
Если при создании подписки по запросу для CreateSyncAgentByDefault было указано значение false (значение по умолчанию), необходимо также указать свойства 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 = "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
В следующем примере синхронизируется подписка по запросу на публикацию транзакций, в которой агент запускается синхронно.
// 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 insufficient 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 insufficient 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 = "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
В следующем примере синхронизируется подписка по запросу на публикацию слиянием, в которой агент запускается синхронно.
// 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 insufficient 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 insufficient 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 = "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