MSBA-359 · Lesson 5 of 12 · 22 min

Domain review: business logic and events

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

Of all the ideas in AL, events were the one that changed how Joss thought. In C# he would have subclassed something or edited the method. In Business Central he learned to ask, "Where does Microsoft let me in?" and to find the answer with the Event Recorder. Noor wanted that instinct sharpened for the exam, but she also wanted him to see that the skill area around it is wider than events. "Half of this area is about doing things the way Business Central does them," she said. "Document patterns, setup tables, assisted setup, error messages. A lot of developers lose marks there because they code like it is any other platform."

This lesson reviews Develop user experiences and logic by using AL, worth 15 to 20 percent, together with the event and interface bullets of the codeunits group from the AL objects area. The logic area has three objective groups: customizing the user interface and onboarding, implementing essential development standards, and extending Business Central with AL code.

Profiles and customizations

A profile represents a role. It names a Role Center and can carry page customizations that change pages for everyone with that profile: hiding fields, moving actions, adding views. In AL, a profile object sets the RoleCenter and lists Customizations, each a pagecustomization object. Users pick a profile in My Settings, and administrators assign profiles to users or make one the default. Profiles can also be created and customized in the client by administrators, without code, and exported as an extension.

Three similar-sounding activities differ by who they affect. Personalization is a user changing a page for themselves. Customization is an administrator changing a page for everyone with a profile. Designer or AL development creates an extension that changes the page for everyone. Exam questions often describe one and offer the others as distractors.

A profile with a Role Center and a page customization that hides a field and adds a view (illustrative).
profile "CNF WARRANTY CLERK"
{
    Caption = 'Warranty clerk';
    ProfileDescription = 'Registers warranties and handles claims.';
    RoleCenter = "CNF Warranty Clerk RC";
    Customizations = "CNF Claims Clerk View";
}

pagecustomization "CNF Claims Clerk View" customizes "CNF Warranty Claims"
{
    layout
    {
        modify("Internal Notes") { Visible = false; }
    }
    views
    {
        addfirst
        {
            view(OpenClaims)
            {
                Caption = 'Open claims';
                Filters = where(Status = const(Open));
                OrderBy = ascending("Claim Date");
            }
        }
    }
}

The user assistance model

Business Central has a consistent way of explaining itself, and the outline asks you to use it. Tooltips on fields and actions explain what each control is for; in recent versions they can be defined on table fields as well as page controls, so every page showing the field inherits them. Teaching tips use AboutTitle and AboutText on pages, parts, fields and actions to give a short tour the first time a user opens a page. InstructionalText guides input in a field, as on a Copilot prompt. Longer help lives in documentation linked through ContextSensitiveHelpPage and the app's help URL.

Assisted setup and onboarding

New users and administrators meet an app through its setup. Assisted setup guides are wizards, usually NavigatePage pages with steps and Back, Next and Finish actions, registered so they appear on the Assisted Setup page and in checklists. Registration uses the Guided Experience codeunit from the System Application: InsertAssistedSetup for wizards and InsertManualSetup for setup pages listed under Manual Setup, normally called from a subscriber to the event that asks apps to register their guides. When the wizard finishes, the code marks the guide complete so the checklist shows progress.

Essential development standards

The outline calls these "standards", and they are the patterns that make Business Central feel consistent. The data process model describes how data moves: setup tables configure behavior, master data (customers, items, vendors) describes the things the business deals with, documents and journals capture transactions before they are final, posting turns them into ledger entries, which are never changed afterwards, and registers record which entries each posting created. Posted documents are kept as history.

