Replication Script Events

The following events can be handled as part of a replication script.

Reader Events

Writer Events

In the order they are called:

1. Refresh_onPrepareRefresh (Refresh only)
or LogReader_onPrepareMirroring (Mirroring only)
2. Record_onBeforeMapping
3. Record_onAfterMapping
4. Replication_onConflict (Synchronization only)
5. Replication_onLateConflict (Synchronization only)

 

In the order they are called:

1.   1.  Refresh_onBeforeRefresh (Refresh only)
2.  Refresh_onBeforeTruncate (Refresh only)
3.  Refresh_onAfterTruncate (Refresh only)
4.  LogReader_onBeforeMirroring (Mirroring only)
5.  Record_onBeforeExecute
6.  Record_onExecuteError (Defined in the global script)
7.  Record_onAfterExecute (Not called if record execution failed)
8.  LogReader_onReceiverChanged (Mirroring only)
9.  Refresh_onAfterRefresh (Refresh only)
10. LogReader_onAfterMirroring (Mirroring only)
11. Replication_onError (Defined in the global script)
 

For more about reader and writer events, check Managing Reader and Writer Events in a Script.

LogReader_onPrepareMirroring

This event is fired before a mirroring operation is built and allows you to perform such operations as cancel the mirroring, record the mirroring start time and so on.

VB.NET syntax

Public Overrides Sub LogReader_onPrepareMirroring(ByRef CancelMirroring As Boolean)

C# syntax

public override void LogReader_onPrepareMirroring(ref bool CancelMirroring)

Parameters

- CancelMirroring: A flag that allows you to cancel the mirroring operation for which the event is fired. The default value is False. Set the flag to True to cancel mirroring.

Example [VB.NET syntax]

Public Overrides Sub LogReader_onPrepareMirroring(ByRef CancelMirroring As Boolean)
    Dim bNeedCancel As Boolean           
    ' TODO:   
    ' check some condition by which the mirroring would need to be canceled
    ' and applying the result to the bNeedCancel variable
    If bNeedCancel Then
       CancelMirroring = True
End If End Sub

