방법: 매개 변수가 있는 필터를 사용하여 병합 게시에 대한 스냅숏 만들기(RMO 프로그래밍)

매개 변수가 있는 필터를 사용하여 병합 게시에 대한 스냅숏을 만들 때는 구독에 대한 구독자 메타데이터를 모두 포함하는 표준 스키마 스냅숏을 먼저 만들어야 합니다. 그런 다음 게시된 데이터의 구독자별 파티션을 포함하는 스냅숏 부분을 만듭니다. 자세한 내용은 방법: 초기 스냅숏 만들기(RMO 프로그래밍)를 참조하십시오.

다음과 같이 RMO(복제 관리 개체)를 사용하여 프로그래밍 방식으로 분할된 스냅숏을 만들 수 있습니다.

  • 구독자가 처음 동기화될 때 스냅숏 생성 및 적용을 요청하도록 허용합니다.

  • 각 파티션에 대한 스냅숏을 미리 생성합니다.

  • 스냅숏 에이전트를 실행하여 각 구독자에 대한 스냅숏을 수동으로 생성합니다.

[!참고]

병합 아티클을 만들 때 PartitionOptionNonOverlappingSingleSubscription 값을 지정하여 아티클을 필터링함으로써 구독별로 고유한 겹치지 않는 파티션을 생성하면 병합 에이전트를 실행할 때마다 메타데이터가 정리됩니다. 따라서 분할된 스냅숏은 더 빨리 만료됩니다. 이 옵션을 사용할 경우 구독자가 스냅숏 생성을 요청하도록 허용하는 것을 고려해야 합니다. 자세한 내용은 매개 변수가 있는 행 필터 항목의 "적절한 필터링 옵션 사용" 섹션을 참조하십시오.

보안 정보보안 정보

가능한 경우 런타임에 사용자에게 보안 자격 증명을 입력하라는 메시지를 표시합니다. 자격 증명을 저장해야 하는 경우 Microsoft Windows .NET Framework에서 제공하는 암호화 서비스를 사용합니다.

구독자가 스냅숏 생성 및 배달을 시작하도록 허용하는 게시를 만들려면

  1. ServerConnection 클래스를 사용하여 게시자 연결을 만듭니다.

  2. 게시 데이터베이스에 대해 ReplicationDatabase 클래스의 인스턴스를 만들고 1단계에서 만든 ServerConnection 인스턴스에 ConnectionContext 속성을 설정한 다음 LoadProperties 메서드를 호출합니다. LoadProperties에서 false를 반환하면 데이터베이스가 있는지 확인합니다.

  3. EnabledMergePublishing 속성이 false이면 true로 설정한 후 CommitPropertyChanges를 호출합니다.

  4. MergePublication 클래스의 인스턴스를 만들고 이 개체에 대해 다음 속성을 설정합니다.

  5. Create 메서드를 호출하여 게시를 만듭니다.

    보안 정보보안 정보

     원격 배포자로 게시자를 구성할 경우 SnapshotGenerationAgentProcessSecurity를 포함하여 모든 속성에 제공된 값이 일반 텍스트로 배포자에게 보내집니다. Create 메서드를 호출하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다. 자세한 내용은 SQL Server 연결 암호화를 참조하십시오.

  6. MergeArticle 속성을 사용하여 게시에 아티클을 추가합니다. 매개 변수가 있는 필터를 정의하는 하나 이상의 아티클에 대해 FilterClause 속성을 지정합니다. 필요한 경우 아티클 간 조인 필터를 정의하는 MergeJoinFilter 개체를 만듭니다. 자세한 내용은 방법: 아티클 정의(RMO 프로그래밍)를 참조하십시오.

  7. SnapshotAgentExists 값이 false이면 CreateSnapshotAgent를 호출하여 이 게시에 대한 초기 스냅숏 에이전트 작업을 만듭니다.

  8. 4단계에서 만든 MergePublication 개체의 StartSnapshotGenerationAgentJob 메서드를 호출합니다. 그러면 초기 스냅숏을 생성하는 에이전트 작업이 시작됩니다. 초기 스냅숏을 생성하고 스냅숏 에이전트에 대한 사용자 지정 일정을 정의하는 방법은 방법: 초기 스냅숏 만들기(RMO 프로그래밍)를 참조하십시오.

  9. (옵션) SnapshotAvailable 속성이 true 값인지 확인하여 초기 스냅숏을 사용할 준비가 되었는지 확인합니다.

  10. 구독자가 병합 에이전트에 처음으로 연결하는 경우에는 분할된 스냅숏이 자동으로 생성됩니다.

