All Around Microsoft Dynamics Business Central
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. :)
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;
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.
The change log turned out to be a good test. It found four bugs in BusinessCraft that had nothing to do with global triggers:
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.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.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.OnValidate. A Confirm inside a field OnValidate on a page now waits for the answer and then continues the trigger.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:
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.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.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.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.TestField and FieldError show the caption of an option value, not its name.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;
}
Like BC, BusinessCraft puts every add-in into its own iframe. The steps:
controladdin and stores the script, style sheet, and image files from the app package.<div id="controlAddIn">, the style sheets, the scripts, and the startup script last.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.
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:
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.SourceTable. BusinessCraft did not render the card body without a record, so the add-in was invisible, and actions like New Game were disabled.Some page features that were missing until now:
label(Name) on a page, with Caption, Visible, Importance, and CaptionClass.3 shows the text after the comma, so '3,My Caption' becomes My Caption.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.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.
xor, in, and case rangesThree 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.
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.
Format and thousand separators in German now matches BC.CalcDate uses Today, not WorkDate.Codeunit.Run.AllObjWithCaption.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.