Membuat Publikasi

Berlaku untuk: SQL ServerAzure SQL Managed Instance

Artikel ini menjelaskan cara membuat publikasi di SQL Server dengan menggunakan SQL Server Management Studio, Transact-SQL, atau Replication Management Objects (RMO).

Pembatasan dan batasan

  • Nama publikasi dan artikel tidak dapat menyertakan salah satu karakter berikut: %, , , *[, ], |:"?, ', \, , /, , <, atau .> Jika objek dalam database menyertakan salah satu karakter ini dan Anda ingin mereplikasinya, Anda harus menentukan nama artikel yang berbeda dari nama objek di kotak dialog Properti Artikel - >Artikel, yang tersedia dari halaman Artikel di wizard.

Keamanan

Jika memungkinkan, minta pengguna untuk memasukkan kredensial keamanan saat runtime. Jika Anda harus menyimpan kredensial, gunakan layanan kriptografi yang disediakan oleh Microsoft Windows .NET Framework.

Menggunakan SQL Server Management Studio

Buat publikasi dan tentukan artikel dengan Panduan Publikasi Baru. Setelah publikasi dibuat, tampilkan dan ubah properti publikasi di kotak dialog Properti Publikasi - <Publikasi> . Untuk informasi tentang membuat publikasi dari database Oracle, lihat Membuat Publikasi dari Oracle Database.

Membuat publikasi dan menentukan artikel

  1. Sambungkan ke Publisher di Microsoft SQL Server Management Studio, lalu perluas simpul server.

  2. Perluas folder Replikasi, lalu klik kanan folder Publikasi Lokal.

  3. Pilih Publikasi Baru.

  4. Ikuti halaman di Panduan Publikasi Baru untuk:

    • Tentukan Distributor jika distribusi belum dikonfigurasi di server. Untuk informasi selengkapnya tentang mengonfigurasi distribusi, lihat Mengonfigurasi Penerbitan dan Distribusi.

      Jika Anda menentukan di halaman Distributor bahwa server Publisher akan bertindak sebagai Distributornya sendiri (Distributor lokal), dan server tidak dikonfigurasi sebagai Distributor, Wizard Publikasi Baru akan mengonfigurasi server. Anda akan menentukan folder cuplikan default untuk Distributor pada halaman Folder Cuplikan. Folder rekam jepret hanyalah direktori yang telah Anda tetapkan sebagai berbagi; agen yang membaca dari dan menulis ke folder ini harus memiliki izin yang memadai untuk mengaksesnya. Untuk informasi selengkapnya tentang cara mengamankan folder dengan semestinya, lihat Mengamankan Folder Snapshot.

      Jika Anda menentukan bahwa server lain harus bertindak sebagai Distributor, Anda harus memasukkan kata sandi di halaman Kata Sandi Administratif untuk koneksi yang dibuat dari Penerbit ke Distributor. Kata sandi ini harus cocok dengan kata sandi yang ditentukan ketika Publisher diaktifkan di Distributor jarak jauh.

      Untuk informasi selengkapnya, lihat Mengonfigurasi Distribusi.

    • Pilih database publikasi.

    • Pilih jenis publikasi. Untuk informasi selengkapnya, lihat Jenis Replikasi.

    • Tentukan data dan objek database yang akan diterbitkan; secara opsional memfilter kolom dari artikel tabel, dan mengatur properti artikel.

    • Secara opsional memfilter baris dari artikel tabel. Untuk informasi selengkapnya, lihat Memfilter Data yang Dipublikasikan.

    • Atur jadwal Snapshot Agent.

    • Tentukan kredensial tempat agen replikasi berikut berjalan dan membuat koneksi:

      • Agen Rekam Jepret untuk semua publikasi.

      • Agen Pembaca Log untuk semua publikasi transaksional.

      • Agen Pembaca Antrean untuk publikasi transaksional yang memungkinkan pembaruan langganan.

        Untuk informasi selengkapnya, lihat Model Keamanan Agen Replikasi dan Praktik Terbaik Keamanan Replikasi.

    • Secara opsional membuat skrip publikasi. Untuk informasi selengkapnya, lihat Replikasi Skrip.

    • Tentukan nama untuk publikasi.

Menggunakan Transact-SQL

Publikasi dapat dibuat secara terprogram menggunakan prosedur tersimpan replikasi. Prosedur tersimpan yang digunakan akan bergantung pada jenis publikasi yang dibuat.

Membuat rekam jepret atau publikasi transaksi

  1. Di Publisher pada database publikasi, jalankan sp_replicationdboption (Transact-SQL) untuk mengaktifkan publikasi database saat ini menggunakan rekam jepret atau replikasi transaksional.

  2. Untuk publikasi transaksional, tentukan apakah ada tugas Agen Pembaca Log untuk database publikasi tersebut. (Langkah ini tidak diperlukan untuk publikasi rekam jepret.)

    • Jika ada pekerjaan Agen Pembaca Log untuk database publikasi, lanjutkan ke langkah 3.

    • Jika Anda tidak yakin apakah tugas Agen Pembaca Log ada untuk database yang dipublikasikan, jalankan sp_helplogreader_agent (Transact-SQL) pada Penerbit di database publikasi.

    • Jika kumpulan hasil kosong, buat tugas Log Reader Agent. Di Publisher, jalankan sp_addlogreader_agent (Transact-SQL). Tentukan kredensial Microsoft Windows yang digunakan agen untuk berjalan pada @job_name dan @password. Jika agen akan menggunakan Autentikasi SQL Server saat menyambungkan ke Penerbit, Anda juga harus menentukan nilai 0 untuk @publisher_security_mode dan informasi masuk SQL Server untuk @publisher_login dan @publisher_password. Lanjutkan ke langkah 3.

  3. Di Publisher, jalankan sp_addpublication (Transact-SQL). Tentukan nama publikasi untuk @publication, dan, untuk @repl_freq parameter , tentukan nilai snapshot untuk publikasi rekam jepret atau nilai continuous untuk publikasi transaksi. Tentukan opsi publikasi lainnya. Ini mendefinisikan publikasi.

    Catatan

    Nama publikasi tidak dapat menyertakan karakter berikut:

    %, *, [, ], |, :, ", ?, \, /, <, atau >.

  4. Di Publisher, jalankan sp_addpublication_snapshot (Transact-SQL). Tentukan nama publikasi yang digunakan di langkah 3 untuk @publication dan kredensial Windows tempat Agen Rekam Jepret berjalan untuk @snapshot_job_name dan @password. Jika agen akan menggunakan Autentikasi SQL Server saat menyambungkan ke Penerbit, Anda juga harus menentukan nilai 0 untuk @publisher_security_mode dan informasi masuk SQL Server untuk @publisher_login dan publisher_password. Ini membuat pekerjaan Agen Rekam Jepret untuk publikasi.

    Penting

    Saat mengonfigurasi Penerbit dengan Distributor jarak jauh, nilai yang disediakan untuk semua parameter, termasuk job_login dan job_password, dikirim ke Distributor sebagai teks biasa. Anda harus mengenkripsi koneksi antara Publisher dan Distributor jarak jauhnya sebelum menjalankan prosedur tersimpan ini. Untuk informasi selengkapnya, lihat Mengaktifkan Koneksi Terenkripsi ke Mesin Database (Pengelola Konfigurasi SQL Server).

  5. Tambahkan artikel ke publikasi. Untuk informasi selengkapnya, lihat Menentukan Artikel.

  6. Mulai pekerjaan Agen Rekam Jepret untuk menghasilkan rekam jepret awal untuk publikasi ini. Untuk informasi selengkapnya, lihat Membuat dan Menerapkan Rekam Jepret Awal.

Buat publikasi gabungan

  1. Di Publisher, jalankan sp_replicationdboption (Transact-SQL) untuk mengaktifkan publikasi database saat ini menggunakan replikasi penggabungan.

  2. Di Publisher pada database publikasi, jalankan sp_addmergepublication (Transact-SQL). Tentukan nama untuk publikasi untuk @publication dan opsi publikasi lainnya. Ini mendefinisikan publikasi.

    Catatan

    Nama publikasi tidak dapat menyertakan karakter berikut:

    %, *, [, ], |, :, ", ?, \, /, <, atau >.

  3. Di Publisher, jalankan sp_addpublication_snapshot (Transact-SQL). Tentukan nama publikasi yang digunakan di langkah 2 untuk @publication dan kredensial Windows tempat Agen Rekam Jepret berjalan untuk @snapshot_job_name dan @password. Jika agen akan menggunakan Autentikasi SQL Server saat menyambungkan ke Penerbit, Anda juga harus menentukan nilai 0 untuk @publisher_security_mode dan informasi masuk SQL Server untuk @publisher_login dan @publisher_password. Ini membuat pekerjaan Agen Rekam Jepret untuk publikasi.

    Penting

    Saat mengonfigurasi Penerbit dengan Distributor jarak jauh, nilai yang disediakan untuk semua parameter, termasuk job_login dan job_password, dikirim ke Distributor sebagai teks biasa. Anda harus mengenkripsi koneksi antara Publisher dan Distributor jarak jauhnya sebelum menjalankan prosedur tersimpan ini. Untuk informasi selengkapnya, lihat Mengaktifkan Koneksi Terenkripsi ke Mesin Database (Pengelola Konfigurasi SQL Server).

  4. Tambahkan artikel ke publikasi. Untuk informasi selengkapnya, lihat Menentukan Artikel.

  5. Mulai pekerjaan Agen Rekam Jepret untuk menghasilkan rekam jepret awal untuk publikasi ini. Untuk informasi selengkapnya, lihat Membuat dan Menerapkan Rekam Jepret Awal.

Contoh (Transact-SQL)

Contoh ini membuat publikasi transaksional. Variabel pembuatan skrip digunakan untuk meneruskan kredensial Windows yang diperlukan untuk membuat pekerjaan untuk Agen Rekam Jepret dan Agen Pembaca Log.

-- To avoid storing the login and password in the script file, the values 
-- are passed into SQLCMD as scripting variables. For information about 
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

DECLARE @publicationDB AS sysname;
DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks'; 
SET @publication = N'AdvWorksProductTran'; 
-- Windows account used to run the Log Reader and Snapshot Agents.
SET @login = $(Login); 
-- This should be passed at runtime.
SET @password = $(Password); 

-- Enable transactional or snapshot replication on the publication database.
EXEC sp_replicationdboption 
    @dbname=@publicationDB, 
    @optname=N'publish',
    @value = N'true';

-- Execute sp_addlogreader_agent to create the agent job. 
EXEC sp_addlogreader_agent 
    @job_login = @login, 
    @job_password = @password,
    -- Explicitly specify the use of Windows Integrated Authentication (default) 
    -- when connecting to the Publisher.
    @publisher_security_mode = 1;

-- Create a new transactional publication with the required properties. 
EXEC sp_addpublication 
    @publication = @publication, 
    @status = N'active',
    @allow_push = N'true',
    @allow_pull = N'true',
    @independent_agent = N'true';

-- Create a new snapshot job for the publication, using a default schedule.
EXEC sp_addpublication_snapshot 
    @publication = @publication, 
    @job_login = @login, 
    @job_password = @password,
    -- Explicitly specify the use of Windows Integrated Authentication (default) 
    -- when connecting to the Publisher.
    @publisher_security_mode = 1;
GO

Contoh ini membuat publikasi gabungan. Variabel skrip digunakan untuk meneruskan kredensial Windows yang diperlukan guna membuat tugas untuk Snapshot Agent.

-- To avoid storing the login and password in the script file, the value 
-- is passed into SQLCMD as a scripting variable. For information about 
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

--Declarations for adding a merge publication
DECLARE @publicationDB AS sysname;
DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks2022'; 
SET @publication = N'AdvWorksSalesOrdersMerge'; 
SET @login = $(Login);
SET @password = $(Password);

-- Enable merge replication on the publication database, using defaults.
USE master
EXEC sp_replicationdboption 
  @dbname=@publicationDB, 
  @optname=N'merge publish',
  @value = N'true' 

-- Create a new merge publication, explicitly setting the defaults. 
USE [AdventureWorks2022]
EXEC sp_addmergepublication 
-- These parameters are optional.
  @publication = @publication,
  -- optional parameters 
  @description = N'Merge publication of AdventureWorks2022.',
  @publication_compatibility_level  = N'120RTM';

-- Create a new snapshot job for the publication.
EXEC sp_addpublication_snapshot 
  @publication = @publication, 
  @job_login = @login, 
  @job_password = @password;
GO

Menggunakan Objek Manajemen Replikasi (RMO)

Anda dapat membuat publikasi secara terprogram dengan menggunakan Objek Manajemen Replikasi (RMO). Kelas RMO yang Anda gunakan untuk membuat publikasi bergantung pada jenis publikasi yang Anda buat.

Membuat rekam jepret atau publikasi transaksi

  1. Buat koneksi ke Publisher dengan menggunakan ServerConnection kelas .

  2. Buat instans kelas ReplicationDatabase untuk basis data publikasi, atur properti ConnectionContext menjadi instans ServerConnection dari langkah 1, dan panggil metode LoadProperties. Jika LoadProperties mengembalikan false, verifikasi bahwa database ada.

  3. EnabledTransPublishing Jika properti adalah false, atur ke true.

  4. Untuk publikasi transaksional, periksa nilai properti LogReaderAgentExists. Jika properti ini adalah true, pekerjaan Agen Baca Log sudah ada untuk database ini. Jika properti ini adalah false, lakukan hal berikut:

  5. Buat instans TransPublication kelas, dan atur properti berikut untuk objek ini:

  6. Create Panggil metode untuk membuat publikasi.

    Penting

    Saat mengonfigurasi Penerbit dengan Distributor jarak jauh, nilai yang disediakan untuk semua properti, termasuk SnapshotGenerationAgentProcessSecurity, dikirim ke Distributor sebagai teks biasa. Anda harus mengenkripsi koneksi antara Publisher dan Distributor jarak jauhnya sebelum memanggil Create metode . Untuk informasi selengkapnya, lihat Mengaktifkan Koneksi Terenkripsi ke Mesin Database (Pengelola Konfigurasi SQL Server).

  7. Panggil metode CreateSnapshotAgent untuk membuat job Snapshot Agent untuk publikasi.

Buat publikasi gabungan

  1. Buat koneksi ke Publisher dengan menggunakan ServerConnection kelas .

  2. Buat instans kelas ReplicationDatabase untuk basis data publikasi, atur properti ConnectionContext menjadi instans ServerConnection dari langkah 1, lalu panggil metode LoadProperties. Jika LoadProperties mengembalikan false, verifikasi bahwa database ada.

  3. Jika properti EnabledMergePublishing adalah false, atur menjadi true, dan panggil CommitPropertyChanges.

  4. Buat instans MergePublication kelas, dan atur properti berikut untuk objek ini:

    • ServerConnection dari langkah 1 untuk ConnectionContext.

    • Nama database yang dipublikasikan untuk DatabaseName.

    • Nama publikasi untuk Name.

    • Bidang Login dan Password pada SnapshotGenerationAgentProcessSecurity digunakan untuk memberikan kredensial bagi akun Windows yang digunakan untuk menjalankan Snapshot Agent. Akun ini juga digunakan ketika Agen Rekam Jepret membuat koneksi ke Distributor lokal dan untuk koneksi jarak jauh apa pun saat menggunakan Autentikasi Windows.

      Catatan

      Pengaturan SnapshotGenerationAgentProcessSecurity tidak diperlukan saat publikasi dibuat oleh anggota peran server tetap sysadmin. Untuk informasi selengkapnya, lihat Model Keamanan Agen Replikasi.

    • (Opsional) Gunakan operator OR logis inklusif (| di Visual C# dan Or di Visual Basic) dan operator OR logis eksklusif (^ di Visual C# dan Xor di Visual Basic) untuk mengatur PublicationAttributes nilai untuk Attributes properti .

  5. Create Panggil metode untuk membuat publikasi.

    Penting

    Saat mengonfigurasi Penerbit dengan Distributor jarak jauh, nilai yang disediakan untuk semua properti, termasuk SnapshotGenerationAgentProcessSecurity, dikirim ke Distributor sebagai teks biasa. Anda harus mengenkripsi koneksi antara Publisher dan Distributor jarak jauhnya sebelum memanggil Create metode . Untuk informasi selengkapnya, lihat Mengaktifkan Koneksi Terenkripsi ke Mesin Database (Pengelola Konfigurasi SQL Server).

  6. Panggil metode CreateSnapshotAgent untuk membuat job Snapshot Agent untuk publikasi.

Contoh (RMO)

Contoh ini mengaktifkan database AdventureWorks untuk publikasi transaksional, mendefinisikan tugas agen Pembaca Log, dan membuat publikasi AdvWorksProductTran. Sebuah artikel harus ditetapkan untuk publikasi ini. Kredensial akun Windows yang diperlukan untuk membuat tugas Agen Pembaca Log dan tugas Agen Snapshot diteruskan saat dijalankan. Untuk mempelajari cara menggunakan RMO untuk menentukan rekam jepret dan artikel transaksional, lihat Menentukan Artikel.

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

ReplicationDatabase publicationDb;
TransPublication publication;

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


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

    // Enable the AdventureWorks2022 database for transactional publishing.
    publicationDb = new ReplicationDatabase(publicationDbName, conn);

    // If the database exists and is not already enabled, 
    // enable it for transactional publishing.
    if (publicationDb.LoadProperties())
    {
        if (!publicationDb.EnabledTransPublishing)
        {
            publicationDb.EnabledTransPublishing = true;
        }

        // If the Log Reader Agent does not exist, create it.
        if (!publicationDb.LogReaderAgentExists)
        {
            // Specify the Windows account under which the agent job runs.
            // This account will be used for the local connection to the 
            // Distributor and all agent connections that use Windows Authentication.
            publicationDb.LogReaderAgentProcessSecurity.Login = winLogin;
            publicationDb.LogReaderAgentProcessSecurity.Password = winPassword;

            // Explicitly set authentication mode for the Publisher connection
            // to the default value of Windows Authentication.
            publicationDb.LogReaderAgentPublisherSecurity.WindowsAuthentication = true;

            // Create the Log Reader Agent job.
            publicationDb.CreateLogReaderAgent();
        }
    }
    else
    {
        throw new ApplicationException(String.Format(
            "The {0} database does not exist at {1}.",
            publicationDb, publisherName));
    }

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

    // Specify a transactional publication (the default).
    publication.Type = PublicationType.Transactional;

    // Activate the publication so that we can add subscriptions.
    publication.Status = State.Active;

    // Enable push and pull subscriptions and independent Distribition Agents.
    publication.Attributes |= PublicationAttributes.AllowPull;
    publication.Attributes |= PublicationAttributes.AllowPush;
    publication.Attributes |= PublicationAttributes.IndependentAgent;

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

    if (!publication.IsExistingObject)
    {
        // Create the transactional 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 publicationName As String = "AdvWorksProductTran"
Dim publicationDbName As String = "AdventureWorks2022"
Dim publisherName As String = publisherInstance

Dim publicationDb As ReplicationDatabase
Dim publication As TransPublication

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

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

    ' Enable the AdventureWorks2022 database for transactional publishing.
    publicationDb = New ReplicationDatabase(publicationDbName, conn)

    ' If the database exists and is not already enabled, 
    ' enable it for transactional publishing.
    If publicationDb.LoadProperties() Then
        If Not publicationDb.EnabledTransPublishing Then
            publicationDb.EnabledTransPublishing = True
        End If

        ' If the Log Reader Agent does not exist, create it.
        If Not publicationDb.LogReaderAgentExists Then
            ' Specify the Windows account under which the agent job runs.
            ' This account will be used for the local connection to the 
            ' Distributor and all agent connections that use Windows Authentication.
            publicationDb.LogReaderAgentProcessSecurity.Login = winLogin
            publicationDb.LogReaderAgentProcessSecurity.Password = winPassword

            ' Explicitly set authentication mode for the Publisher connection
            ' to the default value of Windows Authentication.
            publicationDb.LogReaderAgentPublisherSecurity.WindowsAuthentication = True

            ' Create the Log Reader Agent job.
            publicationDb.CreateLogReaderAgent()
        End If
    Else
        Throw New ApplicationException(String.Format( _
         "The {0} database does not exist at {1}.", _
         publicationDb, publisherName))
    End If

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

    ' Specify a transactional publication (the default).
    publication.Type = PublicationType.Transactional

    'Enable push and pull subscriptions and independent Distribition Agents.
    publication.Attributes = _
    publication.Attributes Or PublicationAttributes.AllowPull
    publication.Attributes = _
    publication.Attributes Or PublicationAttributes.AllowPush
    publication.Attributes = _
    publication.Attributes Or PublicationAttributes.IndependentAgent

    ' Activate the publication so that we can add subscriptions.
    publication.Status = State.Active

    ' 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

    If Not publication.IsExistingObject Then
        ' Create the transactional 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

Contoh ini mengaktifkan database AdventureWorks untuk publikasi gabungan dan membuat publikasi AdvWorksSalesOrdersMerge. Artikel masih harus didefinisikan untuk publikasi ini. Kredensial akun Windows yang diperlukan untuk membuat tugas Snapshot Agent diteruskan saat proses berjalan. Untuk mempelajari cara menggunakan RMO untuk menentukan artikel penggabungan, lihat Menentukan Artikel.

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

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 = "AdventureWorks2022"

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