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.
Note
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 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
Create a connection to the Publisher by using the ServerConnection class.
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.
If EnabledMergePublishing property is false, set it to true and call CommitPropertyChanges.
Create an instance of the MergePublication class, and set the following properties for this object:
The ServerConnection from step 1 for ConnectionContext.
The name of the published database for DatabaseName.
A name for the publication for Name.
The maximum number of dynamic snapshot jobs to run for MaxConcurrentDynamicSnapshots. Because Subscriber initiated snapshot requests can occur at any time, this property limits the number of Snapshot Agent jobs that can run simultaneously when multiple Subscribers request their partitioned snapshot at the same time. When the maximum number of jobs are running, additional partitioned snapshot requests are queued until one of the running jobs is completed.
Use the bitwise logical OR (| in Visual C# and Or in Visual Basic) operator to add the value AllowSubscriberInitiatedSnapshot to Attributes.
The Login and Password fields of SnapshotGenerationAgentProcessSecurity to provide the credentials for the Microsoft Windows account under which the Snapshot Agent job runs.
Note
Setting SnapshotGenerationAgentProcessSecurity is recommended when the publication is created by a member of the sysadmin fixed server role. For more information, see Replication Agent Security Model.
Call the Create method to create the publication.
Security 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.
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).
If the value of SnapshotAgentExists is false, call CreateSnapshotAgent to create the initial Snapshot Agent job for this publication.
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).
(Optional) Check for a value of true for the SnapshotAvailable property to determine when the initial snapshot is ready for use.
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
Use an instance of the MergePublication class to define a merge publication. For more information, see How to: Create a Publication (RMO Programming).
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).
If the value of SnapshotAgentExists is false, call CreateSnapshotAgent to create the snapshot agent job for this publication.
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).
Check for a value of true for the SnapshotAvailable property to determine when the initial snapshot is ready for use.
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:
If the Subscriber's partition is defined by the result of SUSER_SNAME (Transact-SQL), use DynamicFilterLogin.
If the Subscriber's partition is defined by the result of HOST_NAME (Transact-SQL) or an overload of this function, use DynamicFilterHostName.
Create an instance of the MergeDynamicSnapshotJob class, and set the same property as in step 6.
Use the ReplicationAgentSchedule class to define a schedule for generating the filtered snapshot for the Subscriber partition.
Using the instance of MergePublication from step 1, call AddMergePartition. Pass the MergePartition object from step 6.
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.
Call EnumMergeDynamicSnapshotJobs, and locate the MergeDynamicSnapshotJob object for the newly added partitioned snapshot job in the returned array.
Get the Name property for the job.
Create a connection to the Distributor by using the ServerConnection class.
Create an instance of the SQL Server Management Objects (SMO) Server class, passing the ServerConnection object from step 13.
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.
Call the Start method to start the partitioned snapshot job.
Repeat steps 6-16 for each Subscriber.
To create a publication and manually create snapshots for each partition
Use an instance of the MergePublication class to define a merge publication. For more information, see How to: Create a Publication (RMO Programming).
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).
Generate the initial snapshot. For more information, see How to: Create the Initial Snapshot (RMO Programming).
Create an instance of the SnapshotGenerationAgent class, and set the following required properties:
Publisher - name of the Publisher
PublisherDatabase - name of the publication database
Publication - name of the publication
Distributor - name of the Distributor
PublisherSecurityMode - a value of Integrated to used Windows Integrated Authentication or a value of Standard to use SQL Server Authentication.
DistributorSecurityMode - a value of Integrated to used Windows Integrated Authentication or a value of Standard to use SQL Server Authentication.
Set a value of Merge for ReplicationType.
Set one or more of the following properties to define the partitioning parameters:
If the Subscriber's partition is defined by the result of SUSER_SNAME (Transact-SQL), use DynamicFilterLogin.
If the Subscriber's partition is defined by the result of HOST_NAME (Transact-SQL) or an overload of this function, use DynamicFilterHostName.
Call the GenerateSnapshot method.
Repeat steps 4-7 for each Subscriber.
Example
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 = "AdventureWorks";
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 = "AdventureWorks"
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 = "AdventureWorks";
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 = "AdventureWorks"
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 = "AdventureWorks";
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 = "AdventureWorks"
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
See Also