A left-to-right flow. Setup and master data tables feed documents and journals. A posting routine turns documents and journals into ledger entries, a register and posted history documents. Ledger entries and history are marked as read-only.
The data process model: from setup and master data to ledger entries and history.
Functional table types and how to recognize them.
Functional table typeCharacteristicsExample
SetupOne record per company; a primary key field with an empty value; read through GetCNF Warranty Setup
MasterA card and list page, a No. field with number series, Blocked, Search Name, default dimensionsCustomer, Item
SupplementalSmall lookup tables used by master and transaction tablesPayment Terms, Claim fault categories
DocumentHeader and line tables linked by document type and number; a status; editable until postedSales Header and Sales Line
JournalTemplate, batch and line tables; lines posted in batchesGeneral Journal Line
Ledger entryCreated only by posting; never modified or deleted by usersCust. Ledger Entry
RegisterRecords the range of entries one posting createdG/L Register
HistoryPosted documents kept for referenceSales Invoice Header
CueHolds FlowFields for Role Center tiles; one recordSales Cue

Document patterns follow from the model. A document has a header and lines; the lines carry the document type and number of their header. It has a status that controls editing, with release and reopen actions. A separate posting codeunit, usually named after the document with "-Post", checks the document, creates entries and history, and deletes the open document in one transaction. Master data standards include a No. field filled from a number series, a Blocked field that stops new transactions without deleting history, a Search Name, comments, default dimensions and card and list pages. The warranty extension followed these patterns: the registration table is master-like, claims are document-like, and expired registrations are never deleted.

Events: the extension contract

An event is a point where code announces that something is happening, and other code can subscribe to run at that point. There are three kinds.

The three kinds of events in AL.
Event kindWho defines itHow it is declaredTypical use
Trigger eventThe platform, for every table and pageAutomatic, such as OnAfterInsertEvent or OnBeforeValidateEventReact to record and field operations
Integration eventAny developer[IntegrationEvent(IncludeSender, GlobalVarAccess)] on an empty procedureExtension points in your own logic; may change between versions
Business eventAny developer[BusinessEvent(IncludeSender)] on an empty procedureA stable, documented contract for a business action; should not change

A publisher is an empty procedure with an event attribute, called at the right moment. A subscriber is a procedure in a codeunit with an [EventSubscriber] attribute naming the object type, the object, the event name, the element (for trigger events on fields) and two flags, SkipOnMissingLicense and SkipOnMissingPermission. Subscriber parameters must match the publisher's by name and type, but a subscriber may declare only the parameters it needs. Parameters passed var can be changed by the subscriber, which is how subscribers influence the publisher's code.

Publishing OnBefore and OnAfter integration events with the IsHandled pattern, and a subscriber.
codeunit 50105 "CNF Claim Events"
{
    procedure ApproveClaim(var Claim: Record "CNF Warranty Claim")
    var
        IsHandled: Boolean;
    begin
        OnBeforeApproveClaim(Claim, IsHandled);
        if IsHandled then
            exit;
        Claim.TestField(Status, Claim.Status::Open);
        Claim.Validate(Status, Claim.Status::Approved);
        Claim.Modify(true);
        OnAfterApproveClaim(Claim);
    end;

    [IntegrationEvent(false, false)]
    local procedure OnBeforeApproveClaim(var Claim: Record "CNF Warranty Claim"; var IsHandled: Boolean)
    begin
    end;

    [IntegrationEvent(false, false)]
    local procedure OnAfterApproveClaim(var Claim: Record "CNF Warranty Claim")
    begin
    end;
}

codeunit 50106 "CNF Claim Notify"
{
    [EventSubscriber(ObjectType::Codeunit, Codeunit::"CNF Claim Events", 'OnAfterApproveClaim', '', false, false)]
    local procedure NotifyCustomer(var Claim: Record "CNF Warranty Claim")
    begin
        // send the approval notice
    end;
}
A sequence diagram. ApproveClaim calls OnBeforeApproveClaim. A subscriber may set IsHandled to true, in which case ApproveClaim exits. Otherwise the standard logic runs, then OnAfterApproveClaim is raised and a notification subscriber runs.
The IsHandled pattern: an OnBefore event that can replace the standard logic, and an OnAfter event that adds to it.

The IsHandled pattern is everywhere in the base application: an OnBefore event passes a var Boolean, and if a subscriber sets it to true, the publisher skips its standard logic. It is powerful and dangerous, because a subscriber that handles the event takes responsibility for everything the standard code would have done, and two apps that both handle the same event will conflict. Prefer OnAfter events that add behavior; use IsHandled only when the requirement is genuinely to replace logic.

