Birleştirme makale Business Logic işleyicisi gerçekleştir
Bu konuda bir birleştirme makale için iş mantığı işleyicisi uygulamak açıklar SQL Server 2012kullanarak çoğaltma programlama veya Çoğaltma Yönetimi Nesneleri'ni (rmo).
Microsoft.SqlServer.Replication.BusinessLogicSupportAd alanını uygulayan birleştirme çoğaltma eşitleme işlemi sırasında oluşan olayları ele almak için karmaşık iş mantığı yazmanızı sağlayan bir arabirim. Iş mantığı işleyicisi yöntemleri, eşitleme sırasında çoğaltılmış değiştirilen her satır için çoğaltma işlemi tarafından çağrılabilir.
Iş mantığı işleyicisi uygulamak için genel işlemidir:
Iş mantığı işleyicisi derleme oluşturun.
Dağıtımcı öğesindeki derleme kaydettirin.
Derleme birleştirme Aracısı çalıştığı sunucuda dağıtmak. Çekme abonelik için Aracısı abone üzerinde çalışır ve için bir itme abonelik Aracısı dağıtımcı üzerinde çalışır. Web eşitleme kullanırken, aracı Web sunucusunda çalışır.
Iş mantığı işleyicisi kullanan bir makale oluşturun veya iş mantığı işleyicisi kullanmak için varolan bir makale değiştirin.
Belirttiğiniz iş mantığı işleyicisi eşitlenen her satır için yürütülür. Karmaşık mantığı ve diğer uygulamaları ya da ağ hizmetleri çağrı performansı etkileyebilir. İş mantığı işleyicileri hakkında daha fazla bilgi için bkz: Business Logic birleştirme eşitleme sırasında çalıştırma.
Bu Konuda
Bir birleştirme makale için iş mantığı işleyicisi uygulamak için kullanma:
Çoğaltma programlama
Çoğaltma Yönetimi Nesneleri'ni (rmo)
Çoğaltma programlama kullanarak
Oluşturma ve iş mantığı işleyicisi dağıtmak için
De MicrosoftVisual Studio için yeni bir proje yaratın.İş mantığı işleyicisi uygulayan kodunu içeren net Meclis.
Aşağıdaki ad alanları projeye başvurular ekleyin.
Derleme başvurusu
Konum
C:\Program Files\Microsoft SQL Server\110\com (varsayılan yükleme)
gac (component of.net Framework)
gac (component of.net Framework)
Geçersiz kılar sınıf ekleme BusinessLogicModulesınıf
Tarla HandledChangeStatesişlenen değişiklik türlerini belirtmek için özellik.
Bir veya daha aşağıdaki yöntemleri geçersiz kılmak BusinessLogicModulesınıf:
CommitHandler-bir veri değişikliği eşitleme sırasında kaydedilmiş olduğunda çağrılan.
DeleteErrorHandler-delete deyimi ne zaman bir hata oluştuğunda çağrılan karşıya veya karşıdan olduğunu.
DeleteHandler-delete deyimleri olan zaman çağrılan karşıya veya karşıdan.
InsertErrorHandler-karşıya veya karşıdan bir INSERT deyimi ne zaman bir hata oluştuğunda çağrılan olur.
InsertHandler-INSERT deyimleri olan zaman çağrılan karşıya veya karşıdan.
UpdateConflictsHandler-Çakışan update deyimleri yayıncı ve abone oluştuğunda çağrılan.
UpdateDeleteConflictHandler-update deyimleri delete deyimleri yayıncı ve abone çakışıyor zaman çağrılan.
UpdateErrorHandler-karşıya veya karşıdan bir update deyimi ne zaman bir hata oluştuğunda çağrılan olur.
UpdateHandler-update deyimleri olan zaman çağrılan karşıya veya karşıdan.
Iş mantığı işleyici derleme oluşturmak için projeyi derleyin.
Varsayılan yükleme için Birleştirme Aracısı yürütülebilir dosyası (replmerg.exe) içeren dizin derleme dağıtmak C:\Program Files\Microsoft SQL Server\110\com, ya da bunu yükleyin.net genel derleme önbelleğine (gac). Derleme birleştirme aracı dışındaki uygulamaların erişmesi, yalnızca derleme GAC'ye yüklemelisiniz. Derleme genel derleme önbelleği aracını kullanarak gac yüklenebilir (Gacutil.exe) sağlanan.net Framework sdk.
[!NOT]
Iş mantığı işleyicisi üzerinde eşitleme kullanırken replisapi.dll barındıran IIS sunucusunu içeren Birleştirme Aracısı çalıştırır Web her sunucuda dağıtılmalıdır.
Iş mantığı işleyicisi kaydetmek için
Yayımcı tarafında idam sp_enumcustomresolvers (Transact-sql)derleme zaten iş mantığı işleyicisi olarak kaydedilmemiş doğrulamak için.
Dağıtıcı idam sp_registercustomresolver (Transact-sql), business logic işleyicisi için bir kolay ad belirtme @ article_resolver, değeri trueiçin @ is_dotnet_assembly, derleme için adı @ dotnet_assembly_name, geçersiz kılar sınıf tam nitelikli adını BusinessLogicModuleiçin @ dotnet_class_name.
[!NOT]
Derleme birleştirme Aracısı yürütülebilir dosyası ile aynı dizinde dağıtılan değil, uygulama ile aynı dizinde, zaman uyumlu olarak Birleştirme Aracısı başlar ya da genel derleme önbelleğine (gac) için derleme adı ile tam yolunu belirtmeniz gerekiyor @ dotnet_assembly_name. Web eşitleme kullanırken, derleme Web sunucusu konumunu belirtmeniz gerekir.
Yeni bir tablo makale ile iş mantığı işleyicisi kullanmak için
- Yürütme yürütmesp_addmergearticle (Transact-sql)bir makale tanımlamak için iş mantığı işleyicisi kolay adı belirtme @ article_resolver. Daha fazla bilgi için, bkz. Bir makale tanımlamak.
Varolan bir tablo makale ile iş mantığı işleyicisi kullanmak için
- Yürütme sp_changemergearticle (Transact-sql), belirtme @ yayın, @ makale, değeri article_resolver için @ özellikve iş mantığı işleyicisi kolay adı @ değeri.
Örnekler (çoğaltma programlama)
Bu örnek, bir denetim günlüğü oluşturan iş mantığı işleyicisi gösterir.
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, iş mantığı işleyici derleme at dağıtımcı kaydeder ve bu özel iş mantığı kullanmak için varolan bir birleştirme makale 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\110\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
[Top]
Çoğaltma Yönetimi Nesneleri'ni (rmo) kullanarak
Iş mantığı işleyicisi oluşturmak için
De MicrosoftVisual Studio için yeni bir proje yaratın.İş mantığı işleyicisi uygulayan kodunu içeren net Meclis.
Aşağıdaki ad alanları projeye başvurular ekleyin.
Derleme başvurusu
Konum
C:\Program Files\Microsoft SQL Server\110\com (varsayılan yükleme)
gac (component of.net Framework)
gac (component of.net Framework)
Geçersiz kılar sınıf ekleme BusinessLogicModulesınıf
Tarla HandledChangeStatesişlenen değişiklik türlerini belirtmek için özellik.
Bir veya daha aşağıdaki yöntemleri geçersiz kılmak BusinessLogicModulesınıf:
CommitHandler-bir veri değişikliği eşitleme sırasında kaydedilmiş olduğunda çağrılan.
DeleteErrorHandler-delete deyimi sırada bir hata oluştuğunda, çağrılan karşıya veya karşıdan.
DeleteHandler-delete deyimleri olan zaman çağrılan karşıya veya karşıdan.
InsertErrorHandler-karşıya veya karşıdan bir INSERT deyimi ne zaman bir hata oluştuğunda, çağrılan olur.
InsertHandler-INSERT deyimleri olan zaman çağrılan karşıya veya karşıdan.
UpdateConflictsHandler-Çakışan update deyimleri yayıncı ve abone oluştuğunda çağrılan.
UpdateDeleteConflictHandler-update deyimleri delete deyimleri yayıncı ve abone çakışıyor zaman çağrılan.
UpdateErrorHandler-karşıya veya karşıdan bir update deyimi ne zaman bir hata oluştuğunda, çağrılan olur.
UpdateHandler-update deyimleri olan zaman çağrılan karşıya veya karşıdan.
[!NOT]
Özel iş mantığı tarafından açıkça ele makale çakışmaları, makaleyi Varsayılan çözümleyici tarafından işlenir.
Iş mantığı işleyici derleme oluşturmak için projeyi derleyin.
Iş mantığı işleyicisi kaydetmek için
Dağıtımcı bir bağlantı kullanarak oluşturmak ServerConnectionsınıf
Örneğini ReplicationServersınıf Geçmek ServerConnectiondan 1 adım.
Arama EnumBusinessLogicHandlersve dönen kontrol ArrayListnesnesinin derleme zaten iş mantığı işleyicisi olarak kaydedilmemiş emin olmak için.
Örneğini BusinessLogicHandlersınıf Aşağıdaki özellikleri belirtin:
DotNetAssemblyName-adı.net derleme. Derleme birleştirme Aracısı yürütülebilir, zaman uyumlu olarak birleştirme aracı başlatılan uygulama ile aynı dizinde veya gac aynı dizinde dağıtılan değil, derleme adı ile tam yolunu içermelidir. Iş mantığı işleyicisi ile Web eşitleme kullanırken derleme adı ile tam yolunu içermelidir.
DotNetClassName-geçersiz kılar sınıf tam nitelikli adını BusinessLogicModuleve iş mantığı işleyicisi uygulayan.
FriendlyName-iş mantığı işleyicisi erişirken kullandığınız bir kolay ad.
IsDotNetAssembly-değeri true.
Iş mantığı işleyicisi dağıtmak için
- Nerede ne zaman dağıtımcı kayıtlı iş mantığı işleyicisi Birleştirme Aracısı çalıştırır dosya konumunda belirtilen sunucudaki derleme dağıtmak. Çekme abonelik için Aracısı abone üzerinde çalışır ve için bir itme abonelik Aracısı dağıtımcı üzerinde çalışır. Web eşitleme kullanırken, aracı Web sunucusunda çalışır. İş mantığı işleyicisi kaydolurken tam yolu ile derleme adı dahil değildi, derleme birleştirme Aracısı yürütülebilir, zaman uyumlu olarak birleştirme aracı başlatılan uygulama ile aynı dizinde aynı dizinde dağıtın. Eğer aynı derlemenin kullanan birden çok uygulamayı derleme GAC'de kurabilirsiniz.
Yeni bir tablo makale ile iş mantığı işleyicisi kullanmak için
Kullanarak bir yayımcının bağlantısı oluşturmak ServerConnectionsınıf
Örneğini MergeArticlesınıf Aşağıdaki özellikleri ayarlayın:
Makale için adı Name.
Yayın adı PublicationName.
Yayını veritabanı adı DatabaseName.
Iş mantığı işleyicisi kolay adı (FriendlyName) için ArticleResolver.
Arama Createyöntemi. Daha fazla bilgi için, bkz. Bir makale tanımlamak.
Varolan bir tablo makale ile iş mantığı işleyicisi kullanmak için
Kullanarak bir yayımcının bağlantısı oluşturmak ServerConnectionsınıf
Örneğini MergeArticlesınıf
Set Name, PublicationName, ve DatabaseNameÖzellikler.
Adım 1'bağlantısını ayarlayın ConnectionContextözellik.
Arama LoadPropertiesnesne özelliklerini almak için yöntem. Bu yöntem ise false, adım 3 makale özelliklerini hatalı tanımlanmış ya da makale yok. Daha fazla bilgi için, bkz. Makale özelliklerini görüntüleme ve değiştirme.
İş mantığı işleyicisi kolay adı ayarlamak ArticleResolver. Bu değeri ise FriendlyNameiş mantığı işleyicisi kaydedilirken belirtilen özellik.
Örnekler (rmo)
Bu bilgi hakkında açtığı iş mantığı işleyicisi, güncelleştirmeler, ekler ve Abone tarafında siler örneğidir.
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, iş mantığı işleyicisi at dağıtımcı 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, iş mantığı işleyicisi kullanmak için varolan bir makale değiştirir.
// Define the Publisher, publication, and article names.
string publisherName = publisherInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string publicationDbName = "AdventureWorks2012";
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 = "AdventureWorks2012"
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
[Top]
Ayrıca bkz.
Görevler
Bir iş mantığı işleyicisi (çoğaltma programlama) hata ayıklama
Kavramlar
Özel çakışma Çözücü birleştirme makalesi gerçekleştir