Implementing Triggers

 

Project Page

Download

Manual

Overview
Hello SPF
Attributes
Constraints
Triggers
Criteria
Child Collections

Overview

Triggers are pieces of business logic associated with actions occurring on an entity, e.g. a welcome email being sent when a new user is created. A trigger is any method that implements the signature defined by the SpfTrigger delegate shown below:

public delegate void SpfTrigger(ISpfTxnContext p_TxnContext, object p_AppContext);

The full code for this tutorial can be found here.

Creating Triggers

Continuing with the user example used in the previous tutorials, we can use triggers to populate and maintain the field values representing the created and modified dates: First we need to add a couple of methods with the delegate signature:

    public void PopulateDateCreated(ISpfTxnContext p_TxnContext, 
                                    object p_AppContext) {
      this.DateCreated = DateTime.Now;
    }

    public void PopulateDateLastUpdated(ISpfTxnContext p_TxnContext, 
                                        object p_AppContext) {
      this.DateModified = DateTime.Now;
    }

The parameters are the same as those for constraints, the first being the current transaction context and the second being an application specific context object.

Remember that all interactions through the transaction context occur under the same transaction as the current action. This means that if the business logic in a trigger causes an exception, say it tries to persist an entity with invalid values, then current action will also be rolled back.

Adding Triggers

Once the triggers have been created, SPF must be told to when to invoke them. Triggers fall into two categories, pre-triggers and post-triggers. Pre-triggers are called before and entity is inserted or updated, while post-triggers are called after and entity is inserted, updated or deleted.

In our example we want our triggers to be called before the entity is persisted and we want the date created trigger to only being called when the entity is inserted. The following code is placed in the constructor:

      AddPreTrigger(new SpfTrigger(PopulateDateCreated), 
                    SpfPersistenceAction.Insert);
      AddPreTrigger(new SpfTrigger(PopulateDateLastUpdated));

Now whenever our entity is persisted the triggers will fire and ensure the date fields are populated.

Summary

In this tutorial we saw how business logic can be encapsulated in the entity class in the form of triggers. We saw how we can specify both the action and the time that a trigger is called.