Three more event facts come up often. Subscribers in a codeunit with EventSubscriberInstance = StaticAutomatic (the default) run whenever the event fires. With Manual, they run only while the codeunit instance is bound with BindSubscription, until UnbindSubscription or the instance goes out of scope, which is useful in tests and for behavior that should apply only during one operation. IncludeSender gives the subscriber access to the publishing object, and GlobalVarAccess to its global variables; both make the subscriber depend on internals and are used sparingly. To find events, the Event Recorder page records the events raised while you perform an action in the client and lists them with ready-made subscriber code.

Interfaces

An interface declares procedures without code. Codeunits implement it, and code holds a variable of the interface type, assigned from a codeunit or from an enum value whose implementation is declared on the enum. Interfaces let an app offer a choice of behaviors, such as claim resolution types or price calculation methods, that other apps can extend without changing the calling code. In recent runtimes an interface can also extend other interfaces, and code can test and cast between interfaces with the is and as operators.

AL programming essentials

The third group, Extend Business Central by using AL, lists ten bullets that together mean "write correct AL". The exam tests them through code reading, which lesson 8 practices; here are the facts behind them.

Data types. Simple types include Integer, BigInteger, Decimal, Boolean, Text (unlimited or with a maximum length), Code (uppercased, trimmed), Date, Time, DateTime, Duration, DateFormula, Guid and Enum. Complex types include Record, RecordRef and FieldRef, Codeunit, Page, Report and Query variables, List and Dictionary, JsonObject, JsonArray, JsonToken and JsonValue, HttpClient and its message types, InStream and OutStream, TextBuilder, SecretText and ErrorInfo. Variables are declared in a var section; a temporary record variable lives only in memory.

Access modifiers. Procedures are public unless marked local (only in the same object) or internal (only in the same app, and apps listed in internalsVisibleTo). Global variables in table and page extensions can be protected, which makes them visible to extensions of that extension. Objects themselves have an Access property of Public or Internal. Marketplace publishers use internal access to keep the freedom to change code without breaking other apps.

Statements and built-in functions. AL has if-then-else, case, repeat-until, while-do, for-to and foreach for lists and dictionaries, and exit to return. Common built-in functions include CalcDate, Format, Evaluate, StrSubstNo, CopyStr, StrLen, Round, IncStr, DelChr, Today and WorkDate. Record methods include Get, FindFirst, FindSet with Next, SetRange and SetFilter, Insert, Modify, Delete, Validate, TestField, CalcFields, CalcSums, IsEmpty, SetLoadFields and TransferFields.

Manipulating data. Use FindSet and a repeat-until loop to process many records, FindFirst only to get one, Get when you know the primary key, and IsEmpty to test existence. Validate a field when its OnValidate logic must run; assign directly only when you deliberately skip it. Call Modify(true) when table triggers must run. Use ModifyAll and DeleteAll for set-based changes, remembering that they run triggers only when called with true, record by record.

Managing errors. Error stops execution and rolls back the transaction. An ErrorInfo object carries a message plus a title, detailed message, and actions (AddAction, AddNavigationAction) that help the user fix the problem: actionable errors. Collectible errors let a procedure with the ErrorBehavior attribute set to Collect gather several errors instead of stopping at the first, so the user sees them all; ErrorInfo.Collectible must be true on each. A [TryFunction] procedure returns false instead of raising an error, but database changes made inside it are not rolled back, so keep writes out of try methods. Codeunit.Run with a return value catches errors from the codeunit and rolls back its changes. GetLastErrorText reads the message afterwards.

Managing files. Business Central online has no server file system. Files move as streams: UploadIntoStream gets a file from the user, DownloadFromStream sends one, and the Temp Blob codeunit holds data in memory between an OutStream and an InStream. Blob fields, Media and MediaSet fields store files in the database, and the Document Attachment feature stores files against records. Base64 conversion, compression and CSV parsing are available as System Application modules and buffer tables.

