Udostępnij za pośrednictwem


Jak Wdrożenie obsługi logiki biznesowej korespondencji seryjnej artykuł (Programowanie RMO)

Microsoft.SqlServer.Replication.BusinessLogicSupport Nazw implementuje interfejs, który umożliwia pisanie niestandardowe logika biznesowa do obsługi zdarzeń, które występują podczas procesu synchronizacji replikacja scalająca.Metody w obsługa logika biznesowa mogą zostać wywołane przez proces replikacja dla każdego wiersza zmienionych, który jest replikowany podczas synchronizacji.

Ogólny proces wykonywania obsługa logika biznesowa jest:

  1. Tworzenie wirtualny plik dziennika hander logika biznesowa.

  2. Zarejestrować wirtualny plik dziennika u dystrybutora.

  3. Wdrażanie wirtualny plik dziennika na serwerze, na którym uruchomiony jest Agent scalania.Subskrypcji ściąganej agent jest uruchamiany na subskrybenta i subskrypcja wypychana agent działa na dystrybutora.Podczas korzystania z sieci synchronizacja w sieci Web, agent jest uruchamiany na serwerze sieci Web.

  4. Tworzenie artykuł używa obsługa logika biznesowa, lub zmodyfikować istniejące artykuł używać obsługa logika biznesowa.

obsługa logika biznesowa Określić jest wykonywane dla każdego wiersza, który jest synchronizowany.Złożone logikę i wywołań do innych aplikacji lub usług sieciowych może obniżyć wydajność.Aby uzyskać więcej informacji dotyczących obsługi logika biznesowa, zobacz Wykonywanie reguł biznesowych podczas synchronizacji korespondencji seryjnej.

Aby utworzyćobsługa logika biznesowa

  1. W Microsoft programu Visual Studio, tworzenie nowego projektu.wirtualny plik dziennika netto, który zawiera kod, który implementuje obsługa logika biznesowa.

  2. Dodaj odwołania do projektu dla następujących obszarów nazw.

    Odwołanie do zestawu

    Lokalizacja

    Microsoft.SqlServer.Replication.BusinessLogicSupport

    C:\Program Files\Microsoft SQL Server\100\COM (instalacji domyślnej)

    System.Data

    GAC (składnik.NET Framework)

    System.Data.Common

    GAC (składnik.NET Framework)

  3. Add class, który zastępuje BusinessLogicModule klasy

  4. Wdrożenie HandledChangeStates właściwość, aby wskazać typy zmian, które są obsługiwane.

  5. Zastąpienie jednego lub więcej z następujących metod BusinessLogicModule klasy:

    • CommitHandler -wywoływana, gdy zmiana danych jest zobowiązana podczas synchronizacji.

    • DeleteErrorHandler -wywoływane w przypadku wystąpienia błędu podczas Instrukcja DELETE przekazywania lub pobierania.

    • DeleteHandler -wywoływana, gdy usuwanie sprawozdania są przekazywane lub pobrać.

    • InsertErrorHandler-wywołany, jeśli wystąpi błąd, gdy instrukcja INSERT jest przekazywane lub pobrać.

    • InsertHandler -wywoływana, gdy instrukcji INSERT są przekazywane lub pobrać.

    • UpdateConflictsHandler-wywoływana, gdy występują konflikty instrukcji UPDATE w Wydawca i abonenta.

    • UpdateDeleteConflictHandler-wywoływana, gdy instrukcji UPDATE konflikt z instrukcji DELETE na Wydawca i abonenta.

    • UpdateErrorHandler-wywołany, jeśli wystąpi błąd, gdy instrukcja UPDATE jest przekazywane lub pobrać.

    • UpdateHandler-wywoływana, gdy aktualizacja sprawozdania są przekazywane lub pobrać.

    Ostrzeżenie

    Konflikty artykuł jawnie nie są obsługiwane przez logika biznesowa niestandardowe są obsługiwane przez program rozpoznawania nazw domyślnych dla artykuł.

  6. Skompiluj projekt, aby utworzyć obsługa logika biznesowa wirtualny plik dziennika.