게시를 만들고 스냅숏을 미리 생성하거나 자동으로 새로 고치려면

  1. MergePublication 클래스의 인스턴스를 사용하여 병합 게시를 정의합니다. 자세한 내용은 방법: 게시 만들기(RMO 프로그래밍)를 참조하십시오.

  2. MergeArticle 속성을 사용하여 게시에 아티클을 추가합니다. 매개 변수가 있는 필터를 정의하는 하나 이상의 아티클에 대해 FilterClause 속성을 지정하고 아티클 간 조인 필터를 정의하는 MergeJoinFilter 개체를 만듭니다. 자세한 내용은 방법: 아티클 정의(RMO 프로그래밍)를 참조하십시오.

  3. SnapshotAgentExists의 값이 false이면 CreateSnapshotAgent를 호출하여 이 게시에 대한 스냅숏 에이전트 작업을 만듭니다.

  4. 1단계에서 만든 MergePublication 개체의 StartSnapshotGenerationAgentJob 메서드를 호출합니다. 그러면 초기 스냅숏을 생성하는 에이전트 작업이 시작됩니다. 초기 스냅숏을 생성하고 스냅숏 에이전트에 대한 사용자 지정 일정을 정의하는 방법은 방법: 초기 스냅숏 만들기(RMO 프로그래밍)를 참조하십시오.

  5. SnapshotAvailable 속성이 true 값인지 확인하여 초기 스냅숏을 사용할 준비가 되었는지 확인합니다.

  6. MergePartition 클래스의 인스턴스를 만들고 다음 두 속성 중 하나 또는 모두를 사용하여 구독자에 대한 매개 변수가 있는 필터링 조건을 설정합니다.

  7. MergeDynamicSnapshotJob 클래스의 인스턴스를 만들고 6단계와 동일한 속성을 설정합니다.

  8. ReplicationAgentSchedule 클래스를 사용하여 구독자 파티션에 대한 필터링된 스냅숏을 생성할 일정을 정의합니다.

  9. 1단계에서 만든 MergePublication의 인스턴스를 사용하여 AddMergePartition을 호출합니다. 6단계에서 만든 MergePartition 개체를 전달합니다.

  10. 1단계에서 만든 TransSubscription의 인스턴스를 사용하여 SynchronizeWithJob 메서드를 호출합니다. 7단계에서 만든 MergeDynamicSnapshotJob 개체 및 8단계에서 만든 ReplicationAgentSchedule 개체를 전달합니다.

  11. EnumMergeDynamicSnapshotJobs를 호출하고 반환된 배열의 새로 추가된 분할된 스냅숏 작업에서 MergeDynamicSnapshotJob 개체를 찾습니다.

  12. 작업의 Name 속성을 가져옵니다.

  13. ServerConnection 클래스를 사용하여 배포자 연결을 만듭니다.

  14. 13단계에서 만든 ServerConnection 개체를 전달하여 SQL SMO(Server Management Objects) Server 클래스의 인스턴스를 만듭니다.

  15. 14단계에서 만든 Server 개체의 JobServer 속성 및 12단계에서 가져온 작업 이름을 전달하여 Job 클래스의 인스턴스를 만듭니다.

  16. Start 메서드를 호출하여 분할된 스냅숏 작업을 시작합니다.

  17. 구독자별로 6단계에서 16단계까지 반복합니다.

