共用方式為


如何:建立提取訂閱 (RMO 程式設計)

您可以使用「複寫管理物件 (RMO)」以程式設計的方式建立提取訂閱。用於建立提取訂閱的 RMO 類別依該訂閱所屬的發行集類型而定。

若要建立快照式或交易式發行集的提取訂閱

  1. 使用 ServerConnection 類別建立到「訂閱者」和「發行者」的連接。

  2. 使用步驟 1 中的「發行者」連接建立 TransPublication 類別的執行個體。指定 NameDatabaseNameConnectionContext

  3. 呼叫 LoadProperties 方法。如果此方法傳回 false,則表示步驟 2 中指定的屬性不正確,或伺服器上不存在該發行集。

  4. Attributes 屬性和 AllowPull 之間執行位元運算邏輯 AND (Visual C# 中的 & 和 Visual Basic 中的 And)。如果結果為 None,則將 Attributes 設為 AttributesAllowPull 之間位元運算邏輯 OR (Visual C# 中的 | 和 Visual Basic 中的 Or) 的結果。然後呼叫 CommitPropertyChanges 以啟用提取訂閱。

  5. 如果訂閱資料庫不存在,可使用 Database 類別建立它。如需詳細資訊,請參閱<Creating, Altering, and Removing Databases>。

  6. 建立 TransPullSubscription 類別的執行個體。

  7. 設定下列訂閱屬性:

    • ConnectionContext 設為到步驟 1 中建立之「訂閱者」的 ServerConnection
    • DatabaseName 設為訂閱資料庫的名稱。
    • PublisherName 設為「發行者」的名稱。
    • PublicationDBName 設為發行集資料庫的名稱。
    • PublicationName 設為發行集的名稱。
    • SynchronizationAgentProcessSecurityLoginPassword (或 SecurePassword) 欄位,為「散發代理程式」在「訂閱者」上執行時所使用的 Microsoft Windows 帳戶提供認證。此帳戶用於建立到「訂閱者」的本機連接,以及使用「Windows 驗證」建立遠端連接。
      ms147314.note(zh-tw,SQL.90).gif附註:
      當訂閱是由 sysadmin 固定伺服器角色的成員建立時,不需要設定 SynchronizationAgentProcessSecurity,但還是建議您對其進行設定。在這種情況下,代理程式會模擬「SQL Server 代理程式」帳戶。如需詳細資訊,請參閱<複寫代理程式安全性模型>。
    • (選擇性) CreateSyncAgentByDefaulttrue 值,以建立用於同步處理訂閱的代理程式作業。如果指定 false (預設值),則只能以程式設計的方式同步處理訂閱,而且您在從 SynchronizationAgent 屬性存取此物件時必須指定其他屬性 TransSynchronizationAgent。如需詳細資訊,請參閱<如何:同步處理提取訂閱 (RMO 程式設計)>。
      ms147314.note(zh-tw,SQL.90).gif附註:
      Microsoft SQL Server Express Edition 不支援「SQL Server 代理程式」。當您為「Express Edition 訂閱者」指定值 true 時,不會建立代理程式作業。不過,在「訂閱者」上會儲存重要的訂閱相關中繼資料。
    • (選擇性) 在使用「SQL Server 驗證」連接到「散發者」時,設定 DistributorSecuritySqlStandardLoginSqlStandardPassword (或 SecureSqlStandardPassword) 欄位。
  8. 呼叫 Create 方法。

  9. 使用步驟 2 中 TransPublication 類別的執行個體,呼叫 MakePullSubscriptionWellKnown 方法,以使用「發行者」註冊提取訂閱。如果此註冊已存在,則會發生例外狀況。

若要建立合併式發行集的提取訂閱

  1. 使用 ServerConnection 類別建立到「訂閱者」和「發行者」的連接。

  2. 使用步驟 1 中的「發行者」連接建立 MergePublication 類別的執行個體。指定 NameDatabaseNameConnectionContext

  3. 呼叫 LoadProperties 方法。如果此方法傳回 false,則表示步驟 2 中指定的屬性不正確,或伺服器上不存在該發行集。

  4. Attributes 屬性和 AllowPull 之間執行位元運算邏輯 AND (Visual C# 中的 & 和 Visual Basic 中的 And)。如果結果為 None,則將 Attributes 設為 AttributesAllowPull 之間位元運算邏輯 OR (Visual C# 中的 | 和 Visual Basic 中的 Or) 的結果。然後呼叫 CommitPropertyChanges 以啟用提取訂閱。

  5. 如果訂閱資料庫不存在,可使用 Database 類別建立它。如需詳細資訊,請參閱<Creating, Altering, and Removing Databases>。

  6. 建立 MergePullSubscription 類別的執行個體。

  7. 設定下列訂閱屬性:

    • ConnectionContext 設為到步驟 1 中建立之「訂閱者」的 ServerConnection
    • DatabaseName 設為訂閱資料庫的名稱。
    • PublisherName 設為「發行者」的名稱。
    • PublicationDBName 設為發行集資料庫的名稱。
    • PublicationName 設為發行集的名稱。
    • SynchronizationAgentProcessSecurityLoginPassword (或 SecurePassword) 欄位,為「合併代理程式」在「訂閱者」上執行時所使用的 Microsoft Windows 帳戶提供認證。此帳戶用於建立到「訂閱者」的本機連接,以及使用「Windows 驗證」建立遠端連接。
      ms147314.note(zh-tw,SQL.90).gif附註:
      當訂閱是由 sysadmin 固定伺服器角色的成員建立時,不需要設定 SynchronizationAgentProcessSecurity,但還是建議您對其進行設定。在這種情況下,代理程式會模擬「SQL Server 代理程式」帳戶。如需詳細資訊,請參閱<複寫代理程式安全性模型>。
    • (選擇性) CreateSyncAgentByDefaulttrue 值,以建立用於同步處理訂閱的代理程式作業。如果指定 false (預設值),則只能以程式設計的方式同步處理訂閱,而且您在從 SynchronizationAgent 屬性存取此物件時必須指定其他屬性 MergeSynchronizationAgent。如需詳細資訊,請參閱<如何:同步處理提取訂閱 (RMO 程式設計)>。
    • (選擇性) 在使用「SQL Server 驗證」連接到「散發者」時,設定 DistributorSecuritySqlStandardLoginSqlStandardPassword (或 SecureSqlStandardPassword) 欄位。
    • (選擇性) 在使用「SQL Server 驗證」連接到「發行者」時,設定 PublisherSecuritySqlStandardLoginSqlStandardPassword (或 SecureSqlStandardPassword) 欄位。
  8. 呼叫 Create 方法。

  9. 使用步驟 2 中 MergePublication 類別的執行個體,呼叫 MakePullSubscriptionWellKnown 方法,以使用「發行者」註冊提取訂閱。如果此註冊已存在,則會發生例外狀況。

範例

此範例會建立交易式發行集的提取訂閱。用於建立「散發代理程式」作業的 Microsoft Windows 帳戶認證是在執行階段傳遞的。

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

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
TransPublication publication;
TransPullSubscription subscription;

try
{
    // Connect to the Publisher and Subscriber.
    subscriberConn.Connect();
    publisherConn.Connect();

    // Ensure that the publication exists and that 
    // it supports pull subscriptions.
    publication = new TransPublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.IsExistingObject)
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

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

        // Specify the Windows login credentials for the Distribution Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = true;

        // By default, subscriptions to transactional publications are synchronized 
        // continuously, but in this case we only want to synchronize on demand.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.OnDemand;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (TransSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                TransSubscriberType.ReadOnly);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksProductTran"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As TransPublication
Dim subscription As TransPullSubscription

Try
    ' Connect to the Publisher and Subscriber.
    subscriberConn.Connect()
    publisherConn.Connect()

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions.
    publication = New TransPublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.IsExistingObject Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

        ' Define the pull subscription.
        subscription = New TransPullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.Description = "Pull subscription to " + publicationDbName _
        + " on " + subscriberName + "."

        ' Specify the Windows login credentials for the Distribution Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = True

        ' By default, subscriptions to transactional publications are synchronized 
        ' continuously, but in this case we only want to synchronize on demand.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.OnDemand

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As TransSubscription In publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName And _
                existing.SubscriptionDBName = subscriptionDbName Then
                registered = True
            End If
        Next existing
        If Not registered Then
            ' Register the subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             TransSubscriberType.ReadOnly)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
        "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

此範例會建立合併式發行集的提取訂閱。用於建立「合併代理程式」作業的 Windows 帳戶認證是在執行階段傳遞的。

// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksSalesOrdersMerge";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorksReplica";
string publicationDbName = "AdventureWorks";
string hostname = @"adventure-works\garrett1";

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergePullSubscription subscription;

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

    // Ensure that the publication exists and that 
    // it supports pull subscriptions.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

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

        // Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = true;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
Dim hostname As String = "adventure-works\garrett1"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergePullSubscription

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

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

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

        ' Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = True

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
        "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

此範例會建立合併式發行集的提取訂閱,而不會在 MSsubscription_properties 中建立相關聯的代理程式作業和訂閱中繼資料。用於建立「合併代理程式」作業的 Windows 帳戶認證是在執行階段傳遞的。

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

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergePullSubscription subscription;

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

    // Ensure that the publication exists and that 
    // it supports pull subscriptions.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

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

        // Specify that an agent job not be created for this subscription. The
        // subscription can only be synchronized by running the Merge Agent directly.
        // Subscripition metadata stored in MSsubscription_properties will not
        // be available and must be specified at run time.
        subscription.CreateSyncAgentByDefault = false;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergePullSubscription

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

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

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

        ' Specify that an agent job not be created for this subscription. The
        ' subscription can only be synchronized by running the Merge Agent directly.
        ' Subscripition metadata stored in MSsubscription_properties will not
        ' be available and must be specified at run time.
        subscription.CreateSyncAgentByDefault = False

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
     "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

此範例會建立合併式發行集的提取訂閱,使用 Web 同步處理可以從網際網路對其進行同步處理。用於建立「合併代理程式」作業的 Windows 帳戶認證是在執行階段傳遞的。如需詳細資訊,請參閱<How to: Configure Web Synchronization for Merge Replication (RMO Programming)

// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksSalesOrdersMerge";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorksReplica";
string publicationDbName = "AdventureWorks";
string hostname = @"adventure-works\garrett1";
string webSyncUrl = "https://" + publisherInstance + "/WebSync/replisapi.dll";

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergePullSubscription subscription;

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

    // Ensure that the publication exists and that 
    // it supports pull subscriptions and Web synchronization.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }
        if ((publication.Attributes & PublicationAttributes.AllowWebSynchronization) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowWebSynchronization;
        }

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

        // Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Enable Web synchronization.
        subscription.UseWebSynchronization = true;
        subscription.InternetUrl = webSyncUrl;

        // Specify the same Windows credentials to use when connecting to the
        // Web server using HTTPS Basic Authentication.
        subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication;
        subscription.InternetLogin = winLogin;
        subscription.InternetPassword = winPassword;

        // Ensure that we create a job for this subscription.
        subscription.CreateSyncAgentByDefault = true;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorksReplica"
Dim publicationDbName As String = "AdventureWorks"
Dim hostname As String = "adventure-works\garrett1"
Dim webSyncUrl As String = "https://" + publisherInstance + "/WebSync/replisapi.dll"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergePullSubscription

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

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions and Web synchronization.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If
        If (publication.Attributes And PublicationAttributes.AllowWebSynchronization) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowWebSynchronization
        End If

        ' Define the pull subscription.
        subscription = New MergePullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.HostName = hostname
        subscription.CreateSyncAgentByDefault = True

        ' Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Enable Web synchronization.
        subscription.UseWebSynchronization = True
        subscription.InternetUrl = webSyncUrl

        ' Specify the same Windows credentials to use when connecting to the
        ' Web server using HTTPS Basic Authentication.
        subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication
        subscription.InternetLogin = winLogin
        subscription.InternetPassword = winPassword

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
     "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

請參閱

工作

如何:建立提取訂閱 (複寫 Transact-SQL 程式設計)
如何:同步處理提取訂閱 (RMO 程式設計)

其他資源

Programming with Replication Management Objects
How to: Create a Publication (RMO Programming)
訂閱發行集

說明及資訊

取得 SQL Server 2005 協助