MSBA-341 · Lesson 4 of 12 · 19 min

Event handlers

▶ Video coming soon A video version of this lesson is on the way.

Chain of Command was not the first extension technique Microsoft introduced. Before it, the extension model relied on events: points in standard code where an extension could subscribe a handler and be told that something had happened. Events are still everywhere in finance and operations apps, and many tasks are simpler with an event than with a wrapper. Desmond's session started with a question for Prudence: if quality engineers want an email whenever a purchase line for castings is saved with no heat number, which method would you wrap? She guessed validateWrite, then insert, then update, and then realized lines could also be created through data entities and import jobs. That, Desmond said, is what data events are for.

Kinds of events

Finance and operations apps raise several kinds of events, and each has its own handler signature. All handlers are static methods in an ordinary class, decorated with an attribute that names the event they subscribe to. The easiest way to get the signature right is to right-click the event in the designer, choose to copy the event handler method, and paste it into a handler class; Visual Studio generates the attribute and parameters.

Event types and how handlers subscribe to them.
Event kindRaised whenTypical attribute on the handler
Pre-event handlerBefore a method runsPreHandlerFor(classStr(...), methodStr(...))
Post-event handlerAfter a method runsPostHandlerFor(classStr(...), methodStr(...))
DelegateWhen standard code explicitly calls a delegate methodSubscribesTo(classStr(...), delegateStr(...))
Table data eventWhen a record is inserted, updated, deleted or validated, such as onInserted or onValidatedWriteDataEventHandler(tableStr(...), DataEventType::...)
Form eventWhen a form is initialized, closed and so onFormEventHandler(formStr(...), FormEventType::...)
Form data source eventWhen a data source is activated, written and so onFormDataSourceEventHandler(...)
Form control eventWhen a control is clicked, modified and so onFormControlEventHandler(...)
A horizontal timeline with five coloured dots. Labels from left to right: pre-event handler, method body runs, delegate raised inside method, post-event handler, and data event onInserted. A note says handlers are static methods marked with an attribute such as PostHandlerFor or SubscribesTo.
Where handlers attach to standard code.

Pre- and post-event handlers

Pre- and post-event handlers attach to the start and end of a method. A handler receives an XppPrePostArgs object, which gives access to the method's arguments, the object it was called on, and, for a post-handler, the return value. A post-handler can change the return value through the args object. For years these handlers were the main way to change standard logic, and older code in many implementations is full of them.

The same rule as lesson 3, written as a post-event handler.
class CRPurchLineEventHandlers
{
    [PostHandlerFor(tableStr(PurchLine), tableMethodStr(PurchLine, validateWrite))]
    public static void PurchLine_Post_validateWrite(XppPrePostArgs _args)
    {
        PurchLine line = _args.getThis();
        boolean   ok   = _args.getReturnValue();

        if (ok && line.CRInspectionRequired && !line.CRHeatNumber)
        {
            _args.setReturnValue(checkFailed("@CRCustom:HeatNumberRequired"));
        }
    }
}

Microsoft's guidance today is to prefer Chain of Command over pre- and post-handlers for new work. The wrapper is easier to read, has typed access to the arguments instead of going through a generic args object, can see protected members, and runs in the natural flow of the method. Pre- and post-handlers remain valid and are not deprecated, and they are still the right choice for a handful of cases, but a new team member should expect to see Chain of Command in Cobalt Ridge's code and handlers mainly in older or ISV code.

Delegates

A delegate is an empty method that standard code calls at a deliberate point, so that subscribers can react or supply information. Microsoft adds delegates where it expects customers to need extension, often with an EventHandlerResult or EventHandlerAcceptResult parameter that subscribers fill in. The calling code then checks whether a subscriber provided a result and uses it instead of the default. Delegates are a stronger contract than wrappers: Microsoft names them, documents their purpose and keeps their signatures stable.

The shape of a delegate subscription. The class and delegate names here are illustrative; real delegates are found in the reference metadata.
class CRSalesLineDelegateHandlers
{
    // Hypothetical example: a standard class raises a delegate asking
    // subscribers whether a line type needs special handling.
    [SubscribesTo(classStr(SomeStandardClass), delegateStr(SomeStandardClass, isSpecialLineDelegate))]
    public static void isSpecialLine(SalesLine _line, EventHandlerResult _result)
    {
        if (_line.ItemId == 'MC-150-KIT')
        {
            _result.result(true);
        }
    }
}

Delegates have one important limit. Because several subscribers can respond, results can conflict, and the order of subscribers is not guaranteed. Well-designed delegates use EventHandlerResult in a way where only one subscriber is expected to answer, or EventHandlerAcceptResult where any subscriber can accept. A subscriber should only answer when the case is clearly its own, such as an item or line type that its model owns.

Data events