게시를 만들고 각 파티션에 대한 스냅숏을 수동으로 만들려면

  1. MergePublication 클래스의 인스턴스를 사용하여 병합 게시를 정의합니다. 자세한 내용은 방법: 게시 만들기(RMO 프로그래밍)를 참조하십시오.

  2. MergeArticle 속성을 사용하여 게시에 아티클을 추가합니다. 매개 변수가 있는 필터를 정의하는 하나 이상의 아티클에 대해 FilterClause 속성을 지정하고 아티클 간 조인 필터를 정의하는 MergeJoinFilter 개체를 만듭니다. 자세한 내용은 방법: 아티클 정의(RMO 프로그래밍)를 참조하십시오.

  3. 초기 스냅숏을 만듭니다. 자세한 내용은 방법: 초기 스냅숏 만들기(RMO 프로그래밍)를 참조하십시오.

  4. SnapshotGenerationAgent 클래스의 인스턴스를 만들고 다음 필수 속성을 설정합니다.

  5. ReplicationTypeMerge 값을 설정합니다.

  6. 다음 속성 중 하나 이상을 설정하여 분할 매개 변수를 정의합니다.

  7. GenerateSnapshot 메서드를 호출합니다.

  8. 구독자별로 4단계에서 7단계까지 반복합니다.

이 예제에서는 구독자에게 스냅숏 생성 요청을 허용하는 병합 게시를 만듭니다.

            // Set the Publisher, publication database, and publication names.
            string publisherName = publisherInstance;
            string publicationName = "AdvWorksSalesOrdersMerge";
            string publicationDbName = "AdventureWorks2008R2";

            ReplicationDatabase publicationDb;
            MergePublication publication;

            // Create a connection to the Publisher.
            ServerConnection conn = new ServerConnection(publisherName);

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

                // Enable the database for merge publication.               
                publicationDb = new ReplicationDatabase(publicationDbName, conn);
                if (publicationDb.LoadProperties())
                {
                    if (!publicationDb.EnabledMergePublishing)
                    {
                        publicationDb.EnabledMergePublishing = true;
                    }
                }
                else
                {
                    // Do something here if the database does not exist. 
                    throw new ApplicationException(String.Format(
                        "The {0} database does not exist on {1}.",
                        publicationDb, publisherName));
                }

                // Set the required properties for the merge publication.
                publication = new MergePublication();
                publication.ConnectionContext = conn;
                publication.Name = publicationName;
                publication.DatabaseName = publicationDbName;

                // Enable precomputed partitions.
                publication.PartitionGroupsOption = PartitionGroupsOption.True;

                // Specify the Windows account under which the Snapshot Agent job runs.
                // This account will be used for the local connection to the 
                // Distributor and all agent connections that use Windows Authentication.
                publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin;
                publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword;

                // Explicitly set the security mode for the Publisher connection
                // Windows Authentication (the default).
                publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;

                // Enable Subscribers to request snapshot generation and filtering.
                publication.Attributes |= PublicationAttributes.AllowSubscriberInitiatedSnapshot;
                publication.Attributes |= PublicationAttributes.DynamicFilters;

                // Enable pull and push subscriptions.
                publication.Attributes |= PublicationAttributes.AllowPull;
                publication.Attributes |= PublicationAttributes.AllowPush;

                if (!publication.IsExistingObject)
                {
                    // Create the merge publication.
                    publication.Create();
                    
                    // Create a Snapshot Agent job for the publication.
                    publication.CreateSnapshotAgent();
                }
                else
                {
                    throw new ApplicationException(String.Format(
                        "The {0} publication already exists.", publicationName));
                }
            }

            catch (Exception ex)
            {
                // Implement custom application error handling here.
                throw new ApplicationException(String.Format(
                    "The publication {0} could not be created.", publicationName), ex);
            }
            finally
            {
                conn.Disconnect();
            }
' Set the Publisher, publication database, and publication names.
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2008R2"

Dim publicationDb As ReplicationDatabase
Dim publication As MergePublication

' Create a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(publisherName)

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

    ' Enable the database for merge publication.                
    publicationDb = New ReplicationDatabase(publicationDbName, conn)
    If publicationDb.LoadProperties() Then
        If Not publicationDb.EnabledMergePublishing Then
            publicationDb.EnabledMergePublishing = True
        End If
    Else
        ' Do something here if the database does not exist. 
        Throw New ApplicationException(String.Format( _
         "The {0} database does not exist on {1}.", _
         publicationDb, publisherName))
    End If

    ' Set the required properties for the merge publication.
    publication = New MergePublication()
    publication.ConnectionContext = conn
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName

    ' Enable precomputed partitions.
    publication.PartitionGroupsOption = PartitionGroupsOption.True

    ' Specify the Windows account under which the Snapshot Agent job runs.
    ' This account will be used for the local connection to the 
    ' Distributor and all agent connections that use Windows Authentication.
    publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin
    publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword

    ' Explicitly set the security mode for the Publisher connection
    ' Windows Authentication (the default).
    publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = True

    ' Enable Subscribers to request snapshot generation and filtering.
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowSubscriberInitiatedSnapshot
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.DynamicFilters

    ' Enable pull and push subscriptions
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowPull
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowPush

    If Not publication.IsExistingObject Then
        ' Create the merge publication.
        publication.Create()

        ' Create a Snapshot Agent job for the publication.
        publication.CreateSnapshotAgent()
    Else
        Throw New ApplicationException(String.Format( _
            "The {0} publication already exists.", publicationName))
    End If
Catch ex As Exception
    ' Implement custom application error handling here.
    Throw New ApplicationException(String.Format( _
        "The publication {0} could not be created.", publicationName), ex)
Finally
    conn.Disconnect()
End Try

이 예제에서는 매개 변수가 있는 행 필터를 사용하여 병합 게시에 대한 구독자 파티션 및 필터링된 스냅숏을 수동으로 만듭니다.

           // Define the server, database, and publication names
            string publisherName = publisherInstance;
            string publicationName = "AdvWorksSalesOrdersMerge";
            string publicationDbName = "AdventureWorks2008R2";
            string distributorName = publisherInstance;

            MergePublication publication;
            MergePartition partition;
            MergeDynamicSnapshotJob snapshotAgentJob;
            ReplicationAgentSchedule schedule;
            
            // Create a connection to the Publisher.
            ServerConnection publisherConn = new ServerConnection(publisherName);

            // Create a connection to the Distributor to start the Snapshot Agent.
            ServerConnection distributorConn = new ServerConnection(distributorName);

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

                // Set the required properties for the publication.
                publication = new MergePublication();
                publication.ConnectionContext = publisherConn;
                publication.Name = publicationName;
                publication.DatabaseName = publicationDbName;


                // If we can't get the properties for this merge publication, 
                // then throw an application exception.
                if (publication.LoadProperties() || publication.SnapshotAvailable)
                {
                    // Set a weekly schedule for the filtered data snapshot.
                    schedule = new ReplicationAgentSchedule();
                    schedule.FrequencyType = ScheduleFrequencyType.Weekly;
                    schedule.FrequencyRecurrenceFactor = 1;
                    schedule.FrequencyInterval = Convert.ToInt32(0x001);

                    // Set the value of Hostname that defines the data partition. 
                    partition = new MergePartition();
                    partition.DynamicFilterHostName = hostname;
                    snapshotAgentJob = new MergeDynamicSnapshotJob();
                    snapshotAgentJob.DynamicFilterHostName = hostname;

                    // Create the partition for the publication with the defined schedule.
                    publication.AddMergePartition(partition);
                    publication.AddMergeDynamicSnapshotJob(snapshotAgentJob, schedule);
                }
                else
                {
                    throw new ApplicationException(String.Format(
                        "Settings could not be retrieved for the publication, " +
                        " or the initial snapshot has not been generated. " +
                        "Ensure that the publication {0} exists on {1} and " +
                        "that the Snapshot Agent has run successfully.",
                        publicationName, publisherName));
                }
            }
            catch (Exception ex)
            {
                // Do error handling here.
                throw new ApplicationException(string.Format(
                    "The partition for '{0}' in the {1} publication could not be created.",
                    hostname, publicationName), ex);
            }
            finally
            {
                publisherConn.Disconnect();
                if (distributorConn.IsOpen) distributorConn.Disconnect();
            }
' Define the server, database, and publication names
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2008R2"
Dim distributorName As String = publisherInstance

Dim publication As MergePublication
Dim partition As MergePartition
Dim snapshotAgentJob As MergeDynamicSnapshotJob
Dim schedule As ReplicationAgentSchedule

' Create a connection to the Publisher.
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create a connection to the Distributor to start the Snapshot Agent.
Dim distributorConn As ServerConnection = New ServerConnection(distributorName)

Try
    ' Connect to the Publisher.
    publisherConn.Connect()

    ' Set the required properties for the publication.
    publication = New MergePublication()
    publication.ConnectionContext = publisherConn
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName


    ' If we can't get the properties for this merge publication, 
    ' then throw an application exception.
    If (publication.LoadProperties() Or publication.SnapshotAvailable) Then
        ' Set a weekly schedule for the filtered data snapshot.
        schedule = New ReplicationAgentSchedule()
        schedule.FrequencyType = ScheduleFrequencyType.Weekly
        schedule.FrequencyRecurrenceFactor = 1
        schedule.FrequencyInterval = Convert.ToInt32("0x001", 16)

        ' Set the value of Hostname that defines the data partition. 
        partition = New MergePartition()
        partition.DynamicFilterHostName = hostname
        snapshotAgentJob = New MergeDynamicSnapshotJob()
        snapshotAgentJob.DynamicFilterHostName = hostname

        ' Create the partition for the publication with the defined schedule.
        publication.AddMergePartition(partition)
        publication.AddMergeDynamicSnapshotJob(snapshotAgentJob, schedule)
    Else
        Throw New ApplicationException(String.Format( _
         "Settings could not be retrieved for the publication, " + _
         " or the initial snapshot has not been generated. " + _
         "Ensure that the publication {0} exists on {1} and " + _
         "that the Snapshot Agent has run successfully.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Do error handling here.
    Throw New ApplicationException(String.Format( _
     "The partition for '{0}' in the {1} publication could not be created.", _
     hostname, publicationName), ex)
Finally
    publisherConn.Disconnect()
    If distributorConn.IsOpen Then
        distributorConn.Disconnect()
    End If
End Try

이 예제에서는 매개 변수가 있는 행 필터를 사용하여 병합 게시에 구독자에 대한 필터링된 데이터 스냅숏을 수동으로 만듭니다.

            // Set the Publisher, publication database, and publication names.
            string publicationName = "AdvWorksSalesOrdersMerge";
            string publicationDbName = "AdventureWorks2008R2";
            string publisherName = publisherInstance;
            string distributorName = publisherInstance;

            SnapshotGenerationAgent agent;

            try
            {
                // Set the required properties for Snapshot Agent.
                agent = new SnapshotGenerationAgent();
                agent.Distributor = distributorName;
                agent.DistributorSecurityMode = SecurityMode.Integrated;
                agent.Publisher = publisherName;
                agent.PublisherSecurityMode = SecurityMode.Integrated;
                agent.Publication = publicationName;
                agent.PublisherDatabase = publicationDbName;
                agent.ReplicationType = ReplicationType.Merge;

                // Specify the partition information to generate a 
                // filtered snapshot based on Hostname.
                agent.DynamicFilterHostName = hostname;

                // Start the agent synchronously.
                agent.GenerateSnapshot();
            }
            catch (Exception ex)
            {
                // Implement custom application error handling here.
                throw new ApplicationException(String.Format(
                    "A snapshot could not be generated for the {0} publication."
                    , publicationName), ex);
            }
' Set the Publisher, publication database, and publication names.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2008R2"
Dim publisherName As String = publisherInstance
Dim distributorName As String = publisherInstance

Dim agent As SnapshotGenerationAgent

Try
    ' Set the required properties for Snapshot Agent.
    agent = New SnapshotGenerationAgent()
    agent.Distributor = distributorName
    agent.DistributorSecurityMode = SecurityMode.Integrated
    agent.Publisher = publisherName
    agent.PublisherSecurityMode = SecurityMode.Integrated
    agent.Publication = publicationName
    agent.PublisherDatabase = publicationDbName
    agent.ReplicationType = ReplicationType.Merge

    ' Specify the partition information to generate a 
    ' filtered snapshot based on Hostname.
    agent.DynamicFilterHostName = hostname

    ' Start the agent synchronously.
    agent.GenerateSnapshot()
Catch ex As Exception
    ' Implement custom application error handling here.
    Throw New ApplicationException(String.Format( _
     "A snapshot could not be generated for the {0} publication." _
     , publicationName), ex)
End Try