An actionable error: the user can open the registration from the error message.
procedure CheckClaim(Claim: Record "CNF Warranty Claim")
var
    Registration: Record "CNF Warranty Registration";
    Info: ErrorInfo;
begin
    Registration.Get(Claim."Registration No.");
    if Registration."End Date" < Claim."Claim Date" then begin
        Info.Title := 'Warranty expired';
        Info.Message := StrSubstNo(ExpiredErr, Registration."No.", Registration."End Date");
        Info.RecordId := Registration.RecordId;
        Info.AddNavigationAction('Open registration');
        Error(Info);
    end;
end;

How logic questions are worded

Questions in this area usually take one of three forms. The first describes a requirement and asks which pattern meets it: "a value must be stored once per company and read by every page of the app" points to a setup table read with Get. The second shows a few lines of code and asks what they do, which lesson 8 practices. The third describes a symptom: "users see one error, fix it, then see the next" points to collectible errors; "a partner's subscriber stops our standard logic running" points to IsHandled. For each form, ask what Business Central's own code does in the same situation. The base application is the reference implementation of every standard in this area, and an answer that copies its pattern is rarely wrong.

Worked problem

Event or not?

Three requests reach Joss: (a) when a sales order with a grinder is released, warn if the customer has an expired warranty for the same item; (b) the warranty claim approval must be skippable by a future app that sends claims to the manufacturer instead; (c) store the date each claim was first viewed by a clerk.

Show solution
  1. (a) Subscribe to an event raised when a sales document is released, in a codeunit with the default StaticAutomatic instance; show a notification, not an error, because it is a warning.
  2. (b) Publish an OnBefore integration event with an IsHandled parameter in the approval procedure, as in the listing above.
  3. (c) Add a field to the claim table and set it in the claim card page's OnAfterGetCurrRecord if empty; this is your own object, so no event is needed.

Answer: Subscribe to other publishers' events to change their behavior; publish events in your own code so others can change yours; and do not use events inside your own objects when direct code is clearer.

Common mistakes

  • MistakeUsing IsHandled when an OnAfter event would do.

    InsteadHandle only when the requirement is to replace logic; otherwise add after.

  • MistakeCalling personalization what is really a profile customization.

    InsteadPersonalization affects one user; customization affects a profile.

  • MistakeWriting to the database inside a try method.

    InsteadChanges inside a TryFunction are not rolled back; keep writes outside.

  • MistakeDeleting ledger entries or history to fix data.

    InsteadLedger entries and posted documents are never deleted; correct with new postings.

  • MistakeAssuming subscribers need every publisher parameter.

    InsteadSubscribers may declare only the parameters they use, matched by name.

Summary and key terms

  • Profiles name a Role Center and carry customizations; views save filters and sorting; personalization is per user.
  • Tooltips, teaching tips and instructional text form the user assistance model; assisted setup is registered through Guided Experience.
  • The data process model runs from setup and master data through documents and journals to ledger entries, registers and history.
  • Events are trigger, integration or business events; subscribers match by name and may use a subset of parameters; IsHandled replaces logic.
  • Interfaces separate what from how; enums can implement them.
  • Errors can be actionable and collectible; files move as streams in the cloud.
Profile
A role definition naming a Role Center and page customizations.
Teaching tip
A short in-product explanation defined with AboutTitle and AboutText.
Integration event
A developer-defined event intended as an extension point; may change between versions.
Business event
A developer-defined event intended as a stable contract for a business action.
IsHandled pattern
An OnBefore event with a var Boolean that lets a subscriber replace the standard logic.
Collectible error
An error gathered with others when the procedure's ErrorBehavior is Collect.
Temp Blob
A System Application codeunit that holds binary data in memory between streams.

Practice problems

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

  1. Which page lists the events raised by an action in the client?

    Show answer

    The Event Recorder.

  2. Which codeunit registers assisted setup guides?

    Show answer

    Guided Experience.

  3. Which property makes subscribers run only while bound?

    Show answer

    EventSubscriberInstance = Manual, with BindSubscription.

  4. How does a user get a file into Business Central online from code?

    Show answer

    UploadIntoStream into an InStream, often through Temp Blob.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz