IceOnlys Blog

All Around Microsoft Dynamics Business Central

BusinessCraft: Global Triggers, the Change Log, and Control Add-ins

The last BusinessCraft post ended with two promises: generic table and page events, and global triggers. One of them is done. BusinessCraft now runs the global triggers, and the mini base app got the first real user of them: a change log. On top of that, BusinessCraft can host control add-ins now. To test them, Business Central plays Tic Tac Toe against you. :)

Global Triggers

In Business Central, the change log is not part of the platform. It is plain AL. The platform only offers a hook: the codeunit "Global Triggers". Every app can subscribe to its events and gets called for every write on every table it registered for. There are two pipelines:

Events Registration When BusinessCraft raises them
OnDatabaseInsert, OnDatabaseModify, OnDatabaseDelete, OnDatabaseRename GetDatabaseTableTriggerSetup sets four booleans Before every write, from AL and from the UI
OnGlobalInsert, OnGlobalModify, OnGlobalDelete, OnGlobalRename GetGlobalTableTriggerMask returns a bitmask (1 insert, 2 modify, 4 delete, 8 rename) After writes from the UI only

If nobody registers a table, nothing fires. That is the important part for performance: the platform asks each table once per session and caches the answer. A subscriber that changes its mind, like the change log after you change its setup, calls SessionSetting.RequestSessionUpdate, and the next session asks again.

The subscriber side in the mini base app is short:

[EventSubscriber(ObjectType::Codeunit, Codeunit::"Global Triggers", OnDatabaseModify, '', false, false)]
local procedure GlobalTriggers_OnDatabaseModify(RecRef: RecordRef)
var
    ChangeLogManagement: Codeunit "Change Log Management";
begin
    if GetExecutionContext() = ExecutionContext::Normal then
        ChangeLogManagement.LogModification(RecRef);
end;

Before the write, not after

My first version raised OnDatabaseModify after the row was written. That sounds logical, but it breaks the change log. Look at how it finds the old values:

xRecRef.Open(RecRef.Number, false, RecRef.CurrentCompany);
xRecRef.ReadIsolation := xRecRef.ReadIsolation::ReadCommitted;
if xRecRef.ReadPermission() then begin
    IsReadable := true;
    if not xRecRef.Get(RecRef.RecordId) then
        exit;
end;

It reads the row from the database and compares it field by field with RecRef. If the row is already written, both are equal, and nothing is logged. So the event has to run before the physical write. RecRef holds the new values, the database still holds the old ones.

What the change log found

The change log turned out to be a good test. It found four bugs in BusinessCraft that had nothing to do with global triggers:

  • Named return values. HasValue(FldRef) Result: Boolean assigns Result and never calls exit. Publishing dropped the name of the return value, so the procedure always returned false. Insertions and deletions log only fields with a value, so nothing was logged at all.
  • System fields. Every modify also logged SystemModifiedAt. In BusinessCraft, the audit fields were stamped before the event. Now they are stamped after it, so only the fields the user changed show up. SystemRowVersion also no longer counts in RecRef.FieldCount.
  • Stack overflows. The three change log setup tables are always logged. Saving the setup writes a setup row, which raises OnDatabaseInsert, which writes a change log entry, which runs its own triggers. Each level nested another async call in Rust, and the stack ran out. Temporary records no longer raise the events, and the nested calls now live on the heap instead of the stack.
  • Confirm in OnValidate. A Confirm inside a field OnValidate on a page now waits for the answer and then continues the trigger.

The Change Log in the mini base app

The mini base app has a change log now, with setup, table list, field list, and the entries page. It works like the one in BC: activate it, pick the tables, choose All Fields or Some Fields for insertion, modification, and deletion, and select the fields.

The pages needed a few things BusinessCraft did not have:

  • AssistEdit on option fields. The Log Modification column in the table list is an option field with an OnAssistEdit trigger that opens the field list.
  • Page.Run from a modal page. The field list opens from the modal table list, and it now stacks on top of it.
  • Page variables before opening. The table list calls ChangeLogSetupFieldList.SelectColumn(...) before it runs the page, to show only the columns for one type of change. These calls now run before Visible hides the columns.
  • Pages on virtual tables. The field list uses the virtual table Field as source table and keeps the checkboxes in page variables. BusinessCraft tried to write Rec back to Field after every checkbox, and failed, because there is no physical table 2000000041. Read-only virtual tables are no longer written.
  • FlowFields into virtual tables. Table Caption and Field Caption on the entries page are lookups into AllObjWithCaption and Field. Both are built from metadata, and BusinessCraft rebuilt them for every row. Equality filters are now pushed into the projection, and the result is cached. Selecting a row in a list no longer reloads the whole list either.
  • Option captions in errors. TestField and FieldError show the caption of an option value, not its name.

Control add-ins

Control add-ins are the way to put your own HTML and JavaScript on a BC page. A controladdin object lists the scripts, style sheets, and images, declares the sizes, and defines the interface between AL and JavaScript:

controladdin "Tic Tac Toe"
{
    Scripts = 'Demo/TicTacToeDemo/js/TicTacToe.js';
    StartupScript = 'Demo/TicTacToeDemo/js/Startup.js';
    StyleSheets = 'Demo/TicTacToeDemo/css/TicTacToe.css';

    RequestedHeight = 420;
    MinimumHeight = 360;
    RequestedWidth = 360;
    MinimumWidth = 300;
    VerticalStretch = true;
    HorizontalStretch = true;

    event ControlReady();
    event CellClicked(CellNo: Integer);
    event NewGameRequested();

    procedure Render(State: JsonObject);
}

Events go from JavaScript to AL, procedures go from AL to JavaScript. On the page, a usercontrol hosts the add-in, and the events become triggers:

usercontrol(Board; "Tic Tac Toe")
{
    trigger ControlReady()
    begin
        BoardIsReady := true;
        StartNewGame();
    end;

    trigger CellClicked(CellNo: Integer)
    begin
        if TicTacToeGame.PlayHumanMove(CellNo) then
            UpdateScore();
        RenderBoard();
    end;
}

How BusinessCraft hosts them

Like BC, BusinessCraft puts every add-in into its own iframe. The steps:

  1. Publish. The compiler reads the controladdin and stores the script, style sheet, and image files from the app package.
  2. Serve. The web server delivers these files on an extra route, only to signed-in users.
  3. Host. The web client builds the iframe document: a <div id="controlAddIn">, the style sheets, the scripts, and the startup script last.
  4. Bridge. Before the scripts load, the iframe gets the API every add-in expects: Microsoft.Dynamics.NAV.InvokeExtensibilityMethod, GetEnvironment, and GetImageResource.

InvokeExtensibilityMethod('CellClicked', [5]) posts a message to the web client, which sends it to the service tier, which runs the AL trigger. CurrPage.Board.Render(State) goes the other way and calls the global JavaScript function Render in the iframe. A JsonObject arrives there as a real object, not as a string.

The size follows the properties: RequestedWidth and RequestedHeight without stretching, the full width with HorizontalStretch, and the minimums and maximums as limits.

Tic Tac Toe

The demo in the test app keeps all the game logic in AL. The JavaScript only draws the board and reports clicks. The opponent is a codeunit with a simple strategy: win if it can, block if it must, take the center, then the corners, then the edges. You will not win often, but you can get a draw. A field on the page decides whether Business Central Starts.

The game found two bugs:

  • Codeunit state. The board is a global array[9] of Text in the codeunit, and the codeunit is a global variable of the page. After PlayHumanMove, GetState saw an empty board. Every nested call into the same codeunit got its own copy of the globals. I had fixed the same bug in a different place a few days earlier, found by the test for xor (see below). Now it is fixed for page procedures too.
  • Pages without a source table. The demo page is a card with no SourceTable. BusinessCraft did not render the card body without a record, so the add-in was invisible, and actions like New Game were disabled.

Pages

Some page features that were missing until now:

  • Label controls. label(Name) on a page, with Caption, Visible, Importance, and CaptionClass.
  • CaptionClass on pages. A demo page builds the caption of a field and a label at runtime. Caption area 3 shows the text after the comma, so '3,My Caption' becomes My Caption.
  • Importance. Promoted, Standard, and Additional on fields. FastTabs with additional fields get Show more and Show less. The customer card uses it for Website and State.
  • addbefore in page extensions, for fields and for actions.
  • More anchors. addafter and addbefore also work on groups, repeaters, cue groups, and parts.
  • modify with properties. Page extensions can change Caption, Visible, Editable, and Importance of a field, and Caption and Enabled of an action.
  • CurrPage.Control.Visible := and Editable := in AL code.

Still missing: moveafter, movebefore, movefirst, and movelast.

Operators: xor, in, and case ranges

Three things from the language that I rarely use, but the base app does:

if (CustomerBlocked xor VendorBlocked) then
    ...
if Number in [1, 3, 5 .. 9] then
    ...
case Amount of
    0:
        ...
    1 .. 100:
        ...
end;

xor has the same precedence as or. in takes a list of values and ranges, and the case arms use the same ranges.

The xor test has a detail: AL evaluates both sides of xor. The test counts the calls in a global variable of the test codeunit and expects 2. It got 0. Not because of xor, but because every call to a procedure of the same codeunit got its own copy of the globals. That was the bug that came back with Tic Tac Toe.

First contact with the System Application

The goal is still the real Business Central base app. Before that comes the System Application, the app below it. On a branch, BusinessCraft can now parse and publish it. "Publish" is a big word here, because a lot is accepted without being implemented:

Area State
DotNet Variables and dotnet blocks are parsed. Calling a method on a DotNet variable throws a clear error. There is no .NET runtime, and there will not be one. Where needed, a Rust implementation will take the place of the assembly.
Opaque objects entitlement and enumextension are parsed and ignored. Page views too.
Validation References to tables, pages, and fields of other apps are kept by name instead of failing the publish.
Platform events The System Application subscribes to many service tier events BusinessCraft does not raise yet. The subscribers are accepted and stay silent.

Everything is listed in a to-do folder in the repository, so none of it gets forgotten. Once the System Application publishes on main and the first pages open, the next post will be about it.

The rest

  • Format. Building text with Format and thousand separators in German now matches BC.
  • CalcDate. Without a date, CalcDate uses Today, not WorkDate.
  • Hyperlink. Opens the URL in the browser, also when it runs inside Codeunit.Run.
  • StrSubstNo. Enum values are shown with their caption in the user's language.
  • MediaSet. Escape closes the fullscreen image viewer, not the page behind it.
  • Objects page. The test app has a page that lists all published objects, based on AllObjWithCaption.

Numbers

  • 339 commits, up from 327
  • About 107,600 lines of Rust, up from about 97,100
  • 70 platform tests in AL, up from 68
  • Still a Cursor Pro subscription for $20 a month

Next: Generic events and the System Application

The generic table and page events are still open: OnAfterInsertEvent, OnBeforeModifyEvent, OnAfterValidateEvent, and all their friends. They are next.

After that, the System Application moves from the branch to main. That means enumextension, the remaining platform events, and a lot of virtual tables.

I'll keep you updated. :)


BusinessCraft is not affiliated with or endorsed by Microsoft. "Microsoft", "Dynamics 365" and "Business Central" are trademarks of Microsoft Corporation.