Aby zarejestrowaćobsługa logika biznesowa

  1. Tworzenie połączenia do dystrybutora za pomocą ServerConnection klasy

  2. Utworzenie wystąpienie ReplicationServer klasyPrzekazywanie ServerConnection z kroku 1.

  3. Wywołanie EnumBusinessLogicHandlers i Sprawdzanie zwracanych ArrayList obiekt, aby zapewnić, że zgromadzenie nie jest już zarejestrowany jako obsługa logika biznesowa.

  4. Utworzenie wystąpienie BusinessLogicHandler klasyOkreślić następujące właściwości:

    • DotNetAssemblyName -nazwę.wirtualny plik dziennika netto.wirtualny plik dziennika nie jest wdrożony w tym samym katalogu co wykonywalne, w tym samym katalogu co aplikacja synchronicznie uruchamiany Agent scalania lub w pamięci podręcznej GAC scalić agenta, musi zawierać pełną ścieżka z nazwy wirtualny plik dziennika.Musi zawierać pełną ścieżka z nazwy wirtualny plik dziennika, przy użyciu obsługa logika biznesowa synchronizacja w sieci Web.

    • DotNetClassName-pełną nazwę klasy, który zastępuje BusinessLogicModule i implementuje obsługa logika biznesowa.

    • FriendlyName -przyjazną nazwę używanego podczas uzyskiwania dostępu obsługa logika biznesowa.

    • IsDotNetAssembly-wartość true.

Aby wdrożyć obsługi logika biznesowa

  • Wdrażanie wirtualny plik dziennika na serwerze, gdzie działa Agent scalania w lokalizacji określonej podczas obsługa logiki biznesowej została zarejestrowana u dystrybutora.Subskrypcji ściąganej agent jest uruchamiany na subskrybenta i subskrypcja wypychana agent działa na dystrybutora.Podczas korzystania z sieci synchronizacja w sieci Web, agent jest uruchamiany na serwerze sieci Web.Jeśli pełna ścieżka nie został dołączony do wirtualny plik dziennika nazwę po obsługa logika biznesowa został zarejestrowany, wdrożyć wirtualny plik dziennika w tym samym katalogu co plik wykonywalny scalić agenta, w tym samym katalogu co aplikacja uruchamia to synchronicznie agenta scalania.Jeśli istnieje wiele aplikacji, które używają tego samego wirtualny plik dziennika, może zainstalować wirtualny plik dziennika w pamięci podręcznej GAC.

Aby użyć obsługa logika biznesowa z nowego artykuł tabela

  1. Tworzenie połączenia do Wydawca za pomocą ServerConnection klasy

  2. Utworzenie wystąpienie MergeArticle klasyUstaw następujące właściwości:

  3. Wywołanie Create metoda.Aby uzyskać więcej informacji, zobacz Jak Definiowanie artykuł (Programowanie RMO).

Aby użyć obsługa logika biznesowa z istniejącego artykuł tabela

  1. Tworzenie połączenia do Wydawca za pomocą ServerConnection klasy

  2. Utworzenie wystąpienie MergeArticle klasy

  3. Ustaw Name, PublicationName, i DatabaseName Właściwości.

  4. Ustawić połączenie z kroku 1 dla ConnectionContext właściwość.

  5. Wywołanie LoadProperties metoda, aby pobrać właściwości obiektu.Jeśli ta metoda zwraca false, artykuł nie istnieje albo niepoprawnie zostały zdefiniowane właściwości artykuł w kroku 3.Aby uzyskać więcej informacji, zobacz Jak Wyświetlanie i modyfikowanie właściwości artykułu (Programowanie RMO).

  6. Ustawić przyjaznej nazwy obsługa logika biznesowa dla ArticleResolver.Jest to wartość FriendlyName podczas rejestrowania właściwość obsługa logika biznesowa.

Przykład

W tym przykładzie jest obsługa logika biznesowa , rejestruje informacje o wstawia aktualizacje i usuwa przez subskrybenta.

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

W tym przykładzie rejestruje obsługa logika biznesowa u dystrybutora.

         // Specify the Distributor name and business logic properties.
            string distributorName = publisherInstance;
            string assemblyName = @"C:\Program Files\Microsoft SQL Server\100\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\100\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

W tym przykładzie zmiany istniejącego artykuł używać obsługa logika biznesowa.

            // Define the Publisher, publication, and article names.
            string publisherName = publisherInstance;
            string publicationName = "AdvWorksSalesOrdersMerge";
            string publicationDbName = "AdventureWorks2008R2";
            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 = "AdventureWorks2008R2"
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