Example [C# syntax]

public override void LogReader_onPrepareMirroring(ref  bool CancelMirroring)
{
  bool bNeedCancel = false;
  // TODO:   
  // check some condition by which the mirroring would need to be canceled
  // and applying the result to the bNeedCancel variable
  if (bNeedCancel) {
     CancelMirroring = true;
     }
}

LogReader_onBeforeTransactionsRead

Now LogReader_onBeforeMirroring. On installation of v 6.1, all scripts are updated to use the new event name LogReader_onBeforeMirroring

LogReader_onBeforeMirroring

This event will be activated only if you have defined a mirroring or synchronization replication which accesses the database transaction log. The event is fired immediately before attempting to read the transaction log.

VB.NET syntax

Public Overrides Sub LogReader_onBeforeMirroring (ByVal bSource As Boolean)

C# syntax

public override void LogReader_onBeforeMirroring(bool bSource)

Parameters

- bSource : When set to True, the event is related to the source connection. When set to False the event is related to the target

Example [VB.NET syntax]

Public Overrides Sub LogReader_onBeforeMirroring(bSource As Boolean)
     AddLog("BeforeMirroring", 0)
End Sub

Example [C# syntax]

public override void LogReader_onBeforeMirroring(bool bSource)
{
   GlobalScript.AddLog("BeforeMirroring", 0);
}

LogReader_onAfterMirroring

This event will be activated only if you have defined a mirroring or synchronization replication which accesses the database transaction log. The event is fired immediately after reading the transaction log.

VB.NET syntax

Public Overrides Sub LogReader_onAfterMirroring (ByVal bSource As Boolean)

C# syntax

public override void LogReader_onAfterMirroring(bool bSource)

Parameters

- bSource : When set to True, the event is related to the source connection. When set to False the event is related to the target

Example [VB.NET syntax]

Public Overrides Sub LogReader_onAfterMirroring(bSource  As Boolean)
    AddLog("AfterMirroring",  0)
End Sub

Example [C# syntax]

public override void LogReader_onAfterMirroring(bool bSource)
{
    GlobalScript.AddLog("AfterMirroring", 0);
}

LogReader_onReceiverChanged

This event will be activated only if you have defined a mirroring or synchronization replication from Db2/400 which accesses the Db2 journal. Event fired when the iSeries receiver changes. This event could be used to delete an old receiver. However it should be used carefully especially when you have more than one replication sharing the same journal: you don't want to delete a receiver when one replication has changed it if there are other replications still using it. The best approach is to configure the iSeries to delete old receivers, for example, configuring it to keep only the last 2 receivers. Check the Help Center article on Journals and Receivers for more about receivers.

VB.NET syntax

Public Overrides Sub LogReader_onReceiverChanged (sOldRecvLib As String, 
                     sOldRecvName As String, sNewRecvLib As String, sNewRecvName As String)

C# syntax

public override void LogReader_onReceiverChanged(string sOldRecvLib, 
                           string sOldRecvName, string sNewRecvLib, string sNewRecvName)

Parameters

- sOldRecvLib: The old receiver library name

- sOldRecvName: The old receiver name

- sNewRecvLib: The new receiver library name

- sNewRecvName: The new receiver name

Example [VB.NET syntax]

Public Overrides Sub LogReader_onReceiverChanged(sOldRecvLib As String, sOldRecvName As String, 
                           sNewRecvLib As String, sNewRecvName As String)
    AddLog("Receiver Changed: OLD = " + sOldRecvLib+"/"+sOldRecvName+"  
                  NEW = "+sNewRecvLib+"/"+sNewRecvName , 0)
End Sub

Example [C# syntax]

public override void LogReader_onReceiverChanged(string sOldRecvLib, string sOldRecvName, 
                                      string sNewRecvLib, string sNewRecvName)
{
   GlobalScript.AddLog("Receiver Changed: OLD = " + sOldRecvLib + "/" + sOldRecvName + " 
                            NEW = " + sNewRecvLib + "/" + sNewRecvName, 0);
}

 Record_onBeforeMapping

Event fired right before applying the mapping on the source table columns.

VB.NET syntax

Public Overrides Sub Record_onBeforeMapping (recSource As IRecord, ByRef  AbortRecord As Boolean, 
                                                ByRef DisableReplication As Boolean)

C# syntax

public override void Record_onBeforeMapping(IRecord recSource, ref bool AbortRecord, 
                                             ref bool DisableReplication)

Parameters

- recSource: An IRecord object that provides access to source record data, including the intended operation type (UPDATE, INSERT or DELETE)

- AbortRecord: By default this is set to False. If you set it to True, the record will be skipped during replication.

- DisableReplication: By default this is set to False. If you set it to True, the replication will be disabled.

Example [VB.NET syntax]

' For each new inserted record, skip the replication if  COMPANYNAME = 'TEST'
Public Overrides Sub Record_onBeforeMapping(recSource As IRecord, ByRef AbortRecord As Boolean, 
                                                 ByRef DisableReplication As Boolean)
    Dim obj As Object
    If recSource.OperationType = enmOperationType.Insert Then   
         obj = recSource.GetValueAfter("COMPANYNAME") 
         If obj Is Nothing OR IsDBNull(obj) Then        
            Return   
         End If   
         If obj.ToString() = "TEST" Then        
            AbortRecord = True   
         End If
    End If
End Sub

Example [C# syntax]

// For each new inserted record,  skip the replication if COMPANYNAME = 'TEST'
public override void Record_onBeforeMapping(IRecord recSource, ref bool AbortRecord, 
                                              ref bool DisableReplication)
{
   object obj = null;
   if (recSource.OperationType == enmOperationType.Insert) {
       obj = recSource.GetValueAfter("COMPANYNAME");
       if (obj == null | Information.IsDBNull(obj)) {
          return;
       }
       if (obj.ToString() == "TEST") {
          AbortRecord = true;
       }
   }
}

Record_onAfterMapping

Event fired right after applying the mapping on the source table columns.

VB.NET syntax

Public Overrides Sub Record_onAfterMapping (recSource As IRecord, recTarget As IRecord, 
                  ByRef AbortRecord As Boolean, ByRef DisableReplication As Boolean)

C# syntax

public override void Record_onAfterMapping(IRecord recSource, IRecord recTarget, ref bool AbortRecord, 
                                            ref bool DisableReplication)

Parameters

- recSource: An IRecord object that provides access to source record data, including the intended operation type (UPDATE, INSERT or DELETE)

- recTarget: An IRecord object that provides access to target record data, including the intended operation type (UPDATE, INSERT or DELETE)

- AbortRecord: By default this is set to False. If you set it to True, the record will be skipped during replication.

- DisableReplication: By default this is set to False. If you set it to True, the replication will be disabled.

Example [VB.NET syntax]

' For each new inserted record, replicate the field in  column 0 uppercase
Public Overrides Sub Record_onAfterMapping(recSource As IRecord, recTarget As IRecord, 
              ByRef AbortRecord As Boolean, ByRef DisableReplication As Boolean)
     If recSource.OperationType = enmOperationType.Insert Then   
        if Not recTarget.GetValueAfter(0) Is Nothing Then     
           recTarget.SetValueAfter(0, recTarget.GetValueAfter(0).ToUpper)   
        End if
    End If
End Sub

Example [C# syntax]

// For each new inserted record, replicate the field in column 0 uppercase
public override void Record_onAfterMapping(IRecord recSource, IRecord recTarget, ref bool AbortRecord, 
                                            ref bool DisableReplication)
{
   if (recSource.OperationType == enmOperationType.Insert) {
       if ((recTarget.GetValueAfter(0) != null)) {
           recTarget.SetValueAfter(0, recTarget.GetValueAfter(0).ToUpper);
       }
   }
}

Record_onBeforeExecute

Event triggered right before changes to the record are executed at the target site. Note that this event and Record_onAfterExecute no longer have access to the source record values. Therefore, if you need to perform operations using the source value, use the Record_OnAfterMapping event instead.

Events associated with the execution phase of replication are run using a different thread from events associated with the mapping phase of replication. If you want the event to be triggered at the closest possible time to the actual replication of the record, you should use Record_onBeforeExecute or Record_onAfterExecute.

VB.NET syntax

Public Overrides Sub Record_onBeforeExecute (recTarget As IRecord, AbortRecord As Boolean, 
                                                ByRef DisableReplication As Boolean)

C# syntax

public override void Record_onBeforeExecute(IRecord recTarget, bool AbortRecord, ref bool DisableReplication)

Parameters

- recTarget: An IRecord object that provides access to target record data, including the intended operation type (UPDATE, INSERT or DELETE)

- AbortRecord: By default this is set to False. If you set it to True, the record will be skipped during replication.

- DisableReplication: By default this is set to False. If you set it to True, the replication will be disabled.

Example [VB.NET syntax]

' For each inserted and updated record, skip the replication if the new Value assigned to column 0 is 'TEST'
Public Overrides Sub Record_onBeforeExecute(recTarget As IRecord, ByRef AbortRecord As Boolean, 
                                              ByRef DisableReplication As Boolean)
   Dim obj As Object
   If recTarget.OperationType = enmOperationType.Insert 
      Or recTarget.OperationType = enmOperationType.Update Then
          obj = recTarget.GetValueAfter(0)
          if obj Is Nothing OR IsDBNull(obj) Then
             return
          End if
          if obj.ToString() = "TEST" Then
             AbortRecord = True
          End if
   End If
End Sub

Example [C# syntax]

// For each inserted and updated record, skip the replication if the new value assigned to column 0 is 'TEST'
public override void Record_onBeforeExecute(IRecord recTarget, ref bool AbortRecord, ref bool DisableReplication)
{
   object obj = null;
   if (recTarget.OperationType == enmOperationType.Insert | recTarget.OperationType == enmOperationType.Update) {
       obj = recTarget.GetValueAfter(0);
       if (obj == System.DBNull.Value) {
          return;
       }
       if (obj.ToString() == "TEST") {
          AbortRecord = true;
       }
   }
}

Record_onAfterExecute

Event triggered right after changes to the record are executed at the target site. Note that this event and Record_onBeforeExecute no longer have access to the source record values. Therefore, if you need to perform operations using the source value, use the Record_OnAfterMapping event instead.

Events associated with the execution phase of replication are run using a different thread from events associated with the mapping phase of replication. If you want the event to be triggered at the closest possible time to the actual replication of the record, you should use Record_onBeforeExecute or Record_onAfterExecute. Note that this event is generated only if the record operation succeeds and not at all if the record operation fails.

VB.NET syntax

Public Overrides Sub Record_onAfterExecute (recTarget As IRecord, Failed  As Boolean, 
                                             ByRef DisableReplication As Boolean)

C# syntax

public override void Record_onAfterExecute(IRecord recTarget, bool Failed, ref bool DisableReplication)

Parameters

- recTarget: An IRecord object that provides access to target record data, including the intended operation type (UPDATE, INSERT or DELETE)

- Failed: A read-only input parameter. When True, the record operation failed.

- DisableReplication: By default this is set to False. If you set it to True, the replication will be disabled.

Example [VB.NET syntax]

Public Overrides Sub Record_onAfterExecute(recTarget As IRecord, Failed As Boolean, 
                                            ByRef DisableReplication As Boolean)
   If Not Failed Then 
      AddLog("Replication of single record succeeded", 0)   Else         
      AddLog("Replication of single record failed", 2)   
   End If
End Sub

Example [C# syntax]

public override void Record_onAfterExecute(DBMotoPublic.IRecord recTarget, bool Failed, 
                                            ref bool DisableReplications)
{
    if (!(Failed)){
        GlobalScript.AddLog("Replication of single record succeeded", 0);
    }
    else {
        GlobalScript.AddLog("Replication of single record failed", 2);
    }
 }

Refresh_onBeforeTruncate

Event fired right before the truncation of the target table. If the value of the variable CancelTruncate is set to True, no truncation will occur.

VB.NET syntax

Public Overrides Sub Refresh_onBeforeTruncate (ByRef CancelTruncate As Boolean, ByRef Filter As System.String)

C# syntax

public override void Refresh_onBeforeTruncate(ref bool CancelTruncate, ref System.String Filter)

Parameters

- CancelTruncate: indicates if the truncation has to be canceled.

- Filter: a string containing a SQL WHERE condition to be used as a filter to determine which records to truncate.

Example [VB.NET syntax]

Public Overrides Sub Refresh_onBeforeTruncate(ByRef CancelTruncate As Boolean, ByRef Filter As System.String)
   AddLog("Refresh_onBefore Started", 0) 
   Filter = " ID < 10 "
   AddLog("Refresh_onBeforeTruncate Finished", 0) 
End Sub

Example [C# syntax]

public override void Refresh_onBeforeTruncate(ref bool CancelTruncate, ref System.String Filter) 
{         
   AddLog("Refresh_onBefore Started", 0);         
   Filter = " ID < 10 ";         
   AddLog("Refresh_onBeforeTruncate Finished", 0); 
}

Refresh_onAfterTruncate

Event fired right after the truncation of the target table.

VB.NET syntax

Public Overrides Sub Refresh_onAfterTruncate ()

C# syntax

public override void Refresh_onAfterTruncate()

Example [VB.NET syntax]

Public Overrides Sub Refresh_onAfterTruncate()
    AddLog("Truncate Finished", 0)
End Sub

Example [C# syntax]

public override void Refresh_onAfterTruncate()
{
    GlobalScript.AddLog("Truncate Finished", 0);
}

Refresh_onPrepareRefresh

Event fired before refresh operation is built to allow the inclusion of a filter (WHERE condition). This is an alternative to providing a filter in the replication properties and allows you to change the filter each time a refresh is performed.

VB.NET syntax

Public Overrides Sub Refresh_onPrepareRefresh(ByRef CancelRefresh As System.Boolean, ByRef Filter As System.String)

C# syntax

public override void Refresh_onPrepareRefresh(ref bool CancelRefresh, ref System.String Filter)

Parameters

- Filter: a string containing a SQL WHERE condition to be used as a filter when performing a refresh.

- CancelRefresh: A flag that allows you to cancel the refresh operation for which the event is fired. The default value is False. Set the flag to True to cancel a refresh.

Example [VB.NET syntax]

This example shows how to define an incremental refresh by using the Refresh_onPrepareRefresh event.

NOTE: this sample works only with inserted data. Updated and deleted records are not correctly replicated using the incremental refresh.

1. Define a source table in this way:

ID integer (incremental)

Name varchar(20)

2. Define a replication in refresh mode, scheduled to run recurrently.

3. Define the following replication script:


Namespace DBRS
    Public Class ReplicationScript : Inherits IReplicationScript
        ' create a variable m_LastID to store the last inserted id 
        Public m_LastID As Long
        Public Overrides Sub Refresh_onBeforeTruncate(ByRef CancelTruncate As Boolean)
            ' truncate the target table only the first time      
            If m_LastID > 0 Then
              CancelTruncate = True
            End If
        End Sub
        Public Overrides Sub Record_onAfterExecute(recTarget As IRecord)
            ' save the last inserted id  
            If recTarget.OperationType = enmOperationType.Insert Then
              m_LastID = recTarget.GetValueAfter("ID")
            End If
        End Sub
        Public Overrides Sub Refresh_onPrepareRefresh(ByRef Filter As String)
          ' prepare the filter for the next refresh
          If m_LastID > 0 Then
            Filter = "ID > " + m_LastID.ToString() 
          End If
        End Sub
    End Class
End Namespace

C# Syntax

using System;
using System.Data;
using DBMotoPublic;
using DBMotoScript;
namespace DBRS
{
    public class ReplicationScript : IReplicationScript
    {
        long m_LastID = 0; //create a variable m_LastID to store the last inserted id
        public override void Refresh_onBeforeTruncate(ref bool CancelTruncate)
        {
           // truncate the target table only the first time      
           if (m_LastID > 0)  {
              CancelTruncate = true;
              }
        }
        public override void Record_onAfterExecute(DBMotoPublic.IRecord recTarget, bool Failed)
        {
           // save the last inserted id  
           if (recTarget.OperationType == enmOperationType.Insert) {
               m_LastID = (long) recTarget.GetValueAfter("ID");
           }
       }
       public override void Refresh_onPrepareRefresh(ref bool CancelRefresh, ref string Filter)
       {
          // prepare the filter for the next refresh
          if (m_LastID > 0) {
              Filter = "ID > " + m_LastID.ToString();
          }
      }
  }
}

Refresh_onBeforeRefresh

Event fired right before starting the refresh.

VB.NET syntax

Public Overrides Sub Refresh_onBeforeRefresh ()

C# syntax

public override void Refresh_onBeforeRefresh()

Example [VB.NET syntax]

Public Overrides Sub Refresh_onBeforeRefresh()
    AddLog("Refresh Started", 0)
End Sub

Example [C# syntax]

public override void Refresh_onBeforeRefresh()
{
   GlobalScript.AddLog("Refresh  Started", 0);
}

Refresh_onAfterRefresh

Event fired right after the execution of the refresh.

VB.NET syntax

Public Overrides Sub Refresh_onAfterRefresh ()

C# syntax

public override void Refresh_onAfterRefresh()

Example [VB.NET syntax]

Public Overrides Sub Refresh_onAfterRefresh()
    AddLog("Refresh Finished", 0)
End Sub

Example [C# syntax]

public override void Refresh_onAfterRefresh()
{
   GlobalScript.AddLog("Refresh Finished", 0);
}

Replication_onConflict

This event is generated when a collision happens on a record during synchronization. A collision occurs when both the source and target database update/delete/insert the same record at the same time. The two records that generate the collision are passed as parameters to the event. The event function must resolve the collision by returning a new record that will be inserted. The record returned could be the source record, in this case the source connection wins the conflict, the target record (target wins), or a new record obtained merging the values of the two records.

VB.NET syntax

Public Overrides Function Replication_onConflict (ByRef recSource As IRecord, 
                              ByRef recTarget As IRecord) As IRecord

C# syntax

public override IRecord Replication_onConflict(IRecord recSource, IRecord recTarget)

Parameters

- recSource: A record in the table defined by the source connection

- recTarget: A record in the table defined by the target connection

Returns: The record that will be inserted after executing the event function.

Example [VB.NET syntax]

Public Overrides Function Replication_onConflict(recSource As IRecord, recTarget As IRecord) As IRecord
   AddLog("Conflict", 1)
End Function

Example [C# syntax]

public override IRecord Replication_onConflict(IRecord recSource, IRecord recTarget)
{
   GlobalScript.AddLog("Conflict", 1);
}

Replication_onLateConflict

This event is generated when a very specific type of collision occurs on a record during synchronization. It may occasionally happen that between the time the log/journal is read in preparation for replication and the changes are recorded in the tables involved, a transaction occurs in one of the tables. If the transaction conflicts with the newly entered changes (as a result of synchronization), this event is triggered so that you can determine how you want to handle the conflict. The event is triggered during the synchronization iteration following the one where the conflict actually occurred.

VB.NET syntax

Public Overrides Function Replication_onLateConflict (ByRef rec1 As IRecord, ByRef rec2 As IRecord, 
                                                           ByVal bSource As Boolean) As IRecord

C# syntax

public override IRecord Replication_onLateConflict(ref IRecord rec1, ref IRecord rec2, bool bSource)

Parameters

- rec1: The transaction that was missed because it occurred at a critical time during synchronization

- rec2: The Syniti DR transaction that occurred as a result of the synchronization replication

Note that rec1 and rec2 signify a conflict on the same table rather than a conflict between the tables involved in the synchronization.

- bSource: Boolean that when set to True means rec1 and rec2 were found to be in conflict in the table designated as a source table for the replication. When set to False, rec1 and rec2 occurred on the table designated as the target table for the replication.

Related Topics
Managing Reader and Writer Events in a Script
IRecord Interface

Replication Script Properties

Handling Events for INSERT, UPDATE and DELETE Operations

Global Script Functions

Writing a Global Script

Writing a Replication Script

Writing Scripts with Visual Basic .NET

Replication Script Editor