Every table raises data events when records are inserted, updated, deleted and validated: onInserting and onInserted, onUpdating and onUpdated, onDeleting and onDeleted, onValidatedField and onValidatedWrite, among others. A handler subscribes with the DataEventHandler attribute and receives the record and a DataEventArgs object. Data events fire whenever the corresponding table method runs, wherever the change came from: a form, a data entity, an import or code. They are the right tool for reacting to data changes across the application.

There is a catch. Data events are raised by the table's insert, update and delete methods. Set-based operations such as insert_recordset, update_recordset and delete_from bypass those methods unless the table overrides them or the operation is forced to fall back to row-by-row processing. Desmond reminded Prudence of the set-based lesson in the first series: on a table with a data event subscriber, set-based operations may fall back to slower row-by-row processing so the events can fire, and a developer who adds a handler to a high-volume table can slow down someone else's batch job without realizing it.

A data event handler that queues an alert whenever a purchase line is inserted without a heat number. The queue is processed by a batch job (lesson 8).
class CRPurchLineDataEvents
{
    [DataEventHandler(tableStr(PurchLine), DataEventType::Inserted)]
    public static void PurchLine_onInserted(Common _sender, DataEventArgs _e)
    {
        PurchLine line = _sender as PurchLine;

        if (line.CRInspectionRequired && !line.CRHeatNumber)
        {
            CRInspectionAlerts::queueMissingHeat(line.RecId);
        }
    }
}

Look at what the handler does not do: it does not send email directly. Sending email inside a data event would run inside the user's transaction, slow every insert, and fail the save if the mail server was slow. Instead the handler writes a small queue record, and a batch job sends the alerts. Desmond called this the most common performance mistake in event handlers.

Form events

Forms raise events for the form itself, its data sources and its controls. Common ones include OnInitialized for the form, OnActivated and OnWritten for data sources, and OnClicked and OnModified for controls. Before Chain of Command supported nested form parts, form events were the main way to change form behaviour. They remain useful when the requirement is to react, such as refreshing another part of the form after a field changes, rather than to change what a standard method returns.

Choosing between Chain of Command and events

Desmond drew the decision on the whiteboard. First look for a delegate or a Replaceable method designed for the requirement; if one exists, use it, because it is Microsoft's intended extension point. If the requirement needs the method's arguments or its return value, use a Chain of Command wrapper. If the requirement is to react to records being saved wherever they come from, use a data event. If nothing fits, the team either redesigns the requirement or logs an extensibility request.

A decision diagram. The top box asks whether a delegate or Replaceable method exists. Arrows lead to three boxes: yes, subscribe to it; no, need the method arguments or the return value; and need to react to a record being saved anywhere. The second leads to a Chain of Command wrapper box, the third to a data event handler box. At the bottom, a red box says nothing fits, log an extensibility request with Microsoft.
A simple way to choose an extension technique.
How the inspection requirement maps to techniques.
Requirement at Cobalt RidgeTechniqueWhy
Block a receipt line without a certificateChain of Command on the posting checkNeeds the method's return value
Alert quality when a casting line is saved without a heat numberData event onInserted and onUpdatedLines arrive from forms, Excel and imports
Copy the heat number to the receipt lineChain of Command on the method that initializes receipt linesNeeds both the purchase line and the new receipt line
Refresh a certificate panel when the line changes on the formForm data source eventPure reaction in the user interface

Delegates in more detail

A delegate is declared in a standard class as a method with the delegate keyword and no body. When the standard code calls the delegate, every subscribed handler runs. Because a delegate cannot return a value directly, Microsoft passes a result object as a parameter when it wants subscribers to answer a question. An EventHandlerResult lets a subscriber provide a result, and an EventHandlerAcceptResult lets a subscriber accept responsibility for something, such as handling a document type. The standard code then checks whether any subscriber answered and uses the answer, or falls back to its own default.

A delegate subscriber that answers through an EventHandlerResult. Lesson 9 uses this pattern to register a report design; confirm the delegate signature in the reference metadata.
class CRPrintMgmtHandlers
{
    [SubscribesTo(classStr(PrintMgmtDocType), delegateStr(PrintMgmtDocType, getDefaultReportFormatDelegate))]
    public static void getDefaultReportFormatDelegate(PrintMgmtDocumentType _docType, EventHandlerResult _result)
    {
        switch (_docType)
        {
            case PrintMgmtDocumentType::PurchaseOrderPackingSlip:
                _result.result(ssrsReportStr(CRPurchPackingSlip, Report));
                break;
        }
    }
}

Delegates are the most stable kind of extension point because Microsoft added them on purpose and documents their parameters. Desmond's rule of thumb was that if a delegate exists at the place where the change is needed, use it before wrapping a method.

Form events

Forms raise events of their own. The form itself raises events such as initializing, initialized and closing. Data sources raise events such as activated, written and validated. Controls raise events such as clicked and modified. A handler subscribes with an attribute that names the form part and the event type: FormEventHandler for the form, FormDataSourceEventHandler for a data source and FormControlEventHandler for a control. The handler receives the sender, such as the FormRun or FormDataSource object, and an event arguments object. Form event handlers are useful for small user interface reactions, such as enabling a button when a field changes, and Chain of Command on form methods is often clearer for anything larger.

The same rule as the data source wrapper in lesson 3, written as a form data source event handler.
class CRPurchTableFormHandlers
{
    [FormDataSourceEventHandler(formDataSourceStr(PurchTable, PurchLine), FormDataSourceEventType::Activated)]
    public static void PurchLine_OnActivated(FormDataSource _sender, FormDataSourceEventArgs _e)
    {
        PurchLine line = _sender.cursor();
        _sender.object(fieldNum(PurchLine, CRHeatNumber)).allowEdit(line.CRInspectionRequired);
    }
}

Finding the right event

Visual Studio helps with the attribute syntax. In the designer for a table, form, data source or control, the Events node lists the events the element raises, and right-clicking an event offers to copy the event handler method. Pasting into a handler class gives the correct attribute and signature. The same works for pre- and post-handlers on methods in the designer. Prudence found this faster and less error-prone than typing attributes by hand, and it guaranteed that the element and event names were spelled correctly.

Handler classes and naming

Handlers are static methods, so they can live in any class, but Cobalt Ridge kept them in classes named for the element they handled, such as CRPurchLineEventHandlers and CRPurchTableFormHandlers. That made it easy to see everything the model did to an element in one place, which helped during service updates. Each handler method was named for the element and event, so a stack trace showed at once which handler was running.

Choosing between handlers and wrappers

With both techniques available, Prudence asked when she should still choose an event handler. Desmond's answer had three parts. Use a delegate subscriber whenever Microsoft has placed a delegate at the right spot, because that is the designed extension point. Use a data event handler when the requirement is to react to data changes wherever they come from, because data events catch changes from forms, entities and code alike. Use Chain of Command for most other changes to a method's behaviour, because it reads clearly, can use protected members and keeps the logic next to the method it changes. Pre- and post-handlers remain valid, and existing code full of them does not need rewriting, but new Cobalt Ridge code used them only where a wrapper was not possible.

He added a warning about mixing techniques on the same method. If one rule is enforced by a post-handler and another by a wrapper on the same method, a reader has to look in two places to understand what happens, and the order between handlers and wrappers is something developers should not rely on. Cobalt Ridge kept each method's extensions in one technique.

Worked problem

Finding a delegate before writing a wrapper

Prudence wants to stop the purchase order confirmation if any casting line lacks a heat number. Before writing a wrapper, Desmond asks her to look for a delegate.

Show solution
  1. Open the form letter class for purchase confirmation in the reference metadata.
  2. Search the class and its base classes for methods whose names end in Delegate, and read where they are called.
  3. If a delegate is called during validation with a result parameter, subscribe to it and supply the failure only for lines the CR model cares about.
  4. If no suitable delegate exists, wrap the validation method with Chain of Command instead, following the rules from lesson 3.

Answer: Delegates come first because they are Microsoft's designed extension points with stable contracts; Chain of Command is the fallback when none fits.

Common mistakes

  • MistakeDoing slow work, such as sending email, inside a data event handler.

    InsteadWrite a small queue record and process it in a batch job.

  • MistakeAssuming data events fire for every set-based operation.

    InsteadSet-based operations bypass insert, update and delete unless they fall back to row by row; check how the data is written.

  • MistakeAnswering a delegate for every case.

    InsteadAnswer only for records your model owns, so you do not override another subscriber.

  • MistakeTyping handler signatures by hand.

    InsteadCopy the event handler method from the designer so the attribute and parameters are correct.

Summary and key terms

  • Event handlers are static methods subscribed by attributes to pre and post events, delegates, data events and form events.
  • Pre- and post-handlers use XppPrePostArgs; Chain of Command is now preferred for changing method behaviour.
  • Delegates are deliberate extension points with stable contracts and should be checked first.
  • Data events fire whenever table methods run, from any source, but set-based operations may bypass them.
  • Handlers should be fast; queue slow work for batch processing.
Event handler
A static method that runs when a subscribed event is raised.
Delegate
An empty method that standard code calls so that subscribers can respond.
Data event
An event raised by a table when records are inserted, updated, deleted or validated.
XppPrePostArgs
The object that gives pre- and post-handlers access to arguments, the instance and the return value.
EventHandlerResult
A parameter type that lets a delegate subscriber return a result to the caller.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why did Desmond use a data event rather than wrapping a form method for the missing heat alert?

    Show answer

    Lines are created from forms, Excel and imports; a data event fires for all of them.

  2. What is the quickest way to get a correct handler signature?

    Show answer

    Copy the event handler method from the event in the designer.

  3. Which technique should be checked first for a new requirement?

    Show answer

    A delegate or Replaceable method designed for it.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz