MSBA-352 · Lesson 6 of 12 · 20 min

Events and subscribers

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

The warranty app now had a procedure that registers a serial number, and nothing that called it. Callum's requirement was clear: when a shipment of a grinder or brewer posts, the warranty should exist, without anyone remembering to create it. In the old days of Dynamics NAV, a developer would have opened the sales posting codeunit and inserted a line. In Business Central that is impossible, and Noor was glad of it. "Microsoft's posting code is not ours to change," she said. "But Microsoft has left doors in it. Our job is to find the right door." The doors are events.

The event model

An event is a named point in code where something can react. The code that declares and raises the event is the publisher. Code that wants to react declares a subscriber: a procedure in a codeunit, marked with an attribute that names the publisher and the event. When the publisher raises the event, Business Central calls every subscriber in every installed app. The publisher does not know who is listening, and the subscribers do not change the publisher's code.

A publisher box labelled Sales-Post codeunit with a line of code raising OnAfterPostSalesDoc. Three arrows fan out to subscriber boxes in different apps: the warranty extension's CNF Warranty Subscribers codeunit, the web shop integration extension and a Microsoft app. A note says the publisher does not know its subscribers, and the order subscribers run in is not guaranteed.
One publisher, many subscribers in many apps.

This is how Microsoft keeps thousands of partner extensions working through monthly updates. As long as an event keeps its name and parameters, Microsoft can rewrite everything around it. When Microsoft does need to change or remove an event, it marks it obsolete first and gives partners at least one release to move, and the compiler warns about subscribers to obsolete events.

Kinds of events

Kinds of events.
KindDeclared withRaised byPromise
Integration event[IntegrationEvent]Code calling the event procedureA hook for extensions; may change between versions with notice
Business event[BusinessEvent]Code calling the event procedureA stable, documented business moment that should not change
Internal event[InternalEvent]Code calling the event procedureOnly subscribers in the same app
Trigger eventsBuilt in, no declarationThe platform around table and page triggersOnBeforeInsertEvent, OnAfterModifyEvent, OnAfterValidateEvent and so on
External business events[ExternalBusinessEvent]CodeNotifications sent outside Business Central, for example to Power Automate (next course)

Most events a partner subscribes to are integration events that Microsoft has placed throughout the base application, often in pairs named OnBefore and OnAfter something. Trigger events exist for every table and page automatically: every table raises OnBeforeInsertEvent and OnAfterInsertEvent around inserts, every field raises OnBeforeValidateEvent and OnAfterValidateEvent, and pages raise events around their triggers and actions.

Finding the right event

Choosing the event is the hard part, and Noor spent a whole session on it. The warranty registration needs four facts: the serial number, the item, the customer and the ship date. They all exist once a shipment has posted. Joss considered three candidates.

Three candidate events for creating registrations.
CandidateProsCons
OnAfterInsertEvent on Item Ledger EntryFires for every ledger entry, with the serial number on itFires for every entry of every kind, from purchases to adjustments; the code would run thousands of times a day just to ignore most of them
An event inside the shipment line posting loopClose to the dataFires before the posting is finished; if something later fails, the registration rolls back with it, which is fine, but the posted shipment number may not be final yet
OnAfterPostSalesDoc in Sales-PostFires once per posted document, after everything is posted, and passes the posted shipment numberThe code must look up the shipment's item ledger entries to find serial numbers

They chose OnAfterPostSalesDoc, published by the Sales-Post codeunit. It fires once for each sales document posted, still inside the posting transaction, and passes the numbers of the documents it created, including the posted shipment. If the registration fails, the whole posting rolls back, which Callum preferred: a grinder should never leave the building without a warranty.

Joss learned three ways to find events. The Event Recorder page in the client records every event raised while a user performs an action, so Joss started recording, posted a shipment in the container, stopped, and got a list of a few hundred events in the order they fired, with the publishing object. The AL Explorer in Visual Studio Code lists events across the symbols, filtered by object or name. And reading the publisher's source, by going to the definition of Sales-Post, shows exactly where an event fires and which variables it passes. Microsoft also publishes the base application's source on GitHub, which helps when searching across many objects.

