Export (0) Print
Expand All

How to: Create a Snapshot for a Merge Publication with Parameterized Filters (RMO Programming)

When generating a snapshot for a merge publication using parameterized filters, you must first generate a standard (schema) snapshot that contains all of the Subscriber metadata for the subscription. Then, you generate the portion of the snapshot that contains the Subscriber-specific partition of the published data. For more information, see How to: Create the Initial Snapshot (RMO Programming).

You can use Replication Management Objects (RMO) to generate partitioned snapshots programmatically in the following ways:

  • Allow Subscribers to request snapshot generation and application the first time they synchronize.

  • Pre-generate snapshots for each partition.

  • Manually generate a snapshot for each Subscriber by running the Snapshot Agent.

NoteNote

When filtering for an article yields non-overlapping partitions that are unique for each subscription (by specifying a value of NonOverlappingSingleSubscription for PartitionOption when creating a merge article), metadata is cleaned up whenever the Merge Agent runs. This means that the partitioned snapshot expires more quickly. When you use this option, you should consider allowing Subscribers to request snapshot generation. For more information, see the section Using the Appropriate Filtering Options in the topic Parameterized Row Filters.

Security noteSecurity Note

When possible, prompt users to enter security credentials at runtime. If you must store credentials, use the cryptographic services provided by the Microsoft Windows .NET Framework.

To create a publication that allows Subscribers to initiate snapshot generation and delivery

  1. Create a connection to the Publisher by using the ServerConnection class.

  2. Create an instance of the ReplicationDatabase class for the publication database, set the ConnectionContext property to the instance of ServerConnection from step 1, and call the LoadProperties method. If LoadProperties returns false, confirm that the database exists.

  3. If EnabledMergePublishing property is false, set it to true and call CommitPropertyChanges.

  4. Create an instance of the MergePublication class, and set the following properties for this object:

  5. Call the Create method to create the publication.

    Security noteSecurity Note

     When configuring a Publisher with a remote Distributor, the values supplied for all properties, including SnapshotGenerationAgentProcessSecurity, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its remote Distributor before calling the Create method. For more information, see Encrypting Connections to SQL Server.

  6. Use the MergeArticle property to add articles to the publication. Specify the FilterClause property for at least one article that defines the parameterized filter. (Optional) Create MergeJoinFilter objects that define join filters between articles. For more information, see How to: Define an Article (RMO Programming).

  7. If the value of SnapshotAgentExists is false, call CreateSnapshotAgent to create the initial Snapshot Agent job for this publication.

  8. Call the StartSnapshotGenerationAgentJob method of the MergePublication object created in step 4. This starts the agent job that generates the initial snapshot. For more information about generating an initial snapshot and defining a custom schedule for the Snapshot Agent, see How to: Create the Initial Snapshot (RMO Programming).

  9. (Optional) Check for a value of true for the SnapshotAvailable property to determine when the initial snapshot is ready for use.

  10. When the Merge Agent for a Subscriber connects for the first time, a partitioned snapshot is generated automatically.

To create a publication and pregenerate or automatically refresh snapshots

  1. Use an instance of the MergePublication class to define a merge publication. For more information, see How to: Create a Publication (RMO Programming).

  2. Use the MergeArticle property to add articles to the publication. Specify the FilterClause property for at least one article that defines the parameterized filter, and create any MergeJoinFilter objects that define join filters between articles. For more information, see How to: Define an Article (RMO Programming).

  3. If the value of SnapshotAgentExists is false, call CreateSnapshotAgent to create the snapshot agent job for this publication.

  4. Call the StartSnapshotGenerationAgentJob method of the MergePublication object created in step 1. This method starts the agent job that generates the initial snapshot. For more information on generating an initial snapshot and defining a custom schedule for the Snapshot Agent, see How to: Create the Initial Snapshot (RMO Programming).

  5. Check for a value of true for the SnapshotAvailable property to determine when the initial snapshot is ready for use.

  6. Create an instance of the MergePartition class, and set the parameterized filtering criteria for the Subscriber by using one or both of the following properties:

  7. Create an instance of the MergeDynamicSnapshotJob class, and set the same property as in step 6.

  8. Use the ReplicationAgentSchedule class to define a schedule for generating the filtered snapshot for the Subscriber partition.

  9. Using the instance of MergePublication from step 1, call AddMergePartition. Pass the MergePartition object from step 6.

  10. Using the instance of MergePublication from step 1, call the AddMergeDynamicSnapshotJob method. Pass the MergeDynamicSnapshotJob object from step 7 and the ReplicationAgentSchedule object from step 8.

  11. Call EnumMergeDynamicSnapshotJobs, and locate the MergeDynamicSnapshotJob object for the newly added partitioned snapshot job in the returned array.

  12. Get the Name property for the job.

  13. Create a connection to the Distributor by using the ServerConnection class.

  14. Create an instance of the SQL Server Management Objects (SMO) Server class, passing the ServerConnection object from step 13.

  15. Create an instance of the Job class, passing the JobServer property of the Server object from step 14 and the job name from step 12.

  16. Call the Start method to start the partitioned snapshot job.

  17. Repeat steps 6-16 for each Subscriber.

To create a publication and manually create snapshots for each partition

  1. Use an instance of the MergePublication class to define a merge publication. For more information, see How to: Create a Publication (RMO Programming).

  2. Use the MergeArticle property to add articles to the publication Specify the FilterClause property for at least one article that defines the parameterized filter, and create any MergeJoinFilter objects that define join filters between articles. For more information, see How to: Define an Article (RMO Programming).

  3. Generate the initial snapshot. For more information, see How to: Create the Initial Snapshot (RMO Programming).

  4. Create an instance of the SnapshotGenerationAgent class, and set the following required properties:

  5. Set a value of Merge for ReplicationType.

  6. Set one or more of the following properties to define the partitioning parameters:

  7. Call the GenerateSnapshot method.

  8. Repeat steps 4-7 for each Subscriber.

This example creates a merge publication that allows Subscribers to requested snapshot generation.

			// 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


This example manually creates the Subscriber partition and the filtered snapshot for a merge publication with parameterized row filters.

			// 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


This example manually starts the Snapshot Agent to generate the filtered data snapshot for a Subscriber to a merge publication with parameterized row filters.

			// 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


Community Additions

ADD
Show:
© 2014 Microsoft