Cómo sincronizar una suscripción de inserción (programación con RMO)
Puede sincronizar suscripciones de inserción mediante programación con los objetos de administración de replicación (RMO) y el acceso de código administrado a las funcionalidades del agente de replicación. Las clases que se usan para crear una suscripción de inserción dependen del tipo de publicación al que pertenece la suscripción.
[!NOTA]
Si desea iniciar una sincronización que se ejecute de forma autónoma sin afectar a la aplicación, inicie el agente asincrónicamente. Sin embargo, si desea supervisar el resultado de la sincronización y recibir las devoluciones de llamada del agente durante el proceso de sincronización (por ejemplo, si desea mostrar una barra de progreso), debe iniciar el agente sincrónicamente. Para los suscriptores de MicrosoftSQL Server 2005 Express Edition, debe iniciar el agente sincrónicamente.
Para sincronizar una suscripción de inserción a una publicación transaccional o de instantáneas
Cree una conexión al distribuidor mediante la clase ServerConnection.
Cree una instancia de la clase TransSubscription y establezca las propiedades siguientes:
El nombre de la base de datos de publicación para DatabaseName.
El nombre de la publicación a la que pertenece la suscripción para PublicationName.
El nombre de la base de datos de suscripciones para SubscriptionDBName.
El nombre del Suscriptor para SubscriberName.
La conexión creada en el paso 1 para ConnectionContext.
Llame al método LoadProperties para obtener las propiedades de suscripción restantes. Si este método devuelve false, compruebe que la suscripción existe.
Inicie el Agente de distribución en el Distribuidor de una de las maneras siguientes:
Llame al método SynchronizeWithJob en la instancia de TransSubscription del paso 2. Este método inicia el Agente de distribución de forma asincrónica y controla inmediatamente las devoluciones a la aplicación mientras se está ejecutando el trabajo del agente. No puede llamar a este método si la suscripción se creó con un valor false para CreateSyncAgentByDefault.
Obtenga una instancia de la clase TransSynchronizationAgent de la propiedad SynchronizationAgent y llame al método Synchronize. Este método inicia el agente sincrónicamente y controla el resto con el trabajo del agente en ejecución. Durante la ejecución sincrónica, puede administrar el evento Status mientras el agente se está ejecutando.
Para sincronizar una suscripción de inserción con una publicación de mezcla
Cree una conexión al distribuidor mediante la clase ServerConnection.
Cree una instancia de la clase MergeSubscription y establezca las propiedades siguientes:
El nombre de la base de datos de publicación para DatabaseName.
El nombre de la publicación a la que pertenece la suscripción para PublicationName.
El nombre de la base de datos de suscripciones para SubscriptionDBName.
El nombre del Suscriptor para SubscriberName.
La conexión creada en el paso 1 para ConnectionContext.
Llame al método LoadProperties para obtener las propiedades de suscripción restantes. Si este método devuelve false, compruebe que la suscripción existe.
Inicie el Agente de mezcla en el Distribuidor de una de las maneras siguientes:
Llame al método SynchronizeWithJob en la instancia de MergeSubscription del paso 2. Este método inicia el Agente de mezcla de forma asincrónica y controla inmediatamente las devoluciones a la aplicación mientras se está ejecutando el trabajo del agente. No puede llamar a este método si la suscripción se creó con un valor false para CreateSyncAgentByDefault.
Obtenga una instancia de la clase MergeSynchronizationAgent de la propiedad SynchronizationAgent y llame al método Synchronize. Este método inicia el Agente de mezcla sincrónicamente y controla el resto con el trabajo del agente en ejecución. Durante la ejecución sincrónica, puede administrar el evento Status mientras se ejecuta el agente.
Ejemplo
Este ejemplo sincroniza una suscripción de inserción con una publicación transaccional, en la que el agente se inicia forma asincrónica con el trabajo del 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 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 = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
' 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 ejemplo sincroniza una suscripción de inserción con una publicación transaccional, en la que el agente se inicia sincrónicamente.
// 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 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 = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
' 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 ejemplo sincroniza una suscripción de inserción con una publicación de mezcla, en la que el agente se inicia forma asincrónica con el trabajo del 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 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 = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
' 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 ejemplo sincroniza una suscripción de inserción con una publicación de mezcla, en la que el agente se inicia sincrónicamente.
// 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 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 = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
' 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