Writing the subscriber

The subscriber that registers warranties after a sales document posts.
namespace Quarrystone.CorbelFinch.Warranty;

using Microsoft.Sales.Document;
using Microsoft.Sales.Posting;
using Microsoft.Sales.History;
using Microsoft.Inventory.Ledger;

codeunit 50103 "CNF Warranty Subscribers"
{
    Access = Internal;

    [EventSubscriber(ObjectType::Codeunit, Codeunit::"Sales-Post", 'OnAfterPostSalesDoc', '', false, false)]
    local procedure RegisterWarrantiesOnAfterPostSalesDoc(var SalesHeader: Record "Sales Header"; SalesShptHdrNo: Code[20])
    begin
        if SalesShptHdrNo = '' then
            exit;
        RegisterFromShipment(SalesShptHdrNo);
    end;

    local procedure RegisterFromShipment(ShipmentNo: Code[20])
    var
        ShipmentHeader: Record "Sales Shipment Header";
        ItemLedgerEntry: Record "Item Ledger Entry";
        WarrantyMgt: Codeunit "CNF Warranty Mgt.";
    begin
        ShipmentHeader.SetLoadFields("Sell-to Customer No.", "Shipment Date");
        ShipmentHeader.Get(ShipmentNo);

        ItemLedgerEntry.SetLoadFields("Item No.", "Serial No.");
        ItemLedgerEntry.SetRange("Document Type", ItemLedgerEntry."Document Type"::"Sales Shipment");
        ItemLedgerEntry.SetRange("Document No.", ShipmentNo);
        ItemLedgerEntry.SetFilter("Serial No.", '<>%1', '');
        if ItemLedgerEntry.FindSet() then
            repeat
                WarrantyMgt.RegisterSerialNo(ItemLedgerEntry."Serial No.", ItemLedgerEntry."Item No.",
                    ShipmentHeader."Sell-to Customer No.", ShipmentNo, ShipmentHeader."Shipment Date");
            until ItemLedgerEntry.Next() = 0;
    end;
}

The attribute has six arguments: the object type of the publisher, the publisher object, the event name in quotes, an element name (used only for trigger events on a specific field, so empty here), and two Booleans, SkipOnMissingLicense and SkipOnMissingPermission, which decide whether the subscriber is silently skipped when the user lacks the licence or permissions for it. Joss left both false: if a user cannot run the warranty code, Callum wants to know, not to have warranties quietly missing.

The subscriber's parameters must match the publisher's by name and type, but a subscriber may declare only the parameters it needs. OnAfterPostSalesDoc passes a dozen; Joss's subscriber takes two. Parameters marked var in the publisher must be var in the subscriber too.

The subscriber itself is two lines: exit if no shipment was posted (an invoice for goods shipped earlier, for example), otherwise call a local procedure. All the logic lives in RegisterFromShipment and in the warranty management codeunit, which can be tested without posting anything.

What a subscriber must not do

A subscriber inside posting runs in the middle of Microsoft's transaction. Noor gave Joss four rules.

  • No Commit. Committing inside posting would save half-posted data if a later step failed. CodeCop and Microsoft's guidelines both forbid it.
  • No user interaction. Posting can run from the job queue, from a warehouse shipment, or from an API. A Confirm or a page in a subscriber breaks those paths.
  • Be fast and narrow. Every posting in the company now runs this code. SetLoadFields, tight filters and an early exit keep the cost small. A subscriber that reads the whole item ledger would slow every sale.
  • Expect to be one of many. Other apps may subscribe to the same event, and the order in which subscribers run is not guaranteed. Code must not assume another subscriber has or has not run.

The handled pattern

Many OnBefore events in the base application have a parameter called IsHandled. A subscriber that sets it to true tells the publisher "I have done this work; skip the standard code." It is powerful and dangerous. Two apps that both handle the same event will fight, and an app that handles an event replaces Microsoft's logic with its own, losing every fix Microsoft makes later. Noor's rule was to use handled events only when there is no other way, to document why in the code, and never to use them in the warranty app.

A timeline of sales posting from left to right: OnBeforePostSalesDoc, check and release, post shipment lines with item ledger entries and serial numbers, post invoice lines, OnAfterPostSalesDoc, then commit. The warranty subscriber attaches to OnAfterPostSalesDoc, shown before the commit point, with a note that an error there rolls back the whole posting.
Where the warranty subscriber runs in sales posting: after the documents exist, before the commit.

Publishing your own events

Joss's app is also a publisher. Quarrystone might one day build a loaner-machine app, or another partner might extend the warranty app for a different customer. Noor asked Joss to add integration events at the moments another developer might want to react to: before a registration is created, and after one is voided.

Declaring and raising integration events in the warranty app.
    // in codeunit "CNF Warranty Mgt."
    procedure RegisterSerialNo(SerialNo: Code[50]; ItemNo: Code[20]; CustomerNo: Code[20]; ShipmentNo: Code[20]; ShipDate: Date)
    var
        Registration: Record "CNF Warranty Registration";
        IsHandled: Boolean;
    begin
        if not ShouldRegister(ItemNo) then
            exit;
        if AlreadyRegistered(SerialNo, ItemNo) then
            exit;
        OnBeforeCreateRegistration(SerialNo, ItemNo, CustomerNo, IsHandled);
        if IsHandled then
            exit;
        // ... create the registration as before ...
        OnAfterCreateRegistration(Registration);
    end;

    [IntegrationEvent(false, false)]
    local procedure OnBeforeCreateRegistration(SerialNo: Code[50]; ItemNo: Code[20]; CustomerNo: Code[20]; var IsHandled: Boolean)
    begin
    end;

    [IntegrationEvent(false, false)]
    local procedure OnAfterCreateRegistration(var Registration: Record "CNF Warranty Registration")
    begin
    end;

An event publisher is a procedure with an empty body and an event attribute. The two Booleans on IntegrationEvent are IncludeSender, which passes the publishing object to subscribers, and GlobalVarAccess, which lets subscribers see the publisher's global variables; both are normally false. Publishers are usually local, because only the owning object should raise its own events, while any app can still subscribe. Raising the event is simply calling the procedure.

Noor had a rule here too: think before adding an IsHandled parameter. Every handled event is a way for someone else to switch off your logic. For the warranty app, an OnBefore event with IsHandled was justified, because a different customer might register warranties in a completely different way; an OnAfter event without it covers most other needs.

Subscriber instances and binding

By default a subscriber codeunit has EventSubscriberInstance = StaticAutomatic: Business Central creates an instance whenever the event fires, and the subscription is always active. Setting it to Manual means the subscription is active only after code calls BindSubscription on a codeunit variable, and stops at UnbindSubscription or when the variable goes out of scope. Manual binding is useful when a behaviour should apply only during one process, such as a data migration that must not trigger warranty registration. Joss used it in the import of old spreadsheet warranties, so that a test posting during the import did not double-register.

Table and page trigger events

One more subscriber completed the first version. Callum wanted a warning if someone ticked Register Warranty on an item without a warranty period. The check belongs to the Item table, which Joss had extended, but there was an alternative: subscribe to the field's trigger event.

A subscriber to a field's OnAfterValidateEvent, using the element name argument.
    [EventSubscriber(ObjectType::Table, Database::Item, 'OnAfterValidateEvent', 'CNF Register Warranty', false, false)]
    local procedure CheckPeriodOnAfterValidateRegisterWarranty(var Rec: Record Item; var xRec: Record Item)
    begin
        if Rec."CNF Register Warranty" and (Format(Rec."CNF Warranty Period") = '') then
            Error(PeriodFirstErr);
    end;

