Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Bu konuda, çoğaltma programlama veya Çoğaltma Yönetim Nesneleri (RMO) kullanarak SQL Server'da bir birleşik makale için iş mantığı işleyicisinin uygulanması açıklanmaktadır.
Microsoft.SqlServer.Replication.BusinessLogicSupport ad alanı, birleştirme çoğaltma eşitleme işlemi sırasında gerçekleşen olayları yönetmek üzere karmaşık iş mantığı yazabilmenizi sağlayan bir arabirimi uygular. İş mantığı işleyicisindeki yöntemler, eşitleme sırasında çoğaltılan her değiştirilen satır için çoğaltma işlemi tarafından çağrılabilir.
İş mantığı işleyicisi uygulamak için genel süreç şu şekildedir:
İş mantığı işleyici derlemesini oluşturun.
Montajı Dağıtımcıya kaydedin.
Birleştirme Aracısı'nın çalıştığı sunucuda derlemeyi dağıtın. Çekme aboneliği için aracı Abone üzerinde çalışır ve bir anında iletme aboneliği için aracı Dağıtımcı üzerinde çalışır. Web eşitlemesi kullanırken aracı Web sunucusunda çalışır.
İş mantığı işleyicisini kullanan bir makale oluşturun veya iş mantığı işleyicisini kullanmak için var olan bir makaleyi değiştirin.
Belirttiğiniz iş mantığı işleyicisi eşitlenen her satır için yürütülür. Karmaşık mantık ve diğer uygulamalara veya ağ hizmetlerine yapılan çağrılar performansı etkileyebilir. İş mantığı işleyicileri hakkında daha fazla bilgi için bkz. Birleştirme Eşitlemesi Sırasında İş Mantığı Yürütme.
Bu Konuda
Birleştirme makalesi için iş mantığı işleyicisi uygulamak için şunları kullanın:
Replikasyon Programlamasını Kullanma
İş mantığı işleyicisi oluşturmak ve dağıtmak için
Microsoft Visual Studio'da, iş mantığı işleyicisini uygulayan kodu içeren .NET derlemesi için yeni bir proje oluşturun.
Aşağıdaki ad alanları için projeye referanslar ekleyin.
Derleme Kaynağı Yer Microsoft.SqlServer.Replication.BusinessLogicSupport < sürücü>:\Program Files\Microsoft SQL Server\nnn\COM (varsayılan yükleme) System.Data GAC (.NET Framework bileşeni) System.Data.Common GAC (.NET Framework bileşeni) sınıfını geçersiz kılan BusinessLogicModule bir sınıf ekleyin.
HandledChangeStates İşlenen değişiklik türlerini belirtmek için özelliğini uygulayın.
Sınıfının aşağıdaki yöntemlerinden BusinessLogicModule birini veya daha fazlasını geçersiz kılın:
CommitHandler - eşitleme sırasında bir veri değişikliği işlendiğinde çağrılır.
DeleteErrorHandler - DELETE ifadesi yüklenirken veya indirilirken bir hata oluştuğunda çağrılır.
DeleteHandler - Silme ifadeleri yüklenirken veya indirilirken çağrılır.
InsertErrorHandler - INSERT ifadesi yüklenirken veya indirilirken bir hata oluştuğunda çağrılır.
InsertHandler - INSERT ifadeleri yüklenirken veya indirildiğinde çağrılır.
UpdateConflictsHandler - Yayımcı ve Abone'de çakışan UPDATE deyimleri oluştuğunda çağrılır.
UpdateDeleteConflictHandler - UPDATE deyimleri Yayımlayıcı ve Abonede DELETE deyimleriyle çakıştığında tetiklenir.
UpdateErrorHandler - UPDATE deyimi karşıya yüklenirken veya indirilirken bir hata oluştuğunda çağrılır.
UpdateHandler - UPDATE deyimleri karşıya yüklenirken veya indirilirken çağrılır.
İş mantığı işleyici derlemesini oluşturmak için projeyi oluşturun.
Derlemeyi, varsayılan yüklemede <sürücü>:\Program Files\Microsoft SQL Server\nnn\COM olan Birleştirme Aracısı yürütülebilir dosyasını (replmerg.exe) içeren dizine dağıtın veya .NET genel derleme önbelleğine (GAC) yükleyin. Derlemeyi yalnızca Birleştirme Aracısı dışındaki uygulamalar derlemeye erişim gerektiriyorsa GAC'ye yüklemeniz gerekir. Derleme, .NET Framework SDK'sında sağlanan Genel Derleme Önbelleği aracı (Gacutil.exe) kullanılarak GAC'ye yüklenebilir.
Uyarı
Web eşitlemesi kullanılırken replisapi.dll barındıran IIS sunucusunu içeren Birleştirme Aracısı'nın çalıştığı her sunucuya bir iş mantığı işleyicisi dağıtılmalıdır.
İş mantığı işleyicisini kaydetmek için
sp_enumcustomresolvers (Transact-SQL) ifadesini yürütüp derlemenin iş mantığı işleyicisi olarak zaten kaydedilip kaydedilmediğini doğrulamak için Publisher'da çalıştırın.
Dağıtımcıda, @article_resolver için iş mantığı işleyicisi için kolay bir ad, @is_dotnet_assembly için true değeri, @dotnet_assembly_name derlemesinin adı ve @dotnet_class_name için geçersiz kılan BusinessLogicModule sınıfın tam adını belirterek sp_registercustomresolver ( Transact-SQL) yürütür.
Uyarı
Derleme Birleştirme Aracısı yürütülebilir dosyasıyla aynı dizinde dağıtılmazsa, Birleştirme Aracısı'nı zaman uyumlu olarak başlatan uygulamayla aynı dizinde veya genel derleme önbelleğinde (GAC) @dotnet_assembly_name için derleme adıyla tam yolu belirtmeniz gerekir. Web eşitlemesini kullanırken, derlemenin Web sunucusunda konumunu belirtmeniz gerekir.
Yeni bir tablo makalesiyle iş mantığı işleyicisi kullanmak için
- Bir makale tanımlamak için sp_addmergearticle (Transact-SQL) komutunu yürüterek, @article_resolver için iş mantığı işleyicisinin kolay adını belirtin. Daha fazla bilgi için bkz. Makale Tanımlama.
Var olan bir tablo makalesiyle iş mantığı işleyicisini kullanmak için
- sp_changemergearticle (Transact-SQL) yürüterek, @publication, @article, @property için article_resolver değerini ve @value için iş mantığı işleyicisinin kolay adını belirtin.
Örnekler (Çoğaltma Programlama)
Bu örnekte, denetim günlüğü oluşturan bir iş mantığı işleyicisi gösterilmektedir.
using System;
using System.Text;
using System.Data;
using System.Data.Common;
using Microsoft.SqlServer.Replication.BusinessLogicSupport;
using Microsoft.Samples.SqlServer.BusinessLogicHandler;
namespace Microsoft.Samples.SqlServer.BusinessLogicHandler
{
public class OrderEntryBusinessLogicHandler :
Microsoft.SqlServer.Replication.BusinessLogicSupport.BusinessLogicModule
{
// Variables to hold server names.
private string publisherName;
private string subscriberName;
public OrderEntryBusinessLogicHandler()
{
}
// Implement the Initialize method to get publication
// and subscription information.
public override void Initialize(
string publisher,
string subscriber,
string distributor,
string publisherDB,
string subscriberDB,
string articleName)
{
// Set the Publisher and Subscriber names.
publisherName = publisher;
subscriberName = subscriber;
}
// Declare what types of row changes, conflicts, or errors to handle.
override public ChangeStates HandledChangeStates
{
get
{
// Handle Subscriber inserts, updates and deletes.
return ChangeStates.SubscriberInserts |
ChangeStates.SubscriberUpdates | ChangeStates.SubscriberDeletes;
}
}
public override ActionOnDataChange InsertHandler(SourceIdentifier insertSource,
DataSet insertedDataSet, ref DataSet customDataSet, ref int historyLogLevel,
ref string historyLogMessage)
{
if (insertSource == SourceIdentifier.SourceIsSubscriber)
{
// Build a line item in the audit message to log the Subscriber insert.
StringBuilder AuditMessage = new StringBuilder();
AuditMessage.Append(String.Format("A new order was entered at {0}. " +
"The SalesOrderID for the order is :", subscriberName));
AuditMessage.Append(insertedDataSet.Tables[0].Rows[0]["SalesOrderID"].ToString());
AuditMessage.Append("The order must be shipped by :");
AuditMessage.Append(insertedDataSet.Tables[0].Rows[0]["DueDate"].ToString());
// Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString();
// Set the history log level to the default verbose level.
historyLogLevel = 1;
// Accept the inserted data in the Subscriber's data set and
// apply it to the Publisher.
return ActionOnDataChange.AcceptData;
}
else
{
return base.InsertHandler(insertSource, insertedDataSet, ref customDataSet,
ref historyLogLevel, ref historyLogMessage);
}
}
public override ActionOnDataChange UpdateHandler(SourceIdentifier updateSource,
DataSet updatedDataSet, ref DataSet customDataSet, ref int historyLogLevel,
ref string historyLogMessage)
{
if (updateSource == SourceIdentifier.SourceIsPublisher)
{
// Build a line item in the audit message to log the Subscriber update.
StringBuilder AuditMessage = new StringBuilder();
AuditMessage.Append(String.Format("An existing order was updated at {0}. " +
"The SalesOrderID for the order is ", subscriberName));
AuditMessage.Append(updatedDataSet.Tables[0].Rows[0]["SalesOrderID"].ToString());
AuditMessage.Append("The order must now be shipped by :");
AuditMessage.Append(updatedDataSet.Tables[0].Rows[0]["DueDate"].ToString());
// Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString();
// Set the history log level to the default verbose level.
historyLogLevel = 1;
// Accept the updated data in the Subscriber's data set and apply it to the Publisher.
return ActionOnDataChange.AcceptData;
}
else
{
return base.UpdateHandler(updateSource, updatedDataSet,
ref customDataSet, ref historyLogLevel, ref historyLogMessage);
}
}
public override ActionOnDataDelete DeleteHandler(SourceIdentifier deleteSource,
DataSet deletedDataSet, ref int historyLogLevel, ref string historyLogMessage)
{
if (deleteSource == SourceIdentifier.SourceIsSubscriber)
{
// Build a line item in the audit message to log the Subscriber deletes.
// Note that the rowguid is the only information that is
// available in the dataset.
StringBuilder AuditMessage = new StringBuilder();
AuditMessage.Append(String.Format("An existing order was deleted at {0}. " +
"The rowguid for the order is ", subscriberName));
AuditMessage.Append(deletedDataSet.Tables[0].Rows[0]["rowguid"].ToString());
// Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString();
// Set the history log level to the default verbose level.
historyLogLevel = 1;
// Accept the delete and apply it to the Publisher.
return ActionOnDataDelete.AcceptDelete;
}
else
{
return base.DeleteHandler(deleteSource, deletedDataSet,
ref historyLogLevel, ref historyLogMessage);
}
}
}
}
Imports System
Imports System.Text
Imports System.Data
Imports System.Data.Common
Imports Microsoft.SqlServer.Replication.BusinessLogicSupport
Namespace Microsoft.Samples.SqlServer.BusinessLogicHandler
Public Class OrderEntryBusinessLogicHandler
Inherits BusinessLogicModule
' Variables to hold server names.
Private publisherName As String
Private subscriberName As String
' Implement the Initialize method to get publication
' and subscription information.
Public Overrides Sub Initialize( _
ByVal publisher As String, _
ByVal subscriber As String, _
ByVal distributor As String, _
ByVal publisherDB As String, _
ByVal subscriberDB As String, _
ByVal articleName As String _
)
' Set the Publisher and Subscriber names.
publisherName = publisher
subscriberName = subscriber
End Sub
' Declare what types of row changes, conflicts, or errors to handle.
Public Overrides ReadOnly Property HandledChangeStates() As ChangeStates
Get
' Handle Subscriber inserts, updates and deletes.
Return (ChangeStates.SubscriberInserts Or _
ChangeStates.SubscriberUpdates Or ChangeStates.SubscriberDeletes)
End Get
End Property
Public Overrides Function InsertHandler(ByVal insertSource As SourceIdentifier, _
ByVal insertedDataSet As DataSet, ByRef customDataSet As DataSet, _
ByRef historyLogLevel As Integer, ByRef historyLogMessage As String) _
As ActionOnDataChange
If insertSource = SourceIdentifier.SourceIsSubscriber Then
' Build a line item in the audit message to log the Subscriber insert.
Dim AuditMessage As StringBuilder = New StringBuilder()
AuditMessage.Append(String.Format("A new order was entered at {0}. " + _
"The SalesOrderID for the order is :", subscriberName))
AuditMessage.Append(insertedDataSet.Tables(0).Rows(0)("SalesOrderID").ToString())
AuditMessage.Append("The order must be shipped by :")
AuditMessage.Append(insertedDataSet.Tables(0).Rows(0)("DueDate").ToString())
' Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString()
' Set the history log level to the default verbose level.
historyLogLevel = 1
' Accept the inserted data in the Subscriber's data set and
' apply it to the Publisher.
Return ActionOnDataChange.AcceptData
Else
Return MyBase.InsertHandler(insertSource, insertedDataSet, customDataSet, _
historyLogLevel, historyLogMessage)
End If
End Function
Public Overrides Function UpdateHandler(ByVal updateSource As SourceIdentifier, _
ByVal updatedDataSet As DataSet, ByRef customDataSet As DataSet, _
ByRef historyLogLevel As Integer, ByRef historyLogMessage As String) _
As ActionOnDataChange
If updateSource = SourceIdentifier.SourceIsPublisher Then
' Build a line item in the audit message to log the Subscriber update.
Dim AuditMessage As StringBuilder = New StringBuilder()
AuditMessage.Append(String.Format("An existing order was updated at {0}. " + _
"The SalesOrderID for the order is ", subscriberName))
AuditMessage.Append(updatedDataSet.Tables(0).Rows(0)("SalesOrderID").ToString())
AuditMessage.Append("The order must now be shipped by :")
AuditMessage.Append(updatedDataSet.Tables(0).Rows(0)("DueDate").ToString())
' Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString()
' Set the history log level to the default verbose level.
historyLogLevel = 1
' Accept the updated data in the Subscriber's data set and apply it to the Publisher.
Return ActionOnDataChange.AcceptData
Else
Return MyBase.UpdateHandler(updateSource, updatedDataSet, _
customDataSet, historyLogLevel, historyLogMessage)
End If
End Function
Public Overrides Function DeleteHandler(ByVal deleteSource As SourceIdentifier, _
ByVal deletedDataSet As DataSet, ByRef historyLogLevel As Integer, _
ByRef historyLogMessage As String) As ActionOnDataDelete
If deleteSource = SourceIdentifier.SourceIsSubscriber Then
' Build a line item in the audit message to log the Subscriber deletes.
' Note that the rowguid is the only information that is
' available in the dataset.
Dim AuditMessage As StringBuilder = New StringBuilder()
AuditMessage.Append(String.Format("An existing order was deleted at {0}. " + _
"The rowguid for the order is ", subscriberName))
AuditMessage.Append(deletedDataSet.Tables(0).Rows(0)("rowguid").ToString())
' Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString()
' Set the history log level to the default verbose level.
historyLogLevel = 1
' Accept the delete and apply it to the Publisher.
Return ActionOnDataDelete.AcceptDelete
Else
Return MyBase.DeleteHandler(deleteSource, deletedDataSet, _
historyLogLevel, historyLogMessage)
End If
End Function
End Class
End Namespace
Aşağıdaki örnek, Dağıtıcıya bir iş mantığı işleyici derlemesi kaydeder ve mevcut birleşme makalesini bu özel iş mantığını kullanmak üzere değiştirir.
DECLARE @publication AS sysname;
DECLARE @article AS sysname;
DECLARE @friendlyname AS sysname;
DECLARE @assembly AS nvarchar(500);
DECLARE @class AS sysname;
SET @publication = N'AdvWorksCustomers';
SET @article = N'Customers';
SET @friendlyname = N'OrderEntryLogic';
SET @assembly = N'C:\Program Files\Microsoft SQL Server\120\COM\CustomLogic.dll';
SET @class = N'Microsoft.Samples.SqlServer.BusinessLogicHandler.OrderEntryBusinessLogicHandler';
-- Register the business logic handler at the Distributor.
EXEC sys.sp_registercustomresolver
@article_resolver = @friendlyname,
@resolver_clsid = NULL,
@is_dotnet_assembly = N'true',
@dotnet_assembly_name = @assembly,
@dotnet_class_name = @class;
-- Add an article that uses the business logic handler
-- at the Publisher.
EXEC sp_changemergearticle
@publication = @publication,
@article = @article,
@property = N'article_resolver',
@value = @friendlyname,
@force_invalidate_snapshot = 0,
@force_reinit_subscription = 0;
GO
Çoğaltma Yönetimi Nesnelerini (RMO) Kullanma
İş mantığı işleyicisi oluşturmak için
Microsoft Visual Studio'da, iş mantığı işleyicisini uygulayan kodu içeren .NET derlemesi için yeni bir proje oluşturun.
Aşağıdaki ad alanları için projeye referanslar ekleyin.
Derleme Referansı Yer Microsoft.SqlServer.Replication.BusinessLogicSupport < sürücü>:\Program Files\Microsoft SQL Server\nnn\COM (varsayılan yükleme) System.Data GAC (.NET Framework bileşeni) System.Data.Common GAC (.NET Framework bileşeni) sınıfını geçersiz kılan BusinessLogicModule bir sınıf ekleyin.
HandledChangeStates İşlenen değişiklik türlerini belirtmek için özelliğini uygulayın.
Sınıfının aşağıdaki yöntemlerinden BusinessLogicModule birini veya daha fazlasını geçersiz kılın:
CommitHandler - eşitleme sırasında bir veri değişikliği işlendiğinde çağrılır.
DeleteErrorHandler - DELETE deyimi yükleme veya indirme sırasında bir hata oluşması durumunda çağrılır.
DeleteHandler - DELETE ifadesi yüklenirken veya indirilirken çağrılır.
InsertErrorHandler - INSERT deyimi karşıya yüklenirken veya indirilirken bir hata oluşursa çağrılır.
InsertHandler - INSERT deyimleri yüklendiğinde veya indirildiğinde çağrılır.
UpdateConflictsHandler - Yayımcı ve Abone'de çakışan UPDATE deyimleri oluştuğunda çağrılır.
UpdateDeleteConflictHandler - UPDATE deyimleri Publisher ve Abone'deki DELETE deyimleriyle çakıştığında çağrılır.
UpdateErrorHandler - UPDATE deyimi yüklenirken veya indirilirken bir hata oluşursa çağrılır.
UpdateHandler - UPDATE deyimleri karşıya yüklenirken veya indirilirken çağrılır.
Uyarı
Özel iş mantığınız tarafından açıkça işlenmeyen tüm makale çakışmaları, makalenin varsayılan çözümleyicisi tarafından işlenir.
İş mantığı işleyici derlemesini oluşturmak için projeyi oluşturun.
İş mantığı işleyicisini kaydetmek için
sınıfını kullanarak Dağıtımcı ile ServerConnection bağlantı oluşturun.
ReplicationServer sınıfının bir örneğini oluşturun. 1. adımdan ServerConnection'yi geçirin.
EnumBusinessLogicHandlers'ı çağırın ve döndürülen ArrayList nesnesini denetleyerek montajın iş mantığı işleyicisi olarak henüz kaydedilmediğinden emin olun.
BusinessLogicHandler sınıfının bir örneğini oluşturun. Aşağıdaki özellikleri belirtin:
DotNetAssemblyName - .NET derlemesinin adı. Eğer derleme, Birleştirme Aracısı'nın yürütülebilir dosyasıyla aynı dizinde dağıtılmamışsa, Birleştirme Aracısı'nı zaman uyumlu olarak başlatan uygulamayla aynı dizinde veya GAC'de değilse, derleme adıyla tam yolu eklemeniz gerekir. Web eşitlemesi ile bir iş mantığı işleyicisi kullanırken derleme adıyla tam yolu eklemeniz gerekir.
DotNetClassName - BusinessLogicModule'i geçersiz kılan ve iş mantığı işleyicisini uygulayan sınıfın tam adı.
FriendlyName - iş mantığı işleyicisine erişirken kullandığınız kolay ad.
IsDotNetAssembly - true değeri.
İş mantığı işleyicisini dağıtmak için
- Derlemeyi, iş mantığı işleyicisinin Dağıtıcıda kaydedildiği dosya konumunda Birleştirme Aracısı'nın çalıştırıldığı sunucuya dağıtın. Çekme aboneliği için aracı Abone üzerinde çalışır ve bir push aboneliği için aracı Dağıtımcı üzerinde çalışır. Web eşitlemesi kullanırken aracı Web sunucusunda çalışır. İş mantığı işleyicisi kaydedildiğinde tam yol derleme adına dahil edilmediyse, derlemeyi Birleştirme Aracısı yürütülebilir dosyasıyla aynı dizinde, birleştirme aracısını zaman uyumlu olarak başlatan uygulamayla aynı dizinde dağıtın. Aynı derlemeyi kullanan birden çok uygulama varsa, derlemeyi GAC'ye yükleyebilirsiniz.
Yeni bir tablo ile ilgili makalede iş mantığı işleyicisi kullanmak için
sınıfını kullanarak ServerConnection Publisher'a bir bağlantı oluşturun.
MergeArticle sınıfının bir örneğini oluşturun. Aşağıdaki özellikleri ayarlayın:
Name için makalenin adı.
PublicationName yayının adı.
DatabaseName için yayın veritabanının adı.
için ArticleResolver olan iş mantığı işleyicisinin (FriendlyName) kullanıcı dostu adı.
yöntemini çağırın Create . Daha fazla bilgi için bkz. Makale Tanımlama.
Mevcut bir tablo makalesiyle iş mantığı işleyicisini kullanmak için
sınıfını kullanarak ServerConnection Publisher'a bir bağlantı oluşturun.
MergeArticle sınıfının bir örneğini oluşturun.
Name, PublicationNameve DatabaseName özelliklerini ayarlayın.
Özelliği için 1. adımdaki ConnectionContext bağlantıyı ayarlayın.
nesnesinin LoadProperties özelliklerini almak için yöntemini çağırın. Bu yöntem false döndürürse, 3. adımdaki makale özellikleri yanlış tanımlanmıştır veya makale mevcut değildir. Daha fazla bilgi için bkz. Makale Özelliklerini Görüntüleme ve Değiştirme.
ArticleResolver için iş mantığı işleyicisinin kolay ismini belirleyin. Bu, iş mantığı işleyicisi FriendlyName kaydederken belirtilen özelliğin değeridir.
Örnekler (RMO)
Bu örnek, Subscriber'da eklemeler, güncelleştirmeler ve silmeler hakkındaki bilgileri günlüğe kaydeden bir iş mantığı işleyicisidir.
using System;
using System.Text;
using System.Data;
using System.Data.Common;
using Microsoft.SqlServer.Replication.BusinessLogicSupport;
using Microsoft.Samples.SqlServer.BusinessLogicHandler;
namespace Microsoft.Samples.SqlServer.BusinessLogicHandler
{
public class OrderEntryBusinessLogicHandler :
Microsoft.SqlServer.Replication.BusinessLogicSupport.BusinessLogicModule
{
// Variables to hold server names.
private string publisherName;
private string subscriberName;
public OrderEntryBusinessLogicHandler()
{
}
// Implement the Initialize method to get publication
// and subscription information.
public override void Initialize(
string publisher,
string subscriber,
string distributor,
string publisherDB,
string subscriberDB,
string articleName)
{
// Set the Publisher and Subscriber names.
publisherName = publisher;
subscriberName = subscriber;
}
// Declare what types of row changes, conflicts, or errors to handle.
override public ChangeStates HandledChangeStates
{
get
{
// Handle Subscriber inserts, updates and deletes.
return ChangeStates.SubscriberInserts |
ChangeStates.SubscriberUpdates | ChangeStates.SubscriberDeletes;
}
}
public override ActionOnDataChange InsertHandler(SourceIdentifier insertSource,
DataSet insertedDataSet, ref DataSet customDataSet, ref int historyLogLevel,
ref string historyLogMessage)
{
if (insertSource == SourceIdentifier.SourceIsSubscriber)
{
// Build a line item in the audit message to log the Subscriber insert.
StringBuilder AuditMessage = new StringBuilder();
AuditMessage.Append(String.Format("A new order was entered at {0}. " +
"The SalesOrderID for the order is :", subscriberName));
AuditMessage.Append(insertedDataSet.Tables[0].Rows[0]["SalesOrderID"].ToString());
AuditMessage.Append("The order must be shipped by :");
AuditMessage.Append(insertedDataSet.Tables[0].Rows[0]["DueDate"].ToString());
// Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString();
// Set the history log level to the default verbose level.
historyLogLevel = 1;
// Accept the inserted data in the Subscriber's data set and
// apply it to the Publisher.
return ActionOnDataChange.AcceptData;
}
else
{
return base.InsertHandler(insertSource, insertedDataSet, ref customDataSet,
ref historyLogLevel, ref historyLogMessage);
}
}
public override ActionOnDataChange UpdateHandler(SourceIdentifier updateSource,
DataSet updatedDataSet, ref DataSet customDataSet, ref int historyLogLevel,
ref string historyLogMessage)
{
if (updateSource == SourceIdentifier.SourceIsPublisher)
{
// Build a line item in the audit message to log the Subscriber update.
StringBuilder AuditMessage = new StringBuilder();
AuditMessage.Append(String.Format("An existing order was updated at {0}. " +
"The SalesOrderID for the order is ", subscriberName));
AuditMessage.Append(updatedDataSet.Tables[0].Rows[0]["SalesOrderID"].ToString());
AuditMessage.Append("The order must now be shipped by :");
AuditMessage.Append(updatedDataSet.Tables[0].Rows[0]["DueDate"].ToString());
// Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString();
// Set the history log level to the default verbose level.
historyLogLevel = 1;
// Accept the updated data in the Subscriber's data set and apply it to the Publisher.
return ActionOnDataChange.AcceptData;
}
else
{
return base.UpdateHandler(updateSource, updatedDataSet,
ref customDataSet, ref historyLogLevel, ref historyLogMessage);
}
}
public override ActionOnDataDelete DeleteHandler(SourceIdentifier deleteSource,
DataSet deletedDataSet, ref int historyLogLevel, ref string historyLogMessage)
{
if (deleteSource == SourceIdentifier.SourceIsSubscriber)
{
// Build a line item in the audit message to log the Subscriber deletes.
// Note that the rowguid is the only information that is
// available in the dataset.
StringBuilder AuditMessage = new StringBuilder();
AuditMessage.Append(String.Format("An existing order was deleted at {0}. " +
"The rowguid for the order is ", subscriberName));
AuditMessage.Append(deletedDataSet.Tables[0].Rows[0]["rowguid"].ToString());
// Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString();
// Set the history log level to the default verbose level.
historyLogLevel = 1;
// Accept the delete and apply it to the Publisher.
return ActionOnDataDelete.AcceptDelete;
}
else
{
return base.DeleteHandler(deleteSource, deletedDataSet,
ref historyLogLevel, ref historyLogMessage);
}
}
}
}
Imports System
Imports System.Text
Imports System.Data
Imports System.Data.Common
Imports Microsoft.SqlServer.Replication.BusinessLogicSupport
Namespace Microsoft.Samples.SqlServer.BusinessLogicHandler
Public Class OrderEntryBusinessLogicHandler
Inherits BusinessLogicModule
' Variables to hold server names.
Private publisherName As String
Private subscriberName As String
' Implement the Initialize method to get publication
' and subscription information.
Public Overrides Sub Initialize( _
ByVal publisher As String, _
ByVal subscriber As String, _
ByVal distributor As String, _
ByVal publisherDB As String, _
ByVal subscriberDB As String, _
ByVal articleName As String _
)
' Set the Publisher and Subscriber names.
publisherName = publisher
subscriberName = subscriber
End Sub
' Declare what types of row changes, conflicts, or errors to handle.
Public Overrides ReadOnly Property HandledChangeStates() As ChangeStates
Get
' Handle Subscriber inserts, updates and deletes.
Return (ChangeStates.SubscriberInserts Or _
ChangeStates.SubscriberUpdates Or ChangeStates.SubscriberDeletes)
End Get
End Property
Public Overrides Function InsertHandler(ByVal insertSource As SourceIdentifier, _
ByVal insertedDataSet As DataSet, ByRef customDataSet As DataSet, _
ByRef historyLogLevel As Integer, ByRef historyLogMessage As String) _
As ActionOnDataChange
If insertSource = SourceIdentifier.SourceIsSubscriber Then
' Build a line item in the audit message to log the Subscriber insert.
Dim AuditMessage As StringBuilder = New StringBuilder()
AuditMessage.Append(String.Format("A new order was entered at {0}. " + _
"The SalesOrderID for the order is :", subscriberName))
AuditMessage.Append(insertedDataSet.Tables(0).Rows(0)("SalesOrderID").ToString())
AuditMessage.Append("The order must be shipped by :")
AuditMessage.Append(insertedDataSet.Tables(0).Rows(0)("DueDate").ToString())
' Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString()
' Set the history log level to the default verbose level.
historyLogLevel = 1
' Accept the inserted data in the Subscriber's data set and
' apply it to the Publisher.
Return ActionOnDataChange.AcceptData
Else
Return MyBase.InsertHandler(insertSource, insertedDataSet, customDataSet, _
historyLogLevel, historyLogMessage)
End If
End Function
Public Overrides Function UpdateHandler(ByVal updateSource As SourceIdentifier, _
ByVal updatedDataSet As DataSet, ByRef customDataSet As DataSet, _
ByRef historyLogLevel As Integer, ByRef historyLogMessage As String) _
As ActionOnDataChange
If updateSource = SourceIdentifier.SourceIsPublisher Then
' Build a line item in the audit message to log the Subscriber update.
Dim AuditMessage As StringBuilder = New StringBuilder()
AuditMessage.Append(String.Format("An existing order was updated at {0}. " + _
"The SalesOrderID for the order is ", subscriberName))
AuditMessage.Append(updatedDataSet.Tables(0).Rows(0)("SalesOrderID").ToString())
AuditMessage.Append("The order must now be shipped by :")
AuditMessage.Append(updatedDataSet.Tables(0).Rows(0)("DueDate").ToString())
' Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString()
' Set the history log level to the default verbose level.
historyLogLevel = 1
' Accept the updated data in the Subscriber's data set and apply it to the Publisher.
Return ActionOnDataChange.AcceptData
Else
Return MyBase.UpdateHandler(updateSource, updatedDataSet, _
customDataSet, historyLogLevel, historyLogMessage)
End If
End Function
Public Overrides Function DeleteHandler(ByVal deleteSource As SourceIdentifier, _
ByVal deletedDataSet As DataSet, ByRef historyLogLevel As Integer, _
ByRef historyLogMessage As String) As ActionOnDataDelete
If deleteSource = SourceIdentifier.SourceIsSubscriber Then
' Build a line item in the audit message to log the Subscriber deletes.
' Note that the rowguid is the only information that is
' available in the dataset.
Dim AuditMessage As StringBuilder = New StringBuilder()
AuditMessage.Append(String.Format("An existing order was deleted at {0}. " + _
"The rowguid for the order is ", subscriberName))
AuditMessage.Append(deletedDataSet.Tables(0).Rows(0)("rowguid").ToString())
' Set the reference parameter to write the line to the log file.
historyLogMessage = AuditMessage.ToString()
' Set the history log level to the default verbose level.
historyLogLevel = 1
' Accept the delete and apply it to the Publisher.
Return ActionOnDataDelete.AcceptDelete
Else
Return MyBase.DeleteHandler(deleteSource, deletedDataSet, _
historyLogLevel, historyLogMessage)
End If
End Function
End Class
End Namespace
Bu örnek Dağıtımcıya bir iş mantığı işleyicisi kaydeder.
// Specify the Distributor name and business logic properties.
string distributorName = publisherInstance;
string assemblyName = @"C:\Program Files\Microsoft SQL Server\110\COM\CustomLogic.dll";
string className = "Microsoft.Samples.SqlServer.BusinessLogicHandler.OrderEntryBusinessLogicHandler";
string friendlyName = "OrderEntryLogic";
ReplicationServer distributor;
BusinessLogicHandler customLogic;
// Create a connection to the Distributor.
ServerConnection distributorConn = new ServerConnection(distributorName);
try
{
// Connect to the Distributor.
distributorConn.Connect();
// Set the Distributor properties.
distributor = new ReplicationServer(distributorConn);
// Set the business logic handler properties.
customLogic = new BusinessLogicHandler();
customLogic.DotNetAssemblyName = assemblyName;
customLogic.DotNetClassName = className;
customLogic.FriendlyName = friendlyName;
customLogic.IsDotNetAssembly = true;
Boolean isRegistered = false;
// Check if the business logic handler is already registered at the Distributor.
foreach (BusinessLogicHandler registeredLogic
in distributor.EnumBusinessLogicHandlers())
{
if (registeredLogic == customLogic)
{
isRegistered = true;
}
}
// Register the custom logic.
if (!isRegistered)
{
distributor.RegisterBusinessLogicHandler(customLogic);
}
}
catch (Exception ex)
{
// Do error handling here.
throw new ApplicationException(string.Format(
"The {0} assembly could not be registered.",
assemblyName), ex);
}
finally
{
distributorConn.Disconnect();
}
' Specify the Distributor name and business logic properties.
Dim distributorName As String = publisherInstance
Dim assemblyName As String = "C:\Program Files\Microsoft SQL Server\110\COM\CustomLogic.dll"
Dim className As String = "Microsoft.Samples.SqlServer.BusinessLogicHandler.OrderEntryBusinessLogicHandler"
Dim friendlyName As String = "OrderEntryLogic"
Dim distributor As ReplicationServer
Dim customLogic As BusinessLogicHandler
' Create a connection to the Distributor.
Dim distributorConn As ServerConnection = New ServerConnection(distributorName)
Try
' Connect to the Distributor.
distributorConn.Connect()
' Set the Distributor properties.
distributor = New ReplicationServer(distributorConn)
' Set the business logic handler properties.
customLogic = New BusinessLogicHandler()
customLogic.DotNetAssemblyName = assemblyName
customLogic.DotNetClassName = className
customLogic.FriendlyName = friendlyName
customLogic.IsDotNetAssembly = True
Dim isRegistered As Boolean = False
' Check if the business logic handler is already registered at the Distributor.
For Each registeredLogic As BusinessLogicHandler _
In distributor.EnumBusinessLogicHandlers
If registeredLogic Is customLogic Then
isRegistered = True
End If
Next
' Register the custom logic.
If Not isRegistered Then
distributor.RegisterBusinessLogicHandler(customLogic)
End If
Catch ex As Exception
' Do error handling here.
Throw New ApplicationException(String.Format( _
"The {0} assembly could not be registered.", _
assemblyName), ex)
Finally
distributorConn.Disconnect()
End Try
Bu örnek, var olan bir makaleyi iş mantığı işleyicisini kullanacak şekilde değiştirir.
// Define the Publisher, publication, and article names.
string publisherName = publisherInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string publicationDbName = "AdventureWorks2022";
string articleName = "SalesOrderHeader";
// Set the friendly name of the business logic handler.
string customLogic = "OrderEntryLogic";
MergeArticle article = new MergeArticle();
// Create a connection to the Publisher.
ServerConnection conn = new ServerConnection(publisherName);
try
{
// Connect to the Publisher.
conn.Connect();
// Set the required properties for the article.
article.ConnectionContext = conn;
article.Name = articleName;
article.DatabaseName = publicationDbName;
article.PublicationName = publicationName;
// Load the article properties.
if (article.LoadProperties())
{
article.ArticleResolver = customLogic;
}
else
{
// Throw an exception of the article does not exist.
throw new ApplicationException(String.Format(
"{0} is not published in {1}", articleName, publicationName));
}
}
catch (Exception ex)
{
// Do error handling here and rollback the transaction.
throw new ApplicationException(String.Format(
"The business logic handler {0} could not be associated with " +
" the {1} article.",customLogic,articleName), ex);
}
finally
{
conn.Disconnect();
}
' Define the Publisher, publication, and article names.
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2022"
Dim articleName As String = "SalesOrderHeader"
' Set the friendly name of the business logic handler.
Dim customLogic As String = "OrderEntryLogic"
Dim article As MergeArticle = New MergeArticle()
' Create a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(publisherName)
Try
' Connect to the Publisher.
conn.Connect()
' Set the required properties for the article.
article.ConnectionContext = conn
article.Name = articleName
article.DatabaseName = publicationDbName
article.PublicationName = publicationName
' Load the article properties.
If article.LoadProperties() Then
article.ArticleResolver = customLogic
Else
' Throw an exception of the article does not exist.
Throw New ApplicationException(String.Format( _
"{0} is not published in {1}", articleName, publicationName))
End If
Catch ex As Exception
' Do error handling here and rollback the transaction.
Throw New ApplicationException(String.Format( _
"The business logic handler {0} could not be associated with " + _
" the {1} article.", customLogic, articleName), ex)
Finally
conn.Disconnect()
End Try
İlgili içerik
- Birleştirme Makalesi için Özel Çakışma Çözümleyicisi Uygulama
- İş Mantığı İşleyicisinde Hata Ayıklama (Çoğaltma Programlama)
- Çoğaltma Güvenliği en iyi yöntemleri
- Çoğaltma Yönetimi Nesneleri Kavramları