Here the fourth argument names the field. Rec is the record after the change and xRec the record before it, the same pair that standard triggers use. In the end Joss moved this rule into an OnValidate trigger on the field in the table extension itself, because the field belongs to the app and a trigger is easier to read than a subscriber; trigger events are most useful for reacting to standard fields, such as running a check when the Item Tracking Code changes.

Worked problem

Choosing between a trigger event and an integration event

Callum asks that a warning appear when a salesperson adds a grinder to a sales order for a customer that already has three active grinder warranties. Which event should Joss use?

Show solution
  1. The moment is when the item number on a sales line is set. That is the No. field on the Sales Line table.
  2. A trigger event, OnAfterValidateEvent on Sales Line with element name No., fires whenever the field is validated, from the page, an API or code.
  3. Sales Line also has many integration events around validation of No.; the Event Recorder shows which fire when a user enters an item.
  4. Because the request is a warning, not a block, and the sales order may be created by an API with no user present, the subscriber should not use Message or Confirm. A notification on the page is the right tool, raised from a page extension on the Sales Order Subform instead.

Answer: Use a page-level notification for a user warning; trigger and integration events run in every path, including ones without a user.

Testing a subscriber

A subscriber is tested by making its event fire, which for OnAfterPostSalesDoc means posting a real sales document. Joss's manual test in the container followed the same steps every time: create a sales order for a warranty item and a non-warranty item, assign two serial numbers on the warranty line, post the shipment, and check that exactly two registrations exist with the right customer, shipment and end dates. Then post the invoice separately and check that nothing changed. Then ship a coffee bag with a lot number and check that no registration appears. Each of these checks became a test case for the automated tests in the next course. Keeping the subscriber thin paid off here: almost all the logic could be tested by calling RegisterSerialNo directly, and only the wiring needed a full posting.

Common mistakes

  • MistakeSubscribing to a very frequent event, such as every item ledger insert, and filtering inside.

    InsteadChoose the event closest to the business moment, such as once per posted document.

  • MistakeCalling Commit or Confirm in a posting subscriber.

    InsteadDo the work silently inside the transaction; errors roll back the posting.

  • MistakeCopying a publisher's whole parameter list by hand.

    InsteadUse the snippet or code action, and declare only the parameters needed.

  • MistakeSetting IsHandled to true to replace standard behaviour casually.

    InsteadUse handled events only when there is no alternative, and document why.

  • MistakeAssuming subscribers run in a particular order.

    InsteadWrite each subscriber so it works whatever ran before it.

Summary and key terms

  • Events let extensions react to Microsoft's code without changing it; publishers raise events and subscribers respond.
  • Integration events are the usual hooks; trigger events exist automatically around table and page triggers.
  • Find events with the Event Recorder, the AL Explorer and the publisher's source.
  • Subscribers declare an EventSubscriber attribute and may use only the parameters they need.
  • Subscribers inside posting must not commit or talk to users, and should be fast.
  • Apps should publish their own integration events at meaningful moments, with IsHandled used sparingly.
Event
A named point in code where subscribers can react.
Publisher
The procedure that declares an event and the code that raises it.
Subscriber
A procedure that runs when a specific event is raised.
Integration event
An event declared for extensions to hook into.
Trigger event
An event raised automatically around a table or page trigger.
IsHandled
A parameter that lets a subscriber tell the publisher to skip standard code.
Event Recorder
A client page that records which events fire during an action.

Practice problems

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

  1. Why did Joss reject OnAfterInsertEvent on Item Ledger Entry?

    Show answer

    It fires for every ledger entry of every kind, so the code would run thousands of times a day only to ignore most entries.

  2. Why does the subscriber exit when SalesShptHdrNo is empty?

    Show answer

    The posting did not create a shipment, for example an invoice for goods shipped earlier, so there is nothing to register.

  3. What do SkipOnMissingLicense and SkipOnMissingPermission do, and why did Joss set them to false?

    Show answer

    They skip the subscriber silently when the user lacks licence or permissions; false makes the problem visible instead of leaving warranties missing.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz