Merge branch 'main' of https://github.com/demiliani/BCQuality into jobqueue

# Conflicts:
#	microsoft/knowledge/performance/job-queue-category-code-serializes-conflicting-jobs.bad.al
#	microsoft/knowledge/performance/job-queue-category-code-serializes-conflicting-jobs.good.al
#	microsoft/knowledge/performance/job-queue-category-code-serializes-conflicting-jobs.md
#	microsoft/knowledge/performance/job-queue-external-effects-must-be-idempotent.bad.al
#	microsoft/knowledge/performance/job-queue-external-effects-must-be-idempotent.good.al
#	microsoft/knowledge/performance/job-queue-external-effects-must-be-idempotent.md
#	microsoft/knowledge/performance/job-queue-handlers-must-not-require-ui.bad.al
#	microsoft/knowledge/performance/job-queue-handlers-must-not-require-ui.good.al
#	microsoft/knowledge/performance/job-queue-handlers-must-not-require-ui.md
#	microsoft/knowledge/performance/job-queue-handlers-must-propagate-failures.bad.al
#	microsoft/knowledge/performance/job-queue-handlers-must-propagate-failures.good.al
#	microsoft/knowledge/performance/job-queue-handlers-must-propagate-failures.md
#	microsoft/knowledge/performance/job-queue-on-hold-does-not-stop-running-work.bad.al
#	microsoft/knowledge/performance/job-queue-on-hold-does-not-stop-running-work.good.al
#	microsoft/knowledge/performance/job-queue-on-hold-does-not-stop-running-work.md
#	microsoft/knowledge/performance/store-scheduled-task-id-to-avoid-duplicate-tasks.bad.al
#	microsoft/knowledge/performance/store-scheduled-task-id-to-avoid-duplicate-tasks.good.al
#	microsoft/knowledge/performance/store-scheduled-task-id-to-avoid-duplicate-tasks.md
This commit is contained in:
demiliani 2026-09-08 17:02:26 +02:00
commit bb3398610e
228 changed files with 3304 additions and 432 deletions

View file

@ -1,7 +1,7 @@
---
bc-version: [all]
domain: appsource
keywords: [object-affix, prefix, suffix, as0011, appsourcecop, collision, tableextension]
keywords: [object-affix, prefix, suffix, as0011, appsourcecop, collision, tableextension, first-party, isv]
technologies: [al]
countries: [w1]
application-area: [all]
@ -15,6 +15,8 @@ An AppSource extension must prevent name collisions through its registered affix
AppSourceCop enforces this. The primary rule is AS0011 ("An affix is required"); the affixes are configured through `mandatoryAffixes` (and `mandatoryPrefix`) in `AppSourceCop.json`. Two placements matter and are easy to get half-right: an object you define carries the affix at **object-name** level, while a member you add to a **standard** object carries the affix on that **member's** name. Adding an affixed object is not enough — an unaffixed field bolted onto `Customer` still collides and still fails validation.
This rule scopes to Marketplace ISV extensions, which is what AppSourceCop validates. A first-party Microsoft in-box module (publisher `Microsoft`, an object range reserved for first-party use, and no `AppSourceCop.json`/`mandatoryAffixes` in the app) is not built or shipped as an Marketplace extension and is not subject to AS0011, so an unaffixed action or field it adds to a base-application page is not a collision risk to flag. Renaming an existing shipped first-party member to add an affix is itself a breaking change to that module's own history and is not required by this rule.
## Best Practice
Own objects use the registered affix (for example `ABC Loyalty Tier`) or, when targeting BC23 or later, a qualifying namespace. Every field or action added to a standard object remains individually affixed (for example `Loyalty Points ABC` on a `Customer` tableextension).

View file

@ -1,7 +1,7 @@
---
bc-version: [23..]
domain: appsource
keywords: [namespace, two-level, affix, prefix, suffix, as0011, tableextension, pageextension]
keywords: [namespace, two-level, affix, prefix, suffix, as0011, tableextension, pageextension, false-positive]
technologies: [al]
countries: [w1]
application-area: [all]
@ -13,14 +13,16 @@ application-area: [all]
Current AppSource naming guidance accepts a namespace with at least two levels, such as `Contoso.Rentals`, instead of a registered prefix or suffix on the names of objects the app owns. The namespace does not qualify members added to another publisher's object: fields, keys, controls, and actions introduced through table or page extensions still share the target object's flat member namespace and still need the registered affix.
The requirement comes from AppSourceCop rule AS0011, which only runs when the app enables AppSourceCop and configures a mandatory affix — normally an `AppSourceCop.json` next to the app manifest. An app that ships no such configuration is not subject to AS0011, and its extension members are not a compliance gap. This is the usual situation for first-party, in-box apps that ship as part of the product rather than through AppSource: their uniqueness comes from allocated object ID ranges and a controlled source tree, not from a registered affix. Confirm the extending app actually configures a mandatory affix before reporting an unaffixed extension member.
## Best Practice
Choose one collision strategy for owned objects: a registered affix or a globally meaningful namespace with at least two levels. Regardless of that choice, apply the registered affix to every member added to a base or third-party object. Keep the affix configured for AppSourceCop so member validation remains deterministic.
Choose one collision strategy for owned objects: a registered affix or a globally meaningful namespace with at least two levels. Regardless of that choice, apply the registered affix to every member added to a base or third-party object. Keep the affix configured for AppSourceCop so member validation remains deterministic. Do not raise a missing member affix against an app that does not enable AppSourceCop with a mandatory affix; there AS0011 never fires, and the app's namespace is not the reason — the absent configuration is.
See sample: `two-level-namespace-replaces-object-affix-not-extension-member-affix.good.al`.
## Anti Pattern
Using `namespace Contoso;` as though one level satisfied the AppSource alternative, or declaring `namespace Contoso.Rentals;` and then adding an unaffixed `Loyalty Points` field to `Customer`. The namespace distinguishes the extension's own objects; it cannot disambiguate members on Customer.
Using `namespace Contoso;` as though one level satisfied the AppSource alternative, or declaring `namespace Contoso.Rentals;` and then adding an unaffixed `Loyalty Points` field to `Customer` in an app that does configure a mandatory affix. The namespace distinguishes the extension's own objects; it cannot disambiguate members on Customer. The mirror-image mistake is reporting an unaffixed extension member in an app that enables no mandatory affix at all — AS0011 does not apply there, and the finding is a false positive.
See sample: `two-level-namespace-replaces-object-affix-not-extension-member-affix.bad.al`.

View file

@ -1,7 +1,7 @@
---
bc-version: [all]
domain: breaking-changes
keywords: [signature, public-procedure, parameter, return-value, overload, contract]
keywords: [signature, public-procedure, parameter, return-value, overload, contract, integration-event]
technologies: [al]
countries: [w1]
application-area: [all]
@ -13,6 +13,8 @@ application-area: [all]
A procedure that is reachable from outside its object — any procedure not marked `local` (and, for on-prem-scoped code, anything a dependent app can still bind to) — is a contract. Once another extension compiles against it, changing its shape breaks that extension at build time. Signature changes include adding, removing, or reordering parameters, changing a parameter or return type, and toggling a parameter between by-value and `var` (by-reference). The platform treats the procedure's identity as its full signature, so even a "compatible-looking" tweak is a new method to dependents. There is exactly one safe edit: naming a previously unnamed return value, which adds no caller obligation. LLMs routinely "improve" a public procedure in place by adding a parameter, not realizing every consumer must be recompiled.
This rule governs procedures that dependents *call*. An event publisher — a procedure carrying `[IntegrationEvent]` or `[BusinessEvent]`, conventionally declared `local` — is bound to, not called, and AL binds each subscriber parameter by name rather than by position. Adding a parameter to a shipped event therefore leaves every existing subscriber binding successfully, at any position in the list, so it is additive rather than breaking and must not be flagged under this rule. See `events/adding-a-parameter-to-an-event-is-not-a-breaking-change` for the full treatment, and `events/add-new-event-parameters-at-the-end` for when publisher access does make the addition breaking. Every other edit to a published event signature — removing or retyping a parameter, renaming one, or flipping one to or from `var` — still breaks subscribers, and `events/treat-local-and-internal-events-as-subscriber-contracts` owns that case together with the analyzer rules that enforce it: AS0025 for parameter names and types, AS0063 for removing `var`, and AS0077 for adding it. Adding `var IsHandled: Boolean` is a separate concern: it binds fine but changes the event's contract, and is covered by `events/do-not-add-ishandled-to-an-existing-event`.
## Best Practice
Treat a published signature as frozen. When new behavior needs more inputs, add a new procedure or overload alongside the original — for example a `CalculateDiscountWithRate(Amount; Rate)` next to the unchanged `CalculateDiscount(Amount)` — and let the old one delegate to the new one. Existing callers keep compiling; new callers opt into the richer entry point. Naming an unnamed return value is the one in-place change that is always safe.
@ -21,6 +23,6 @@ See sample: `do-not-change-published-procedure-signatures.good.al`.
## Anti Pattern
Editing the existing public procedure's parameter list — here, adding a `Rate` parameter to `CalculateDiscount` — so every dependent extension that called the old form fails to compile. Detection: a parameter added, removed, reordered, retyped, or flipped to/from `var`, or a changed return type, on any non-`local` procedure that already shipped. Add a new overload instead.
Editing the existing public procedure's parameter list — here, adding a `Rate` parameter to `CalculateDiscount` — so every dependent extension that called the old form fails to compile. Detection: a parameter added, removed, reordered, retyped, or flipped to/from `var`, or a changed return type, on any non-`local` procedure that already shipped. Add a new overload instead. Exclude event publishers whose only change is an added parameter: subscribers bind by parameter name, not position, so that edit is additive and reporting it here is a false positive.
See sample: `do-not-change-published-procedure-signatures.bad.al`.

View file

@ -0,0 +1,24 @@
---
bc-version: [all]
domain: data-modeling
keywords: [transfer, cleanup, deleteall, onvalidate, caller, stale-rows, false-positive]
technologies: [al]
countries: [w1]
application-area: [all]
---
# An insert-only transfer routine may rely on cleanup its caller already performed
## Description
A routine that copies rows from a template table into a target table — a `TransferX` procedure filling comment, dimension, or attribute lines from a standard-task or template record — is frequently written as filter-and-insert with no `DeleteAll` of its own. That is not automatically a stale-row or duplicate-primary-key defect. In the common AL shape, the field's `OnValidate` trigger first calls a sibling cleanup procedure that clears the same filtered range, then calls the transfer. By the time `Insert` runs, the target range is guaranteed empty, so the transfer has nothing to clean up and adding a second `DeleteAll` inside it would be redundant.
Deciding whether a missing cleanup is real therefore requires reading the caller, not just the routine in the diff. The relevant question is whether every path that reaches the transfer clears the target range first — not whether the transfer clears it itself.
## Best Practice
Before reporting a transfer or copy routine for missing cleanup, trace its call sites. If the callers in scope invoke a cleanup procedure that clears the same filtered range immediately beforehand — typically in the same `OnValidate` trigger or the same routine — the insert-only transfer is correct and must not be flagged for stale rows, duplicate keys, or a missing `DeleteAll`. Raise the finding only when a reachable call path inserts into a range that was not cleared, or when the cleanup filters a different range than the insert writes to.
## Anti Pattern
Reporting an insert-only transfer as a stale-row or duplicate-key risk on the strength of the routine body alone, when the trigger that calls it already ran the cleanup. The mirror-image mistake is waving through a transfer whose caller clears a *different* filter range than the one the transfer inserts into, or one reachable from a path with no cleanup at all — those are genuine defects.

View file

@ -0,0 +1,48 @@
table 50100 "Order Header"
{
fields
{
field(1; "Entry No."; Integer)
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
// No OnDelete. Deleting a header silently orphans every Order Line that
// belonged to it. Nothing errors, and no page shows the stranded rows.
}
table 50101 "Order Line"
{
fields
{
field(1; "Line No."; Integer)
{
DataClassification = CustomerContent;
}
field(2; "Header Entry No."; Integer)
{
DataClassification = CustomerContent;
// Reads like referential integrity. It is lookup and input validation
// only: it propagates a RENAME of the parent key, and cascades nothing
// on DELETE.
TableRelation = "Order Header"."Entry No.";
}
}
keys
{
key(PK; "Line No.")
{
Clustered = true;
}
}
}

View file

@ -0,0 +1,55 @@
table 50100 "Order Header"
{
// The owning table needs delete rights on what it owns. Granting D only on the
// header is a common miss and makes OnDelete fail for a non-SUPER user.
Permissions = tabledata "Order Line" = rd;
fields
{
field(1; "Entry No."; Integer)
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
trigger OnDelete()
var
OrderLine: Record "Order Line";
begin
OrderLine.SetRange("Header Entry No.", "Entry No.");
// Pass false only when Order Line has no OnDelete of its own.
OrderLine.DeleteAll(true);
end;
}
table 50101 "Order Line"
{
fields
{
field(1; "Line No."; Integer)
{
DataClassification = CustomerContent;
}
field(2; "Header Entry No."; Integer)
{
DataClassification = CustomerContent;
TableRelation = "Order Header"."Entry No.";
}
}
keys
{
key(PK; "Line No.")
{
Clustered = true;
}
}
}

View file

@ -0,0 +1,36 @@
---
bc-version: [all]
domain: data-modeling
keywords: [ondelete, cascade, table-relation, orphan-records, header-line, dependent-records, referential-integrity]
technologies: [al]
countries: [w1]
application-area: [all]
---
# A table that owns dependent records must delete them in `OnDelete`
## Description
`TableRelation` looks like referential integrity but only performs lookup and input validation. AL has **no cascading delete**: deleting a parent record leaves every dependent row untouched, and no error is raised.
What makes this specifically missable is an asymmetry. The platform *does* keep references correct on **rename** — renaming a record updates it in all other locations that declare a `TableRelation` to it, with no code. Delete has no equivalent. Same relation, same metadata, opposite behaviour. A developer who correctly learns that `TableRelation` "keeps references consistent" from the rename case, and generalises it to delete, ships orphans.
Orphaned rows are usually invisible, because a dependent table rarely has a page of its own. They inflate the table, break later reconciliation, and are re-encountered by duplicate checks when the parent key is reused.
This applies to internal, staging and `SystemMetadata` tables too. A table having no delete action in the UI today is not protection: a permission set that grants `D` on the table is evidence that deletion is anticipated.
See also `validate-table-relation-false-suppresses-rename-propagation.md` for the two preconditions on the rename half of this asymmetry.
## Best Practice
The owning table implements `OnDelete` and deletes its dependents there, filtered on the foreign key. Declare `Permissions = tabledata <dependent> = rd` on the owning table — granting delete rights only on the parent is a common miss that makes the trigger fail for a non-`SUPER` user. This mirrors the base application, where every header table deletes its own lines.
See sample: `owning-table-must-delete-dependents-in-ondelete.good.al`.
## Anti Pattern
A parent table with dependent rows and no `OnDelete` trigger, where the dependent's foreign-key field declares a `TableRelation` back to the parent. The relation reads as if it guarantees integrity; it does not.
Detection signal: a table declares `TableRelation` to table X, and table X has no `OnDelete` trigger. Whether a delete path currently exists in the UI is irrelevant to the finding.
See sample: `owning-table-must-delete-dependents-in-ondelete.bad.al`.

View file

@ -0,0 +1,55 @@
table 50123 "Transfer Source Bad"
{
fields
{
field(1; "Entry No."; Integer)
{
DataClassification = CustomerContent;
}
field(2; "Reference"; Code[20])
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}
table 50124 "Transfer Target Bad"
{
fields
{
field(1; "Entry No."; Integer)
{
DataClassification = CustomerContent;
}
field(2; "Reference"; Integer)
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}
codeunit 50492 "TransferFields Bad"
{
procedure CopyData(Source: Record "Transfer Source Bad"; var Target: Record "Transfer Target Bad")
begin
Target.TransferFields(Source, true, true);
end;
}

View file

@ -0,0 +1,59 @@
table 50121 "Transfer Source"
{
fields
{
field(1; "Entry No."; Integer)
{
DataClassification = CustomerContent;
}
field(2; "Reference"; Code[20])
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}
table 50122 "Transfer Target"
{
fields
{
field(1; "Entry No."; Integer)
{
DataClassification = CustomerContent;
}
field(2; "Reference"; Integer)
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}
codeunit 50491 "TransferFields Good"
{
procedure CopyData(Source: Record "Transfer Source"; var Target: Record "Transfer Target")
var
ConvertedReference: Integer;
begin
Target."Entry No." := Source."Entry No.";
Evaluate(ConvertedReference, Source."Reference");
Target.Validate("Reference", ConvertedReference);
end;
}

View file

@ -0,0 +1,26 @@
---
bc-version: [16..]
domain: data-modeling
keywords: [transferfields, skipfieldsnotmatchingtype, type-mismatch, field-mapping, data-transfer]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Do not use SkipFieldsNotMatchingType to hide required TransferFields mismatches
## Description
`Record.TransferFields` copies values between fields with matching field numbers. Without `SkipFieldsNotMatchingType` (or with it `false`), a type mismatch between two fields in the same extension raises a runtime error at the point of transfer. Setting `SkipFieldsNotMatchingType` to `true` removes that error: the field is skipped instead, and the rest of the transfer completes normally. The caller gets no indication that a field was not copied.
## Best Practice
Use `TransferFields(Source)` only when every field the destination requires, including primary key fields, is guaranteed to share a matching field number and type with the source; this form defaults `InitPrimaryKeyFields` to `true`. Fields with no matching field number, and fields whose types differ across extensions, are skipped regardless of `SkipFieldsNotMatchingType` — that parameter only governs same-extension type mismatches. If the destination depends on a field that falls into either case, map and validate it explicitly in code rather than relying on `TransferFields` to catch the gap. Use `SkipFieldsNotMatchingType = true` only when skipping same-extension type mismatches is an intentional, documented part of the transfer contract.
See sample: `transferfields-skip-type-mismatch-can-drop-data.good.al`.
## Anti Pattern
Using `TransferFields(Source, InitPrimaryKeyFields, true)` as a generic way to make two evolving table schemas transfer without errors, when the destination depends on every required source field being copied. A type change on either table can turn a previously transferred field into a silently skipped one without making the transfer itself fail.
See sample: `transferfields-skip-type-mismatch-can-drop-data.bad.al`.

View file

@ -0,0 +1,35 @@
table 50121 "Document Link"
{
fields
{
field(1; "Entry No."; Integer)
{
DataClassification = CustomerContent;
}
field(2; "Document No."; Code[20])
{
DataClassification = CustomerContent;
TableRelation = "Source Document"."No.";
// Added to silence a validation error while the row is staged, before
// the Source Document exists. The relation is still declared, so this
// reads as harmless — but it also switches OFF rename propagation.
// Renaming a Source Document now leaves this field on the old key,
// with no error, and nothing else maintains it.
ValidateTableRelation = false;
}
// Composite value: no TableRelation is possible, and no OnRename on the
// owning table maintains it either. Rots the same way, for the other reason.
field(3; "Source Key"; Code[50])
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}

View file

@ -0,0 +1,70 @@
table 50120 "Source Document"
{
fields
{
field(1; "No."; Code[20])
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "No.")
{
Clustered = true;
}
}
// "Source Key" below cannot declare a TableRelation, so the platform cannot
// repoint it. The owning table carries the relationship by hand.
trigger OnRename()
var
DocumentLink: Record "Document Link";
begin
// In OnRename, xRec holds the PREVIOUS primary key while Rec holds the new
// one — the one trigger where that is true regardless of what drove the rename.
DocumentLink.SetRange("Source Key", MakeSourceKey(xRec."No."));
if DocumentLink.FindSet(true) then
repeat
DocumentLink."Source Key" := MakeSourceKey(Rec."No.");
DocumentLink.Modify(true);
until DocumentLink.Next() = 0;
end;
local procedure MakeSourceKey(DocumentNo: Code[20]): Code[50]
begin
exit(StrSubstNo('DOC|%1', DocumentNo));
end;
}
table 50121 "Document Link"
{
fields
{
field(1; "Entry No."; Integer)
{
DataClassification = CustomerContent;
}
// Default ValidateTableRelation: the platform repoints this on rename.
field(2; "Document No."; Code[20])
{
DataClassification = CustomerContent;
TableRelation = "Source Document"."No.";
}
// Composite value — no TableRelation can express it, so the parent's
// OnRename above maintains it explicitly.
field(3; "Source Key"; Code[50])
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}

View file

@ -0,0 +1,38 @@
---
bc-version: [all]
domain: data-modeling
keywords: [validatetablerelation, table-relation, rename, onrename, propagation, dangling-reference, soft-relation]
technologies: [al]
countries: [w1]
application-area: [all]
---
# `ValidateTableRelation = false` suppresses rename propagation, not just input validation
## Description
Renaming a record updates it in all other locations that reference it through a `TableRelation`, with no code. That guarantee has **two** preconditions, and a field failing either one is silently left holding a key that no longer exists.
First, a `TableRelation` must exist. A field whose value is constructed or computed — a composite key, or a value derived from several fields of the target — cannot declare one, so nothing propagates. The field is still a foreign key in intent, but the platform treats it as an opaque value.
Second, and far less obvious: the relation must not carry `ValidateTableRelation = false`. The property name implies it only governs *input validation*, so it looks safe to disable on a field populated by code that already knows the target is valid. It is not. **Disabling it also switches off rename propagation.** The relation still documents intent and still drives lookups, but it no longer keeps the stored value correct.
Both failures are quiet: no error at rename time, and in the first case no input validation either, so a wrong value is never rejected on write.
This is verified behaviour, not inference. A parent renamed once against a child holding three fields — a normal relation, the same relation with `ValidateTableRelation = false`, and a field with no relation — updates only the first.
See also `owning-table-must-delete-dependents-in-ondelete.md` for the delete half of this asymmetry, and `xrec-is-a-before-image-only-in-some-triggers.md` for why `OnRename` is the one trigger where a hand-written fix-up is reliable.
## Best Practice
Leave `ValidateTableRelation` at its default wherever the stored value must stay correct across a rename. When it must be disabled, or when the relationship cannot be expressed as a `TableRelation` at all, the table owning the referenced key carries an explicit `OnRename` that repoints the dependents itself.
See sample: `validate-table-relation-false-suppresses-rename-propagation.good.al`.
## Anti Pattern
`ValidateTableRelation = false` added to silence a validation error, on a field expected to keep tracking its target. The field stops being maintained on rename, and the defect surfaces much later as a reference to a key that no longer exists.
Detection signal: any `ValidateTableRelation = false` on a field that also declares a `TableRelation`. Ask what repoints the value when the target is renamed; if the answer is "the platform", the finding stands.
See sample: `validate-table-relation-false-suppresses-rename-propagation.bad.al`.

View file

@ -0,0 +1,36 @@
table 50130 "Service Request"
{
fields
{
field(1; "No."; Code[20])
{
DataClassification = CustomerContent;
}
field(2; Status; Enum "Service Request Status")
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "No.")
{
Clustered = true;
}
}
trigger OnModify()
begin
// Dead branch under any code-driven Modify: from code xRec mirrors Rec, so
// the two Status values are always equal and LogStatusChange never runs.
// Editing the field on a page DOES populate xRec, so this passes manual
// testing and then silently does nothing in a job queue or API call.
if Status <> xRec.Status then
LogStatusChange(xRec.Status, Status);
end;
local procedure LogStatusChange(FromStatus: Enum "Service Request Status"; ToStatus: Enum "Service Request Status")
begin
end;
}

View file

@ -0,0 +1,58 @@
table 50130 "Service Request"
{
fields
{
field(1; "No."; Code[20])
{
DataClassification = CustomerContent;
}
field(2; Status; Enum "Service Request Status")
{
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "No.")
{
Clustered = true;
}
}
// OnModify: xRec mirrors Rec when the write came from code, so it cannot be
// used as a before-image. Re-read the stored row instead — this behaves the
// same whether a page, a job queue or an API drove the write.
trigger OnModify()
var
Previous: Record "Service Request";
begin
if Previous.Get("No.") and (Previous.Status <> Status) then
LogStatusChange(Previous.Status, Status);
end;
// OnRename: xRec IS the before-image of the primary key here, whatever drove
// the rename. This is the one trigger where the idiom is reliable.
trigger OnRename()
begin
RepointDependents(xRec."No.", "No.");
end;
// OnDelete: xRec reflects the record being removed.
trigger OnDelete()
begin
ArchiveRequest(xRec."No.");
end;
local procedure LogStatusChange(FromStatus: Enum "Service Request Status"; ToStatus: Enum "Service Request Status")
begin
end;
local procedure RepointDependents(OldNo: Code[20]; NewNo: Code[20])
begin
end;
local procedure ArchiveRequest(RequestNo: Code[20])
begin
end;
}

View file

@ -0,0 +1,36 @@
---
bc-version: [all]
domain: data-modeling
keywords: [xrec, before-image, onmodify, onrename, oninsert, ondelete, table-trigger, page-driven]
technologies: [al]
countries: [w1]
application-area: [all]
---
# `xRec` is a before-image in `OnRename` and `OnDelete`, but mirrors `Rec` in `OnInsert` and `OnModify` from code
## Description
`xRec` is widely believed to be "the previous record" inside every table trigger, and — in reaction to that — is often dismissed with the folk rule *"`xRec` only works from a page, never from code"*. Both are wrong, and the second is wrong in the place it matters most.
The behaviour is per-trigger. In `OnRename` and `OnDelete`, `xRec` is a genuine before-image regardless of what drove the write. In `OnInsert` and `OnModify`, a **code-driven** write leaves `xRec` mirroring `Rec` — there is no before-image at all — while a **page-driven** write does supply one.
That combination produces a defect that is unusually hard to catch. A comparison such as `if Rec.Status <> xRec.Status then` inside `OnModify` works when a tester clicks through a page, and silently never fires when the same code path runs from a job queue, a batch routine, or an API call. It fails as a no-op, not as an error.
The `OnRename` case is the useful half: because `xRec` there holds the previous primary key even from code, it is the one place a hand-written key fix-up is reliable. Note that in `OnRename` only the key differs between `Rec` and `xRec` — non-key field values are identical on both sides.
See also `validate-table-relation-false-suppresses-rename-propagation.md`, which describes when such a hand-written `OnRename` fix-up is required.
## Best Practice
Use `xRec` for the previous key in `OnRename`, and for the record being removed in `OnDelete`. In `OnModify`, obtain the before-image by re-reading the stored row rather than trusting `xRec`, so the logic behaves identically whether a page, a job queue or an API drove the write.
See sample: `xrec-is-a-before-image-only-in-some-triggers.good.al`.
## Anti Pattern
Comparing `Rec` against `xRec` inside `OnModify` (or `OnInsert`) to detect a change. From code the two are equal, so the branch is dead and whatever it guards never happens.
Detection signal: any read of `xRec` inside `OnModify` or `OnInsert`. Treat "but it works when I test it on the page" as confirmation of the defect rather than a refutation.
See sample: `xrec-is-a-before-image-only-in-some-triggers.bad.al`.

View file

@ -1,7 +1,7 @@
---
bc-version: [all]
domain: error-handling
keywords: [fielderror, testfield, field-validation, onvalidate, error-message, mandatory-field, record-context]
keywords: [fielderror, testfield, field-validation, onvalidate, error-message, mandatory-field, record-context, onaction, enabled-property]
technologies: [al]
countries: [w1]
application-area: [all]
@ -14,6 +14,8 @@ application-area: [all]
## Best Practice
Use `TestField` when the condition is a simple presence-or-equality check on a single field — mandatory-field gates and prerequisite checks at the top of a procedure read clearly and self-document intent. Use `FieldError` inside an `OnValidate` trigger or a validation procedure where surrounding business logic has already determined the value is invalid and you want a specific, custom message. Rely on the built-in field-and-record context both methods add rather than re-stating the field name in the text.
A page action's `OnAction` trigger is a different case: a page action is only invocable through its own UI control, so when the action's `Enabled` property is already bound to the same condition the trigger would otherwise `TestField`, the control cannot be clicked while the field is blank and the field can never reach the trigger empty. Adding a `TestField` there is redundant defensive code, not a missing check — flag it only when the trigger can run through a path `Enabled` does not cover (a shared procedure, an API, or a condition broader than what gates the action).
See sample: `fielderror-vs-testfield.good.al`.
## Anti Pattern

View file

@ -3,7 +3,7 @@
codeunit 50116 "Payment Processor Bad"
{
[IntegrationEvent(false, false)]
procedure OnBeforeSubmitPayment(var PaymentAmount: Decimal; var Cancel: Boolean)
local procedure OnBeforeSubmitPayment(var PaymentAmount: Decimal; var Cancel: Boolean)
begin
end;

View file

@ -3,7 +3,7 @@
codeunit 50114 "Payment Processor"
{
[IntegrationEvent(false, false)]
procedure OnBeforeSubmitPayment(var PaymentAmount: Decimal; var Cancel: Boolean)
local procedure OnBeforeSubmitPayment(var PaymentAmount: Decimal; var Cancel: Boolean)
begin
end;

View file

@ -0,0 +1,43 @@
// Demonstration only. Shows the wrong pattern: the publisher carries no access modifier, so it is
// public - which never was what lets extensions subscribe.
codeunit 50100 "Loyalty Points Mgt Bad"
{
procedure AwardPoints(CustomerNo: Code[20]; SalesAmount: Decimal)
var
Points: Decimal;
IsHandled: Boolean;
begin
Points := SalesAmount / 10;
IsHandled := false;
OnBeforeAwardPoints(CustomerNo, Points, IsHandled);
if IsHandled then
exit;
// ... insert the loyalty entry ...
end;
// BAD: no access modifier, so this publisher is public. Public access does not enable
// subscription - it enables raising. Narrowing it to internal after release breaks callers,
// so the widening cannot be walked back cheaply.
[IntegrationEvent(false, false)]
procedure OnBeforeAwardPoints(CustomerNo: Code[20]; var Points: Decimal; var IsHandled: Boolean)
begin
end;
}
codeunit 50101 "Loyalty Points Caller Bad"
{
procedure FirePublisherDirectly(CustomerNo: Code[20])
var
LoyaltyPointsMgt: Codeunit "Loyalty Points Mgt Bad";
Points: Decimal;
IsHandled: Boolean;
begin
// Compiles only because the publisher is public. Every subscriber runs although no points
// were ever awarded, on a Points value nobody computed, and the IsHandled answer the
// subscribers write is read by no one.
LoyaltyPointsMgt.OnBeforeAwardPoints(CustomerNo, Points, IsHandled);
end;
}

View file

@ -0,0 +1,59 @@
// Demonstration only. Shows the correct pattern: a public facade codeunit whose event publishers
// are internal, so only the implementation codeunit decides when they fire.
codeunit 50100 "Loyalty Points Mgt Good"
{
procedure AwardPoints(CustomerNo: Code[20]; SalesAmount: Decimal)
var
LoyaltyPointsImpl: Codeunit "Loyalty Points Impl Good";
begin
LoyaltyPointsImpl.AwardPoints(CustomerNo, SalesAmount);
end;
// internal, not public: the implementation codeunit raises this and nobody else. Subscribers
// bind through Codeunit::"Loyalty Points Mgt Good", which is public by default - that object
// access is all a subscriber in another extension needs.
[IntegrationEvent(false, false)]
internal procedure OnBeforeAwardPoints(CustomerNo: Code[20]; var Points: Decimal; var IsHandled: Boolean)
begin
end;
[IntegrationEvent(false, false)]
internal procedure OnAfterAwardPoints(CustomerNo: Code[20]; Points: Decimal)
begin
end;
}
codeunit 50101 "Loyalty Points Impl Good"
{
Access = Internal;
procedure AwardPoints(CustomerNo: Code[20]; SalesAmount: Decimal)
var
LoyaltyPointsMgt: Codeunit "Loyalty Points Mgt Good";
Points: Decimal;
IsHandled: Boolean;
begin
Points := SalesAmount / 10;
IsHandled := false;
LoyaltyPointsMgt.OnBeforeAwardPoints(CustomerNo, Points, IsHandled);
if IsHandled then
exit;
// ... insert the loyalty entry ...
LoyaltyPointsMgt.OnAfterAwardPoints(CustomerNo, Points);
end;
}
codeunit 50102 "Loyalty Points Sub Good"
{
// The shape a subscriber in a dependent extension takes: it names the public object, and is
// indifferent to the publisher being internal.
[EventSubscriber(ObjectType::Codeunit, Codeunit::"Loyalty Points Mgt Good", 'OnAfterAwardPoints', '', false, false)]
local procedure LogAwardedPointsOnAfterAwardPoints(CustomerNo: Code[20]; Points: Decimal)
begin
// ... write telemetry ...
end;
}

View file

@ -0,0 +1,42 @@
---
bc-version: [all]
domain: events
keywords: [event-publisher, access-modifier, local, internal, integration-event, business-event, subscriber, breaking-change]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Declare event publishers local or internal
> Contributions welcome — open a PR to refine or extend this article.
## Description
The access modifier on an `[IntegrationEvent]` or `[BusinessEvent]` publisher controls who may *raise* the procedure, not who may *subscribe* to it. A subscriber in a dependent extension binds through the object named in its `[EventSubscriber(...)]` attribute, so the only accessibility a foreign subscriber needs is on the *object* — a codeunit left at its default public access. The publisher procedure itself can and should stay `local` or `internal`. Publishing an event is an invitation to subscribe, not an invitation to call: an omitted access modifier makes the publisher public, which hands every dependent extension the ability to fire the event on its own. The signature-compatibility consequences of a shipped publisher are covered separately by `treat-local-and-internal-events-as-subscriber-contracts`.
## Applies to
Ordinary `[IntegrationEvent]` and `[BusinessEvent]` publishers. `[InternalEvent]` has its own module-only visibility semantics, and external business events are out of scope.
## Best Practice
Give an event publisher the narrowest access modifier that still lets the code owning the operation raise it:
- `local` when only the declaring object raises the event. This is the common case and the default choice.
- `internal` when another object in the same app raises it — typically an internal implementation codeunit raising an event declared on a public facade codeunit. The facade object stays public so dependent extensions can name it in `[EventSubscriber(...)]`; the publisher stays `internal` so only the implementation decides when the event fires.
- `public` only when a *different app* must raise the event — a hub or event-bus codeunit in a foundation app that sibling apps signal through, where `internal` cannot reach across the app boundary. This is a deliberate caller contract, not a concession to subscribers, and it is maintained like any other public API.
Subscribers are unaffected by any of these choices. A non-public publisher also keeps the freedom to add a parameter later, which a public publisher gives up — see `add-new-event-parameters-at-the-end`.
See sample: `declare-event-publishers-local-or-internal.good.al`.
## Anti Pattern
An event publisher declared with no access modifier — or widened to public — in the belief that dependent extensions need that to subscribe. They do not. Two consequences follow. Any dependent extension can now call the publisher directly, firing every subscriber outside the owning routine's control flow, on state the publisher never prepared and with an `IsHandled` answer nobody reads. And because the publisher is a public procedure, it is a caller contract: narrowing it back to `local` or `internal` after release is itself a breaking change, so the mistake is not cheaply reversible.
Detection: an `[IntegrationEvent]` or `[BusinessEvent]` publisher that is public although every raiser is in its own app — typically raised only from its declaring object. A publisher deliberately made public so another app can raise it is not this anti-pattern; do not report it. When the surrounding repository or API context does not reveal whether an external raiser is intended, treat the public modifier as intentional rather than reporting it.
The mirror-image anti-pattern belongs to the reviewer, human or agent: recommending that a publisher be made public so extensions can subscribe, or reporting a `local`/`internal` publisher as unreachable dead code. Both readings mistake raising for subscribing. Neither should be raised as a finding.
See sample: `declare-event-publishers-local-or-internal.bad.al`.

View file

@ -0,0 +1,72 @@
// Demonstration-only AL. Not compiled by CI; illustrates the article.
// Anti-pattern 1: the context is kept in single-instance state.
codeunit 50545 "Process State Bad Sample"
{
SingleInstance = true;
var
ProcessRunning: Boolean;
procedure SetProcessRunning(NewProcessRunning: Boolean)
begin
ProcessRunning := NewProcessRunning;
end;
procedure IsProcessRunning(): Boolean
begin
exit(ProcessRunning);
end;
}
codeunit 50546 "Process Driver Bad Sample"
{
procedure Run(DocumentNo: Code[20])
var
ProcessState: Codeunit "Process State Bad Sample";
begin
ProcessState.SetProcessRunning(true);
RunSharedCode(DocumentNo);
// An error above never reaches this line. The database writes roll
// back, the single-instance variable does not: ProcessRunning stays
// true until the company is closed, so every later run in this session
// is treated as part of the process.
ProcessState.SetProcessRunning(false);
end;
local procedure RunSharedCode(DocumentNo: Code[20])
begin
end;
}
// Anti-pattern 2: the context stays private. Flag and driver look like the
// good sample, but the query is internal, so only the owning app can ever ask.
codeunit 50547 "Process Ctx Bad Sample"
{
internal procedure IsProcessRunning(): Boolean
var
IsRunning: Boolean;
begin
OnCheckProcessRunning(IsRunning);
exit(IsRunning);
end;
[InternalEvent(false)]
local procedure OnCheckProcessRunning(var IsRunning: Boolean)
begin
end;
}
reportextension 50548 "Shared Report Ext Bad Sample" extends "Standard Sales - Invoice"
{
trigger OnPreReport()
begin
// No callable query exists, so the extension infers the context from
// something it hopes only that process does - here, running without a
// UI. The guess is wrong for every other background run, and breaks
// silently the first time the owning app changes how it works.
if GuiAllowed() then
exit;
// ... behaviour that was meant to apply only inside that process ...
end;
}

View file

@ -0,0 +1,70 @@
// Demonstration-only AL. Not compiled by CI; illustrates the article.
// The published context API - the entire public surface of the pattern.
// Any dependent extension may call IsProcessRunning; nothing else is exposed.
codeunit 50540 "Process Context Good Sample"
{
procedure IsProcessRunning(): Boolean
var
IsRunning: Boolean;
begin
OnCheckProcessRunning(IsRunning);
exit(IsRunning);
end;
// InternalEvent: only this app can subscribe, which is all the pattern
// needs. local: only this codeunit can raise it.
[InternalEvent(false)]
local procedure OnCheckProcessRunning(var IsRunning: Boolean)
begin
end;
}
// The flag - implementation, not API, hence Access = Internal. It stores
// nothing between runs: being bound is the state.
codeunit 50541 "Process Flag Good Sample"
{
Access = Internal;
EventSubscriberInstance = Manual;
[EventSubscriber(ObjectType::Codeunit, Codeunit::"Process Context Good Sample", 'OnCheckProcessRunning', '', false, false)]
local procedure SetProcessRunning(var IsRunning: Boolean)
begin
IsRunning := true;
end;
}
// The app that drives the process claims the context for exactly its own run.
codeunit 50542 "Process Driver Good Sample"
{
procedure Run(DocumentNo: Code[20])
var
ProcessFlag: Codeunit "Process Flag Good Sample";
begin
// A fresh instance, bound for exactly this call. If the shared code
// errors, the stack unwinds and takes the binding with it - nothing to reset.
BindSubscription(ProcessFlag);
RunSharedCode(DocumentNo);
end;
local procedure RunSharedCode(DocumentNo: Code[20])
begin
// A base application report, a posting routine, or any other object
// that extensions hook into - including a customer's own replacement.
end;
}
// An extension hooked into that shared code can now ask the question directly
// instead of guessing which process is driving the run. The hook happens to be
// a report extension here; a subscriber on any other shared object is the same.
reportextension 50543 "Shared Report Ext Good Sample" extends "Standard Sales - Invoice"
{
trigger OnPreReport()
var
ProcessContext: Codeunit "Process Context Good Sample";
begin
if not ProcessContext.IsProcessRunning() then
exit;
// ... behaviour that applies only inside that process ...
end;
}

View file

@ -0,0 +1,40 @@
---
bc-version: [all]
domain: events
keywords: [bindsubscription, manual-binding, eventsubscriberinstance, internalevent, singleinstance, process-context, running-flag, scoped-state, rollback]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Expose process context through a manually bound flag, not a single-instance boolean
> Contributions welcome — open a PR to refine or extend this article.
## Description
When an extension drives a process over shared code — a base application report, a posting routine — other extensions hooked into that code cannot tell whether a run belongs to that process: AL keeps no ambient "current process", so the driving app has to publish the context itself. The reflex answer, a `SingleInstance` codeunit holding a boolean set at the start of the run and cleared at the end, is unsafe: single-instance variables are not part of the database transaction, so a failed run rolls back the writes but not the flag, which stays `true` until the company is closed and marks every later run in the session as part of the process. A manual event binding carries the same signal safely, because the platform ties its lifetime to a variable's scope instead of to cleanup code that has to run.
## Best Practice
Publish the context as a query and let the binding itself be the state. One procedure is public; everything behind it is internal:
- A public context codeunit exposes `IsProcessRunning(): Boolean`, which raises an `[InternalEvent]` publisher taking a `var Boolean` and returns what comes back — the entire public surface. The publisher is internal because only the owning app subscribes, `local` because only this codeunit raises it.
- A second codeunit, `Access = Internal` with `EventSubscriberInstance = Manual`, subscribes to that event and sets the boolean to `true`. Internal keeps it out of the API and stops other apps binding it to forge the context; it stores nothing between runs — being bound *is* the state.
- The driving process calls `BindSubscription` on a variable whose scope is exactly the span it wants to claim: a local in the procedure that drives the run, or a global on an object that lives exactly as long as the run. While that variable is alive the query answers `true`; when it leaves scope — normally, or because an error unwound the call stack — the platform removes the binding and the query answers `false` again.
Bind a fresh instance per run rather than reusing one: the platform refuses to bind the same instance twice but accepts several instances of the same codeunit, so nesting and re-entrancy need no counter. The binding is session-scoped, so work the process starts in another session — a background session, a page background task, a job queue entry — cannot see it; pass the context explicitly there.
See sample: `expose-process-context-via-manually-bound-flag.good.al`.
## Anti Pattern
Two shapes.
First, the single-instance boolean — the failure described above. Detection: a `SingleInstance = true` codeunit with a boolean set before a process and cleared after it, read by other code to decide whether that process is running.
Second, the context kept private: the driving app arranges its own marker — typically a manually bound subscriber on an event added for its benefit alone — and offers no query, or only an `internal` one. Other extensions are left inferring the context from side effects, request-page values, or record state, which breaks silently the first time the process changes. Detection: a manual binding used purely as an internal run marker, with no public query procedure over it.
The mirror-image anti-pattern belongs to the reviewer: flagging the `BindSubscription` here as a leaked binding because no `UnbindSubscription` follows it. Scope release is the mechanism, not an omission — see `microsoft/knowledge/events/choose-static-vs-manual-subscribers-deliberately.md`, whose leak case is an instance parked on a `SingleInstance` global that never leaves scope.
See sample: `expose-process-context-via-manually-bound-flag.bad.al`.

View file

@ -1,31 +0,0 @@
// Demonstration-only AL. Not compiled by CI; illustrates the article.
codeunit 50241 "IsHandled Init Bad Sample"
{
procedure ApplyDiscounts(var SalesHeader: Record "Sales Header")
var
DiscountPct: Decimal;
IsHandled: Boolean;
begin
// IsHandled is never initialized before the first raise, so flow depends
// on the variable's default rather than an explicit, documented intent.
OnBeforeApplyHeaderDiscount(SalesHeader, DiscountPct, IsHandled);
if not IsHandled then
DiscountPct := 5;
// Bug: IsHandled is not reset. If the first subscriber set it true, the
// payment-discount default below is silently skipped too.
OnBeforeApplyPaymentDiscount(SalesHeader, DiscountPct, IsHandled);
if not IsHandled then
DiscountPct += 2;
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyHeaderDiscount(var SalesHeader: Record "Sales Header"; var DiscountPct: Decimal; var IsHandled: Boolean)
begin
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyPaymentDiscount(var SalesHeader: Record "Sales Header"; var DiscountPct: Decimal; var IsHandled: Boolean)
begin
end;
}

View file

@ -1,31 +0,0 @@
// Demonstration-only AL. Not compiled by CI; illustrates the article.
codeunit 50240 "IsHandled Init Good Sample"
{
procedure ApplyDiscounts(var SalesHeader: Record "Sales Header")
var
DiscountPct: Decimal;
IsHandled: Boolean;
begin
IsHandled := false;
OnBeforeApplyHeaderDiscount(SalesHeader, DiscountPct, IsHandled);
if not IsHandled then
DiscountPct := 5;
// Reset before reusing the same variable for the next event so a
// subscriber that handled the first raise can't suppress this one.
IsHandled := false;
OnBeforeApplyPaymentDiscount(SalesHeader, DiscountPct, IsHandled);
if not IsHandled then
DiscountPct += 2;
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyHeaderDiscount(var SalesHeader: Record "Sales Header"; var DiscountPct: Decimal; var IsHandled: Boolean)
begin
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyPaymentDiscount(var SalesHeader: Record "Sales Header"; var DiscountPct: Decimal; var IsHandled: Boolean)
begin
end;
}

View file

@ -1,26 +0,0 @@
---
bc-version: [all]
domain: events
keywords: [ishandled, initialization, deterministic, onbefore, reset, integration-event, control-flow]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Initialize IsHandled to false before publishing
## Description
A routine that raises an `OnBefore…` integration event with a `var IsHandled: Boolean` parameter passes that variable in by reference, so its incoming value decides whether the default logic is skipped. A freshly declared Boolean starts as `false`, but the same variable is frequently reused to raise several events in one routine, and after the first raise it may already be `true`. Assigning `IsHandled := false;` on the line immediately before every raise makes the control flow deterministic and self-documenting, and prevents a stale `true` from silently suppressing logic the author never meant to make skippable. Generated code often reuses one `IsHandled` across several raises without resetting it.
## Best Practice
Set `IsHandled := false;` immediately before each `OnBeforeX(…, IsHandled)` raise, then guard the default logic with `if IsHandled then exit;` or `if not IsHandled then …`. Do this even when the variable was just declared: the explicit reset documents intent and stays correct if a second event raise is added to the routine later. This applies only to events that carry a `var IsHandled: Boolean`; an `OnBefore` event with no `IsHandled` parameter needs no reset.
See sample: `initialize-ishandled-to-false-before-publishing.good.al`.
## Anti Pattern
Raising `OnBeforeX(…, IsHandled)` with a variable whose value carries over from an earlier raise, so a subscriber that handled the first event unintentionally suppresses the second routine's default logic. Detection: an `IsHandled` variable passed to more than one event in a routine without an intervening `IsHandled := false;`, or any `OnBefore…` raise that passes an `IsHandled` variable without an intervening `IsHandled := false;`.
See sample: `initialize-ishandled-to-false-before-publishing.bad.al`.

View file

@ -0,0 +1,48 @@
// Demonstration-only AL. Not compiled by CI; illustrates the article.
codeunit 50241 "IsHandled Carry Over Bad Sample"
{
procedure ApplyDiscounts(var SalesHeader: Record "Sales Header")
var
DiscountPct: Decimal;
IsHandled: Boolean;
begin
OnBeforeApplyHeaderDiscount(SalesHeader, DiscountPct, IsHandled);
if not IsHandled then
DiscountPct := 5;
// Bug: execution continues when the first event set IsHandled to true,
// and that stale value is passed to a different publisher.
OnBeforeApplyPaymentDiscount(SalesHeader, DiscountPct, IsHandled);
if not IsHandled then
DiscountPct += 2;
end;
procedure ApplyLineDiscounts(var SalesLine: Record "Sales Line")
var
LineIsHandled: Boolean;
begin
if SalesLine.FindSet() then
repeat
// Bug: the local initializes only once. A subscriber that handles
// one line leaves true for every later iteration.
OnBeforeApplyLineDiscount(SalesLine, LineIsHandled);
if not LineIsHandled then
SalesLine.Validate("Line Discount %", 5);
until SalesLine.Next() = 0;
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyHeaderDiscount(var SalesHeader: Record "Sales Header"; var DiscountPct: Decimal; var IsHandled: Boolean)
begin
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyPaymentDiscount(var SalesHeader: Record "Sales Header"; var DiscountPct: Decimal; var IsHandled: Boolean)
begin
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyLineDiscount(var SalesLine: Record "Sales Line"; var IsHandled: Boolean)
begin
end;
}

View file

@ -0,0 +1,50 @@
// Demonstration-only AL. Not compiled by CI; illustrates the article.
codeunit 50240 "IsHandled Carry Over Good Sample"
{
procedure ApplyDiscounts(var SalesHeader: Record "Sales Header")
var
DiscountPct: Decimal;
HeaderIsHandled: Boolean;
PaymentIsHandled: Boolean;
begin
// Each fresh local is false and belongs to one non-looping raise.
OnBeforeApplyHeaderDiscount(SalesHeader, DiscountPct, HeaderIsHandled);
if not HeaderIsHandled then
DiscountPct := 5;
// Handling the header event does not suppress this independent seam.
OnBeforeApplyPaymentDiscount(SalesHeader, DiscountPct, PaymentIsHandled);
if not PaymentIsHandled then
DiscountPct += 2;
end;
procedure ApplyLineDiscounts(var SalesLine: Record "Sales Line")
var
LineIsHandled: Boolean;
begin
if SalesLine.FindSet() then
repeat
// The local initializes once, so reset it per iteration; a
// subscriber that handles one line must not skip the rest.
LineIsHandled := false;
OnBeforeApplyLineDiscount(SalesLine, LineIsHandled);
if not LineIsHandled then
SalesLine.Validate("Line Discount %", 5);
until SalesLine.Next() = 0;
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyHeaderDiscount(var SalesHeader: Record "Sales Header"; var DiscountPct: Decimal; var IsHandled: Boolean)
begin
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyPaymentDiscount(var SalesHeader: Record "Sales Header"; var DiscountPct: Decimal; var IsHandled: Boolean)
begin
end;
[IntegrationEvent(false, false)]
local procedure OnBeforeApplyLineDiscount(var SalesLine: Record "Sales Line"; var IsHandled: Boolean)
begin
end;
}

View file

@ -0,0 +1,26 @@
---
bc-version: [all]
domain: events
keywords: [ishandled, carry-over, loop-iteration, onbefore, reset, integration-event, control-flow, false-positive]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Reset IsHandled before publishing only when its value can carry over
## Description
A routine that raises an `OnBefore…` integration event with a `var IsHandled: Boolean` parameter passes that variable by reference, so a pre-existing `true` can affect the following control flow. AL [automatically initializes Boolean variables to `false`](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-al-variables#initialization), so a freshly declared local Boolean passed to one event exactly once per procedure invocation is already deterministic. Initialization does not repeat for each loop iteration: a local declared outside a loop can carry `true` from one iteration to the next even when the source contains only one textual event raise. Outside a loop, reaching a later raise after `if IsHandled then exit;` also proves the value is `false`, provided that early exit is semantically correct and does not skip required downstream events.
## Best Practice
Reset `IsHandled := false;` before a raise only when the value might otherwise carry over as `true`: the same variable is reused after an earlier raise without a control-flow proof that it is false, a raise is re-entered by a loop, the value comes from an input parameter, field, or global, or earlier code seeds it. Prefer separate fresh locals when independent event seams need independent handled state. A reset on a guaranteed-false fresh local used by one non-looping raise, or before a later raise reached only after a semantically valid `if IsHandled then exit;`, can be retained for readability, but its absence is not a correctness finding.
See sample: `reset-ishandled-only-when-the-value-can-carry-over.good.al`.
## Anti Pattern
Raising `OnBeforeX(…, IsHandled)` when the variable can still be `true` from an earlier raise, an earlier loop iteration, or another source, so the publisher call starts with stale state. Do not match a single non-looping raise using a fresh local Boolean, or a later raise reached only after a semantically valid `if IsHandled then exit;` proves the value is false.
See sample: `reset-ishandled-only-when-the-value-can-carry-over.bad.al`.

View file

@ -5,8 +5,8 @@ codeunit 50493 "Perf Record Clone Bad"
Customer: Record Customer;
CustomerCopy: Record Customer;
begin
Customer.SetLoadFields("Credit Limit (LCY)");
Customer.SetFilter("Credit Limit (LCY)", '>0');
Customer.SetLoadFields("Credit Limit (LCY)");
if Customer.FindSet(true) then
repeat
CustomerCopy.Copy(Customer);

View file

@ -4,8 +4,8 @@ codeunit 50492 "Perf Record Clone Good"
var
Customer: Record Customer;
begin
Customer.SetLoadFields("Credit Limit (LCY)");
Customer.SetFilter("Credit Limit (LCY)", '>0');
Customer.SetLoadFields("Credit Limit (LCY)");
if Customer.FindSet(true) then
repeat
Customer.Validate(

View file

@ -3,12 +3,24 @@ codeunit 50129 "Perf Sample CommitInLoop Bad"
procedure NormalizeCustomerNames()
var
Customer: Record Customer;
LastCustomerNo: Code[20];
ProcessedCount: Integer;
begin
Customer.SetFilter("No.", '>%1', LastCustomerNo);
if Customer.FindSet(true) then
repeat
Customer.Name := UpperCase(Customer.Name);
Customer.Modify();
Commit();
// LastCustomerNo exists only in memory, so a retry cannot exclude
// work that was already committed.
LastCustomerNo := Customer."No.";
ProcessedCount += 1;
// This still opened a FindSet over the complete remaining tail;
// periodic commits do not turn retrieval into bounded TOP X.
if ProcessedCount mod 500 = 0 then
Commit();
until Customer.Next() = 0;
end;
}

View file

@ -16,11 +16,22 @@ codeunit 50128 "Perf Sample CommitInLoop Good"
{
procedure NormalizeCustomerNames()
var
NormalizeState: Record "Perf Normalize State";
LastCustomerNo: Code[20];
begin
// The outer loop owns checkpoints; the per-row loop contains no Commit.
while NormalizeNextChunk(LastCustomerNo) do
if not NormalizeState.Get('CUSTOMER') then begin
NormalizeState.Init();
NormalizeState.Code := 'CUSTOMER';
NormalizeState.Insert();
end;
LastCustomerNo := NormalizeState."Last Customer No.";
while NormalizeNextChunk(LastCustomerNo) do begin
// Persist progress in the same transaction as the completed chunk.
NormalizeState."Last Customer No." := LastCustomerNo;
NormalizeState.Modify();
Commit();
end;
end;
local procedure NormalizeNextChunk(var LastCustomerNo: Code[20]): Boolean
@ -58,3 +69,17 @@ codeunit 50128 "Perf Sample CommitInLoop Good"
exit(true);
end;
}
table 50128 "Perf Normalize State"
{
fields
{
field(1; Code; Code[10]) { }
field(2; "Last Customer No."; Code[20]) { }
}
keys
{
key(PK; Code) { Clustered = true; }
}
}

View file

@ -13,16 +13,18 @@ application-area: [all]
## Description
Commit ends the current write transaction. Calling it inside a per-row loop produces one transaction per iteration and loses the ability to roll back the whole operation atomically; it also interferes with the platform's ability to batch write operations. Most loops need no explicit Commit at all — AL auto-commits the enclosing code module on successful completion (see `understand-implicit-transaction-boundary.md`). When the batch is too large for one transaction, the fix is not a per-row Commit but bounded checkpoints that select an exact list of at most N keys and process only those rows.
Commit ends the current write transaction. Calling it inside a per-row loop usually produces one transaction per iteration and loses the ability to roll back the whole operation atomically; it also interferes with batching. Most loops need no explicit Commit at all — AL auto-commits the enclosing code module on successful completion (see `understand-implicit-transaction-boundary.md`).
A durability checkpoint inside an outer batch loop can be valid only when the same transaction persists a progress marker or state that makes retries strictly exclude completed work, the checkpoint follows a complete business unit, and errors propagate instead of being swallowed. Restart safety and bounded retrieval are separate requirements: a persisted watermark can make retries safe, but an outer `FindSet` over the full remaining tail with periodic commits still retrieves the complete set because [`FindSet` is not implemented as `TOP X`](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/optimize-sql-al-database-methods-and-performance-on-server#get-find-findset-and-next).
## Best Practice
If the batch is large enough that a single transaction is untenable, use an ordered primary-key watermark and retrieve a bounded next-N key list. `FindSet` is optimized for reading the complete filtered set and isn't implemented as `TOP X`, so calling it over the remaining tail and breaking after N rows does not bound retrieval. The sample uses a query capped by [`TopNumberOfRows`](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/query/queryinstance-topnumberofrows-method) to fill a temporary key buffer, then takes update locks and modifies only those exact keys. It does not reconstruct an inclusive first-to-last range that concurrent inserts could expand. Commit after the bounded inner loop returns and persist its last selected key as the next watermark. Use a stable key and define how a later run handles records inserted at or below an already committed watermark. A `Codeunit.Run` boundary can also own a chunk when its implicit commit and error behavior fit the caller — see `codeunit-run-as-atomic-sub-operation.md`.
If the batch is large enough that a single transaction is untenable, use an ordered primary-key watermark and retrieve a bounded next-N key list. The sample uses a query capped by [`TopNumberOfRows`](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/query/queryinstance-topnumberofrows-method) to fill a temporary key buffer, then takes update locks and modifies only those exact keys. It does not reconstruct an inclusive first-to-last range that concurrent inserts could expand. Persist the last selected key in the same transaction as the completed chunk, then commit after the bounded helper returns. Use a stable key and define how a later run handles records inserted at or below an already committed watermark. Let errors escape so failed work is not recorded as complete. A `Codeunit.Run` boundary can also own a chunk when its implicit commit and error behavior fit the caller — see `codeunit-run-as-atomic-sub-operation.md`.
See sample: `avoid-commit-inside-loops.good.al`.
## Anti Pattern
Placing Commit inside `repeat ... until Next() = 0` is almost always a mistake: it is unusual for the correctness of the operation to depend on per-row commits, and the cost of starting a new transaction on every row dominates the work. A capped query that discovers only an upper key and then re-reads an inclusive key range is not exact batching either; concurrent inserts inside that range can enlarge the checkpoint.
Placing Commit inside `repeat ... until Next() = 0` without persisted progress is almost always a mistake: retries re-enter already committed work, while the cost of starting a transaction on every row dominates the operation. A progress variable held only in memory is not restart-safe. A full-tail `FindSet` with a commit every N rows is not bounded retrieval, even if a persisted watermark makes it restart-safe. A capped query that discovers only an upper key and then re-reads an inclusive key range is not exact batching either; concurrent inserts inside that range can enlarge the checkpoint.
See sample: `avoid-commit-inside-loops.bad.al`.

View file

@ -0,0 +1,24 @@
page 50100 "CurrPage Update OAGR Bad"
{
PageType = List;
SourceTable = Customer;
ApplicationArea = All;
layout
{
area(content)
{
repeater(Rows)
{
field("No."; Rec."No.") { }
field(Name; Rec.Name) { }
}
}
}
trigger OnAfterGetRecord()
begin
// Update from OnAfterGetRecord re-enters the trigger on every row.
CurrPage.Update(false);
end;
}

View file

@ -0,0 +1,26 @@
page 50100 "CurrPage Update OAGR Good"
{
PageType = List;
SourceTable = Customer;
ApplicationArea = All;
layout
{
area(content)
{
repeater(Rows)
{
field("No."; Rec."No.") { }
field(Warning; WarningText) { }
}
}
}
var
WarningText: Text[50];
trigger OnAfterGetRecord()
begin
WarningText := CopyStr(Rec.Name, 1, MaxStrLen(WarningText));
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [currpage-update, onaftergetrecord, list-page, scroll, refresh]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Do not call CurrPage.Update inside OnAfterGetRecord
> Contributions welcome — open a PR to refine or extend this article.
## Description
`OnAfterGetRecord` on a list already runs once per visible row on scroll and refresh. `CurrPage.Update` asks the page to reload, which fires those triggers again. The result is a refresh loop or a stutter on every row paint. Official developer performance guidance lists `CurrPage.Update()` in `OnAfterGetRecord` next to `Modify` as work that must not live there. Sibling of `do-not-modify-in-onaftergetrecord.md` (writes); this file is the client refresh half.
## Best Practice
Put display-only results in page variables assigned in `OnAfterGetRecord` without calling `Update`. If the page must refresh after an action, call `CurrPage.Update(false)` from `OnAction` once, not per row.
See sample: `avoid-currpage-update-in-onaftergetrecord.good.al`.
## Anti Pattern
`trigger OnAfterGetRecord() begin ... CurrPage.Update(); end;` on a list. The signal is `CurrPage.Update` inside `OnAfterGetRecord` or `OnAfterGetCurrRecord` without an explicit user action.
See sample: `avoid-currpage-update-in-onaftergetrecord.bad.al`.

View file

@ -0,0 +1,20 @@
codeunit 50100 "Batch NoSeries Insert Bad"
{
procedure InsertDraftOrders(var Customer: Record Customer)
var
SalesHeader: Record "Sales Header";
SalesSetup: Record "Sales & Receivables Setup";
NoSeries: Codeunit "No. Series";
begin
SalesSetup.Get();
if Customer.FindSet() then
repeat
SalesHeader.Init();
SalesHeader."Document Type" := SalesHeader."Document Type"::Order;
// Per-row GetNextNo locks the number-series line every insert.
SalesHeader."No." := NoSeries.GetNextNo(SalesSetup."Order Nos.", WorkDate());
SalesHeader."Sell-to Customer No." := Customer."No.";
SalesHeader.Insert(true);
until Customer.Next() = 0;
end;
}

View file

@ -0,0 +1,20 @@
codeunit 50100 "Batch NoSeries Insert Good"
{
procedure InsertDraftOrders(var Customer: Record Customer)
var
SalesHeader: Record "Sales Header";
SalesSetup: Record "Sales & Receivables Setup";
NoSeriesBatch: Codeunit "No. Series - Batch";
begin
SalesSetup.Get();
if Customer.FindSet() then
repeat
SalesHeader.Init();
SalesHeader."Document Type" := SalesHeader."Document Type"::Order;
SalesHeader."No." := NoSeriesBatch.GetNextNo(SalesSetup."Order Nos.", WorkDate());
SalesHeader."Sell-to Customer No." := Customer."No.";
SalesHeader.Insert(true);
until Customer.Next() = 0;
NoSeriesBatch.SaveState();
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [22..]
domain: performance
keywords: [no-series, getnextno, no-series-batch, savestate, numbersequence, lock]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Batch number-series calls instead of GetNextNo per insert
> Contributions welcome — open a PR to refine or extend this article.
## Description
`Codeunit "No. Series".GetNextNo` on a **gapless (Normal)** series updates and locks the number-series line on every call. A tight `Insert` loop that asks for a number per row serializes every concurrent writer on that series — the classic SaaS posting bottleneck. Training data still copies the per-row C/AL `NoSeriesManagement` shape. Series configured with **Allow Gaps** instead obtain numbers through `NumberSequence` and do not hold the series-line lock between calls, so they are not affected by this pattern. Codeunit `"No. Series - Batch"` issues gapless numbers in memory and writes the series line once via `SaveState`.
## Best Practice
Inside a multi-row insert, call `"No. Series - Batch".GetNextNo` per row and `SaveState` once after the loop when the series must remain gapless. Use `NumberSequence.Next` when holes are allowed. Do not replace a single `OnInsert` `GetNextNo` for one master record; that path is not the hotspot.
See sample: `batch-number-series-instead-of-getnextno-per-row.good.al`.
## Anti Pattern
`NoSeries.GetNextNo(...)` inside `repeat ... Insert ... until Next() = 0` where the series is **gapless** (Allow Gaps = false). Each iteration takes the series-line lock. The signal is `"No. Series"` (not `"No. Series - Batch"`) in a loop that inserts more than one row; do not flag the same pattern when the series has Allow Gaps enabled, as the `NumberSequence` path already avoids the lock.
See sample: `batch-number-series-instead-of-getnextno-per-row.bad.al`.

View file

@ -0,0 +1,31 @@
codeunit 50541 "Perf Sample NoShortCircuit Bad"
{
procedure ExceedsThreshold(var Thresholds: array[10] of Decimal; Index: Integer; Amount: Decimal): Boolean
begin
// Thresholds[Index] is evaluated even when Index is 0, so the leading range
// check does not prevent the subscript from being read out of range.
exit((Index >= 1) and (Index <= ArrayLen(Thresholds)) and (Amount > Thresholds[Index]));
end;
procedure IsBlockedCustomer(CustomerNo: Code[20]): Boolean
var
Customer: Record Customer;
begin
// The Get runs even for an empty CustomerNo, and Blocked is read even when the
// Get failed, so the result is taken from a record that was never loaded.
exit((CustomerNo <> '') and Customer.Get(CustomerNo) and (Customer.Blocked <> Customer.Blocked::" "));
end;
procedure IsEligibleForFreeShipping(SalesHeader: Record "Sales Header"): Boolean
begin
// HasActiveLoyaltyBenefit runs even when the amount alone already qualifies,
// paying for the costly check on every evaluation instead of only the path
// where it can still change the outcome.
exit((SalesHeader."Amount Including VAT" >= 1000) or HasActiveLoyaltyBenefit(SalesHeader."Sell-to Customer No."));
end;
local procedure HasActiveLoyaltyBenefit(CustomerNo: Code[20]): Boolean
begin
exit(CustomerNo <> '');
end;
}

View file

@ -0,0 +1,41 @@
codeunit 50540 "Perf Sample NoShortCircuit Good"
{
procedure ExceedsThreshold(var Thresholds: array[10] of Decimal; Index: Integer; Amount: Decimal): Boolean
begin
// 'and' is safe here: both operands are cheap and neither depends on the other.
if (Index >= 1) and (Index <= ArrayLen(Thresholds)) then
// The subscript lives in its own if, so it is never evaluated out of range.
if Amount > Thresholds[Index] then
exit(true);
exit(false);
end;
procedure IsBlockedCustomer(CustomerNo: Code[20]): Boolean
var
Customer: Record Customer;
begin
// The cheap test runs first, and the field is read only after Get succeeded.
if CustomerNo = '' then
exit(false);
if not Customer.Get(CustomerNo) then
exit(false);
exit(Customer.Blocked <> Customer.Blocked::" ");
end;
procedure IsEligibleForFreeShipping(SalesHeader: Record "Sales Header"): Boolean
begin
// 'or' is unsafe here: nesting would also be wrong, since it would drop the
// case where the amount alone already qualifies. Exit as soon as the cheap
// condition already decides the result; the costly lookup runs only on the
// path where it can still change the outcome.
if SalesHeader."Amount Including VAT" >= 1000 then
exit(true);
exit(HasActiveLoyaltyBenefit(SalesHeader."Sell-to Customer No."));
end;
local procedure HasActiveLoyaltyBenefit(CustomerNo: Code[20]): Boolean
begin
// Stands in for a costly check — a webservice call or a large table scan.
exit(CustomerNo <> '');
end;
}

View file

@ -0,0 +1,36 @@
---
bc-version: [all]
domain: performance
keywords: [short-circuit, lazy-evaluation, boolean-operators, nested-if, guard, and-operator, or-operator, xor-operator, early-exit]
technologies: [al]
countries: [w1]
application-area: [all]
---
# AL boolean operators do not short-circuit
## Description
AL gives no short-circuit (lazy) evaluation guarantee for `and`, `or`, and `xor`: every operand of a boolean expression is evaluated, even when the leftmost operand already determines the result. Neither the AL operators documentation nor the boolean operators documentation defines a lazy evaluation order, so code must not depend on one. Developers arriving from C#, JavaScript, or SQL routinely assume the left operand guards the right; in AL it does not. `xor` is not actually a short-circuit candidate in any language — its result depends on both operands regardless of their values, so there is nothing to skip — but AL still evaluates both operands unconditionally, so neither should carry a cost or a risk the developer assumed the other would guard against. For `and` and `or`, the right operand still runs even when the left already decides the result, so its cost is paid on every evaluation, and a check intended to protect an unsafe expression — an array subscript, a division, a field read that is only valid after a successful `Get` — does not protect it.
## Best Practice
For an `and`-shaped guard — a condition that must hold before the next operand is safe or worth evaluating — split into nested `if` statements: the guarding or cheapest condition in the outer `if`, the dependent or expensive one in the inner `if`. This preserves the result, since `if A then if B then Action` matches `if A and B then Action` exactly. Where there is no `else` branch, nesting is a pure win; where there is one, extract the conditions into a helper procedure that exits early instead.
For an `or`-shaped condition, do not nest: nesting `if A then if B then Action` drops the case where `A` is true and `B` is false, silently changing the result of `A or B`. Exit as soon as the cheap or safe operand already decides the outcome, and reach the other operand only on the path where it can still change the result — `if A then exit(true); exit(B);` for a boolean return, or `if A then Action else if B then Action;` when both branches share one action.
`xor` has no equivalent rewrite, because its result always depends on both operands; the only actionable guidance is to keep both operands of an `xor` cheap and free of side effects, since AL evaluates both unconditionally.
Where a chain of `and`-guards runs past about three conditions, stop nesting and use a `case` statement instead — see `case-true-of-for-long-condition-chains.md`. Keep `and` and `or` for operands that are independently safe and cheap — in-memory field comparisons, enum tests, bound checks — where combining them reads better and costs nothing.
See sample: `boolean-operators-do-not-short-circuit.good.al`.
## Anti Pattern
A single condition that joins a guard with an operand depending on that guard, or with an expensive operand, using `and` or `or`. The consequence is either wasted work on every evaluation — a database call or validation procedure invoked even when the outcome is already decided — or a runtime error or silently wrong result that the guard was written to prevent. Applying the `and` fix to an `or` condition is a distinct mistake: rewriting `A or B` as nested `if`s drops the `A`-true/`B`-false case instead of preserving it. Detection signals: an operand that indexes an array or list with a variable whose bounds are checked in a sibling operand; `Record.Get(...)` or a `Find`/`IsEmpty` call as one operand of `and` with a field read of the same record as another; an expensive or unsafe operand combined with `or` next to a condition that alone already makes the result true; a boolean-returning procedure call combined with a cheap field test. The pattern is common in code ported from a language that does short-circuit, and in conditions grown by appending a clause to an existing `if`.
See sample: `boolean-operators-do-not-short-circuit.bad.al`.
## See also
`case-true-of-for-long-condition-chains.md` covers what to do when nesting an `and`-guard chain would go more than about three levels deep. `microsoft/knowledge/performance/apply-guards-before-get.md` covers the related ordering rule for statements rather than operands.

View file

@ -0,0 +1,29 @@
codeunit 50543 "Perf Sample CaseChain Bad"
{
procedure IsShippableLine(SalesLine: Record "Sales Line"): Boolean
var
Item: Record Item;
begin
// Five levels of nesting to sequence five guards. The evaluation order is
// carried by indentation alone and the body drifts steadily right.
if SalesLine.Type = SalesLine.Type::Item then
if SalesLine."No." <> '' then
if SalesLine."Qty. to Ship" > 0 then
if Item.Get(SalesLine."No.") then
if not Item.Blocked then
exit(true);
exit(false);
end;
procedure IsShippableLineCollapsed(SalesLine: Record "Sales Line"): Boolean
var
Item: Record Item;
begin
// The wrong escape from the ladder: flattening it into 'and' trades the
// nesting for a defect, because every operand is still evaluated. Item
// fields are read even when the Get failed. The parentheses are not
// optional either — 'and' binds tighter than '=' and '<>' in AL.
exit((SalesLine.Type = SalesLine.Type::Item) and (SalesLine."No." <> '') and
(SalesLine."Qty. to Ship" > 0) and Item.Get(SalesLine."No.") and not Item.Blocked);
end;
}

View file

@ -0,0 +1,48 @@
codeunit 50542 "Perf Sample CaseChain Good"
{
procedure IsShippableLine(SalesLine: Record "Sales Line"): Boolean
var
Item: Record Item;
begin
// 'case false of' matches value sets in order and stops at the first match.
// The first three checks are pure and order-independent, so they share one
// value set. Get and Blocked are each their own value set, in order, because
// the ordering the documentation guarantees is across value sets, not within
// one — Item.Get must run, and succeed, before Blocked is read.
case false of
SalesLine.Type = SalesLine.Type::Item,
SalesLine."No." <> '',
SalesLine."Qty. to Ship" > 0:
exit(false);
Item.Get(SalesLine."No."):
exit(false);
not Item.Blocked:
exit(false);
end;
exit(true);
end;
procedure FindOpenDocumentType(CustomerNo: Code[20]): Text
begin
// 'case true of' stops at the first condition that holds, so the later
// lookups never run once an earlier one matched.
case true of
HasOpenDocument(CustomerNo, "Sales Document Type"::Quote):
exit('Quote');
HasOpenDocument(CustomerNo, "Sales Document Type"::Order):
exit('Order');
HasOpenDocument(CustomerNo, "Sales Document Type"::Invoice):
exit('Invoice');
end;
exit('None');
end;
local procedure HasOpenDocument(CustomerNo: Code[20]; DocumentType: Enum "Sales Document Type"): Boolean
var
SalesHeader: Record "Sales Header";
begin
SalesHeader.SetRange("Document Type", DocumentType);
SalesHeader.SetRange("Sell-to Customer No.", CustomerNo);
exit(not SalesHeader.IsEmpty());
end;
}

View file

@ -0,0 +1,30 @@
---
bc-version: [all]
domain: performance
keywords: [case-statement, case-true-of, nested-if, condition-chain, guard, lazy-evaluation, nesting-depth]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Use case true of for long chains of dependent conditions
## Description
Because AL gives no short-circuit guarantee for `and` and `or`, a chain of conditions that must be evaluated in order has to be sequenced with nested `if` statements — and past three conditions the nesting itself becomes the problem: the body drifts right, the order of evaluation is carried by indentation alone, and any shared failure path is repeated at every level. AL's `case` statement is the flat alternative. Its value sets "must be an expression or a range", so `case true of` and `case false of` accept arbitrary boolean expressions, and the statement "is evaluated, and the first matching value set executes the associated statement" — evaluation stops at the first matching value set, which is exactly the laziness the boolean operators do not provide. That guarantee is stated for value sets, plural: it orders evaluation *across* separate value sets, and says nothing about the order of the individual expressions listed inside one comma-separated value set.
## Best Practice
Sequence two or three dependent conditions with nested `if`. Beyond that, switch to `case`: use `case false of` for a chain of guards where every condition must hold, letting control fall past `end` when all of them pass; use `case true of` for first-match dispatch, where each later probe runs only if the earlier ones did not match. Comma-separate conditions into one value set only when every one of them is a pure, order-independent test with no side effect — a field comparison, an enum check, a bound test — so it makes no difference whether AL evaluates all of them or stops early; grouping these costs nothing and removes the repeated action. A condition that guards another, or that carries a side effect or a cost of its own — a `Get`, a `Find`, a procedure call — keeps its own value set, placed immediately after the value set it depends on, so the code relies only on the ordering the documentation actually states. A value set needs no parentheses around a comparison, unlike an operand of `and` or `or`: the AL operator hierarchy places `and` and `or` above the comparison operators, so parentheses are mandatory there and the chain fills up with them. This keeps every condition at one indentation level, makes evaluation order explicit rather than implied by nesting, and preserves the stop-at-first-match behaviour it relies on. It also aligns with the AL programming convention that more than two alternatives belong in a `case` statement rather than an `if-then-else`.
See sample: `case-true-of-for-long-condition-chains.good.al`.
## Anti Pattern
An `if` ladder four or more levels deep whose only purpose is sequencing guards. Detection: a chain of nested `if` statements with no `else`, each condition guarding the one below it, terminating in a single action or `exit`; or the same `exit`/`error` duplicated at every level of such a nested chain, purely to escape it. The second, worse form is collapsing that ladder into one `and` chain to escape the nesting — that trades indentation for a real defect, because the operands are still all evaluated. A third, subtler form is over-applying the comma-grouping itself: putting a guard and the condition it protects — for example `Item.Get(...)` and a read of a field on that same record — into one comma-separated value set. That relies on an evaluation order within a single value set that the documentation does not state; keep them in separate value sets instead. Reach for `case` over nested `if` or a collapsed `and` chain, and keep order-dependent conditions in their own value sets within it.
See sample: `case-true-of-for-long-condition-chains.bad.al`.
## See also
`boolean-operators-do-not-short-circuit.md` covers the underlying evaluation rule that makes the sequencing necessary in the first place.

View file

@ -0,0 +1,20 @@
codeunit 50100 "ChangeCompany Loop Bad"
{
procedure NamesForCustomers(var Buffer: Record Customer)
var
Customer: Record Customer;
Company: Record Company;
begin
Customer.SetLoadFields(Name);
if Buffer.FindSet() then
repeat
if Company.FindSet() then
repeat
// ChangeCompany per customer per company resets caches every row.
Customer.ChangeCompany(Company.Name);
if Customer.Get(Buffer."No.") then
Message(Customer.Name);
until Company.Next() = 0;
until Buffer.Next() = 0;
end;
}

View file

@ -0,0 +1,19 @@
codeunit 50100 "ChangeCompany Loop Good"
{
procedure NamesForCustomers(var Buffer: Record Customer)
var
Customer: Record Customer;
Company: Record Company;
begin
Customer.SetLoadFields(Name);
if Company.FindSet() then
repeat
Customer.ChangeCompany(Company.Name);
if Buffer.FindSet() then
repeat
if Customer.Get(Buffer."No.") then
Message(Customer.Name);
until Buffer.Next() = 0;
until Company.Next() = 0;
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [changecompany, loop, cache, multi-company, isolation]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Do not call ChangeCompany inside a per-row loop
> Contributions welcome — open a PR to refine or extend this article.
## Description
`ChangeCompany` retargets a record variable to another company's data and drops the in-memory caches bound to the previous company. Calling it once per row in a multi-company scan therefore pays a cache reset on every iteration, even when consecutive rows share a company. Agents treat `ChangeCompany` like a filter. It is an isolation switch.
## Best Practice
Group work by company. Call `ChangeCompany` once per distinct company, then `FindSet`/`Get` that company's rows. If the record variable is reused afterward, call `ChangeCompany()` without a company name to redirect it back to the current company.
See sample: `changecompany-in-loop-drops-caches.good.al`.
## Anti Pattern
`repeat Rec.ChangeCompany(Buffer.Company); Rec.Get(Buffer."No."); until Buffer.Next() = 0` when `Buffer` is not ordered by company, or even when it is — if `ChangeCompany` still runs every row. The signal is `ChangeCompany` inside `repeat`/`while` keyed by a document line rather than by a company loop.
See sample: `changecompany-in-loop-drops-caches.bad.al`.

View file

@ -0,0 +1,15 @@
report 50100 "Cust List ReadOnly Bad"
{
UsageCategory = ReportsAndAnalysis;
ApplicationArea = All;
// Missing DataAccessIntent = ReadOnly; the scan hits the primary replica.
dataset
{
dataitem(Customer; Customer)
{
column(No; "No.") { }
column(Name; Name) { }
}
}
}

View file

@ -0,0 +1,15 @@
report 50100 "Cust List ReadOnly Good"
{
UsageCategory = ReportsAndAnalysis;
ApplicationArea = All;
DataAccessIntent = ReadOnly;
dataset
{
dataitem(Customer; Customer)
{
column(No; "No.") { }
column(Name; Name) { }
}
}
}

View file

@ -0,0 +1,28 @@
---
bc-version: ["16.."]
domain: performance
keywords: [dataaccessintent, read-only, read-scale-out, report, api-page, query]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Set DataAccessIntent ReadOnly on analytical objects
> Contributions welcome — open a PR to refine or extend this article.
## Description
`DataAccessIntent` was introduced at runtime 5.0 (BC 16) and has no effect in earlier versions. Reports, API pages (`PageType = API` with `Editable = false`), and queries that only read can run against a read replica when `DataAccessIntent = ReadOnly`. For queries, replica routing only applies when the query is exposed via OData/API; running a query in AL code is unaffected. Without the property these objects hit the primary replica and compete with posting. Agents omit it because the default is read-write and the object "only reads" in AL. The replica routing is a metadata switch, not something the compiler infers from the absence of `Modify`.
## Best Practice
On report objects and `PageType = API` pages with `Editable = false` that never write, set `DataAccessIntent = ReadOnly`. For query objects, set it when the query is consumed via OData or an API endpoint. Keep the default on objects that insert, modify, or call a write codeunit from a processing-only report.
See sample: `dataaccessintent-readonly-on-analytical-objects.good.al`.
## Anti Pattern
A listing report or API query with no `DataAccessIntent` that scans G/L or sales lines. The object is read-only in practice and still loads the primary.
See sample: `dataaccessintent-readonly-on-analytical-objects.bad.al`.

View file

@ -0,0 +1,34 @@
page 50100 "GuiAllowed OData Guard Bad"
{
PageType = List;
SourceTable = Customer;
ApplicationArea = All;
layout
{
area(content)
{
repeater(Rows)
{
field("No."; Rec."No.") { }
field(Name; Rec.Name)
{
StyleExpr = NameStyle;
}
}
}
}
var
NameStyle: Text;
trigger OnAfterGetRecord()
begin
// UI-only styling still runs for every OData / Edit-in-Excel row.
Rec.CalcFields("Balance (LCY)");
if Rec."Balance (LCY)" > 0 then
NameStyle := 'Attention'
else
NameStyle := 'Standard';
end;
}

View file

@ -0,0 +1,35 @@
page 50100 "GuiAllowed OData Guard Good"
{
PageType = List;
SourceTable = Customer;
ApplicationArea = All;
layout
{
area(content)
{
repeater(Rows)
{
field("No."; Rec."No.") { }
field(Name; Rec.Name)
{
StyleExpr = NameStyle;
}
}
}
}
var
NameStyle: Text;
trigger OnAfterGetRecord()
begin
if not GuiAllowed then
exit;
Rec.CalcFields("Balance (LCY)");
if Rec."Balance (LCY)" > 0 then
NameStyle := 'Attention'
else
NameStyle := 'Standard';
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [guiallowed, clienttype, odata, edit-in-excel, page-trigger, factbox]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Guard page trigger work with GuiAllowed for OData and Excel
> Contributions welcome — open a PR to refine or extend this article.
## Description
Pages exposed as OData, including Edit in Excel, still run AL page triggers for every row returned. FactBox updates, defaulting, and extra `CalcFields` in `OnAfterGetRecord` therefore run on the web-service path where no UI exists. `GuiAllowed` is false for those sessions. Agents add page logic as if only the browser client will execute it.
## Best Practice
Wrap UI-only work — FactBox refresh, notifications, defaulting that is not part of the web-service contract — in `if GuiAllowed then`. Keep the OData path to field values the API actually returns.
See sample: `guiallowed-guard-on-pages-used-as-odata.good.al`.
## Anti Pattern
Unconditional FactBox or calculation logic in `OnAfterGetRecord` / `OnAfterGetCurrRecord` on a page that is published as a web service or used with Edit in Excel. The signal is trigger work that calls `CurrPage` parts or extra queries without a `GuiAllowed` guard.
See sample: `guiallowed-guard-on-pages-used-as-odata.bad.al`.

View file

@ -0,0 +1,13 @@
codeunit 50100 "HttpClient Holds Locks Bad"
{
procedure SyncCustomerLastName(var Customer: Record Customer)
var
Client: HttpClient;
Response: HttpResponseMessage;
begin
Customer."Search Name" := Customer.Name;
Customer.Modify(false);
// Locks from Modify are held for the entire HTTP wait.
Client.Get(StrSubstNo('https://example.local/sync/%1', Customer."No."), Response);
end;
}

View file

@ -0,0 +1,62 @@
codeunit 50100 "HttpClient Holds Locks Good"
{
procedure SyncCustomerLastName(var Customer: Record Customer)
var
CustomerSyncOutbox: Record "Customer Sync Outbox";
begin
Customer."Search Name" := Customer.Name;
Customer.Modify(false);
// This work item commits or rolls back with the customer change.
CustomerSyncOutbox."Customer No." := Customer."No.";
CustomerSyncOutbox.Insert();
end;
}
table 50100 "Customer Sync Outbox"
{
DataClassification = CustomerContent;
fields
{
field(1; "Entry No."; Integer)
{
AutoIncrement = true;
}
field(2; "Customer No."; Code[20]) { }
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}
codeunit 50101 "Customer Sync Outbox Worker"
{
// Configure this codeunit as a recurring job queue entry.
TableNo = "Job Queue Entry";
trigger OnRun()
var
Customer: Record Customer;
CustomerSyncOutbox: Record "Customer Sync Outbox";
Client: HttpClient;
Response: HttpResponseMessage;
begin
// Only committed work is visible here; a rolled-back change leaves no outbox row.
if not CustomerSyncOutbox.FindFirst() then
exit;
Customer.Get(CustomerSyncOutbox."Customer No.");
Client.Get(StrSubstNo('https://example.local/sync/%1', Customer."No."), Response);
if not Response.IsSuccessStatusCode() then
Error('Customer sync failed with HTTP status %1.', Response.HttpStatusCode());
// Delete only after HTTP completes, so no write lock is held during the call.
CustomerSyncOutbox.Delete();
end;
}

View file

@ -0,0 +1,30 @@
---
bc-version: [all]
domain: performance
keywords: [httpclient, write-transaction, lock, commit, outbound-http, session-block]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Do not call HttpClient inside an open write transaction
> Contributions welcome — open a PR to refine or extend this article.
## Description
The first database write opens an AL write transaction that the runtime holds until the execution completes or `Commit()` runs — see `understand-implicit-transaction-boundary.md`. `HttpClient` blocks the session until the remote call returns. Any locks taken by earlier `Insert`/`Modify`/`Delete` therefore stay held for the HTTP wall-clock time, and interactive users see a spinner. This is not generic "don't block": it is the AL transaction model plus lock lifetime around outbound I/O.
## Best Practice
Defer the HTTP call to a separate session. When the external operation must correspond to a committed database change, insert an outbox work item in the same transaction as that change and process committed outbox rows with a recurring job queue entry. The change and work item then commit or roll back together, and the worker performs HTTP before deleting the item so it holds no write lock during the call. The separate retry-safety requirement is covered by `job-queue-external-effects-must-be-idempotent.md`.
A directly created scheduled task is suitable only when its work is independent of the caller's commit. An immediately ready task can run concurrently with the caller, so it must not assume that the caller's writes are already committed. Do **not** use `Commit()` as a general remedy: it irrevocably commits all prior writes in the current transaction, so any subsequent failure cannot roll them back. `Commit()` is appropriate only at top-level entry points where partial persistence is intentional and understood.
See sample: `httpclient-inside-write-transaction-holds-locks.good.al`.
## Anti Pattern
`Modify`/`Insert` followed by `HttpClient` in the same procedure with no `Commit` between them. Detection signal: any `HttpClient` use after a write on the same execution path, especially in posting, page actions, or subscribers.
See sample: `httpclient-inside-write-transaction-holds-locks.bad.al`.

View file

@ -0,0 +1,16 @@
codeunit 50100 "IsEmpty Before FindSet Bad"
{
procedure ListUsCustomerNames()
var
Customer: Record Customer;
begin
Customer.SetLoadFields(Name);
Customer.SetRange("Country/Region Code", 'US');
// IsEmpty does not replace FindSet; it adds a second round-trip.
if not Customer.IsEmpty() then
if Customer.FindSet() then
repeat
Message(Customer.Name);
until Customer.Next() = 0;
end;
}

View file

@ -0,0 +1,14 @@
codeunit 50100 "IsEmpty Before FindSet Good"
{
procedure ListUsCustomerNames()
var
Customer: Record Customer;
begin
Customer.SetLoadFields(Name);
Customer.SetRange("Country/Region Code", 'US');
if Customer.FindSet() then
repeat
Message(Customer.Name);
until Customer.Next() = 0;
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [isempty, findset, extra-round-trip, existence-check, false-positive]
technologies: [al]
countries: [w1]
application-area: [all]
---
# IsEmpty immediately before FindSet is an extra round-trip
> Contributions welcome — open a PR to refine or extend this article.
## Description
`IsEmpty` is the right API when the caller only needs existence — see `microsoft/knowledge/performance/use-isempty-for-existence-check.md`. It is not a cheap guard in front of a loop that will `FindSet` anyway. Both calls hit the database; `FindSet` already returns false when the filter matches nothing. Agents and reviewers often insert `if not Rec.IsEmpty() then` "for performance" and pay a second query for a result the iterator already provides.
## Best Practice
When the body iterates, open with `if Rec.FindSet() then repeat ... until Next() = 0`. Do not flag a bare `FindSet` loop as missing an `IsEmpty` precondition. Reserve `IsEmpty` for branches that never materialize the row set.
See sample: `isempty-before-findset-is-extra-round-trip.good.al`.
## Anti Pattern
`if not Rec.IsEmpty() then if Rec.FindSet() then repeat`. Also a false-positive review comment that asks to add that guard. The second read does not avoid the first; it duplicates it.
See sample: `isempty-before-findset-is-extra-round-trip.bad.al`.

View file

@ -0,0 +1,9 @@
codeunit 50113 "Job Queue Category Bad"
{
procedure ConfigurePostingJobs(var PostSales: Record "Job Queue Entry"; var PostPurchases: Record "Job Queue Entry")
begin
// Both jobs update the same posting resources, but nothing prevents overlap.
PostSales.Validate("Job Queue Category Code", '');
PostPurchases.Validate("Job Queue Category Code", '');
end;
}

View file

@ -0,0 +1,9 @@
codeunit 50113 "Job Queue Category Good"
{
procedure ConfigurePostingJobs(var PostSales: Record "Job Queue Entry"; var PostPurchases: Record "Job Queue Entry")
begin
// The shared category lets only one conflicting posting job run at a time.
PostSales.Validate("Job Queue Category Code", 'POSTING');
PostPurchases.Validate("Job Queue Category Code", 'POSTING');
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [job-queue, category-code, concurrency, waiting, serialization, locking]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Use a job queue category to serialize conflicting jobs
> Contributions welcome — open a PR to refine or extend this article.
## Description
Different job queue entries can run at the same time. When two jobs update the same exclusive resource, concurrent execution can cause lock contention, deadlocks, or conflicting results. Entries with the same Job Queue Category Code are serialized: while one runs, another entry in that category waits.
## Best Practice
Assign the same non-empty Job Queue Category Code to jobs that must not overlap, regardless of which codeunit they run. Define categories around the shared resource or exclusivity requirement, not merely around object names. Leave independent jobs in different categories so they can still run concurrently.
See sample: `job-queue-category-code-serializes-conflicting-jobs.good.al`.
## Anti Pattern
Creating or configuring multiple job queue entries that update the same exclusive resource while leaving their Job Queue Category Code empty or different. Do not flag jobs merely because they touch the same tables; the rule applies when their operation requires mutual exclusion.
See sample: `job-queue-category-code-serializes-conflicting-jobs.bad.al`.

View file

@ -0,0 +1,57 @@
table 50112 "Queued Export Bad"
{
DataClassification = CustomerContent;
fields
{
field(1; "Entry No."; Integer)
{
AutoIncrement = true;
}
field(2; Payload; Text[250])
{
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}
codeunit 50112 "Queued Export Worker Bad"
{
TableNo = "Job Queue Entry";
trigger OnRun()
var
QueuedExport: Record "Queued Export Bad";
Client: HttpClient;
Content: HttpContent;
Response: HttpResponseMessage;
begin
if not QueuedExport.FindFirst() then
exit;
Content.WriteFrom(QueuedExport.Payload);
Client.Post('https://example.local/exports', Content, Response);
if not Response.IsSuccessStatusCode() then
Error('Export failed with HTTP status %1.', Response.HttpStatusCode());
// If this local step fails, the external export exists but this row is retried.
UpdateLocalStatus();
FinalizeExport(QueuedExport);
end;
local procedure UpdateLocalStatus()
begin
end;
local procedure FinalizeExport(var QueuedExport: Record "Queued Export Bad")
begin
QueuedExport.Delete();
end;
}

View file

@ -0,0 +1,65 @@
table 50112 "Queued Export Good"
{
DataClassification = CustomerContent;
fields
{
field(1; "Entry No."; Integer)
{
AutoIncrement = true;
}
field(2; Payload; Text[250])
{
}
}
keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}
codeunit 50112 "Queued Export Worker Good"
{
TableNo = "Job Queue Entry";
trigger OnRun()
var
QueuedExport: Record "Queued Export Good";
Client: HttpClient;
Content: HttpContent;
ContentHeaders: HttpHeaders;
JsonPayload: JsonObject;
RequestBody: Text;
Response: HttpResponseMessage;
begin
if not QueuedExport.FindFirst() then
exit;
JsonPayload.Add('idempotencyKey', Format(QueuedExport.SystemId));
JsonPayload.Add('payload', QueuedExport.Payload);
JsonPayload.WriteTo(RequestBody);
Content.WriteFrom(RequestBody);
Content.GetHeaders(ContentHeaders);
ContentHeaders.Clear();
ContentHeaders.Add('Content-Type', 'application/json');
Client.Post('https://example.local/exports', Content, Response);
if not Response.IsSuccessStatusCode() then
Error('Export failed with HTTP status %1.', Response.HttpStatusCode());
// The external service must atomically create a record only when idempotencyKey
// does not exist. When the key already exists, it must return the existing record
// without repeating the side effect.
UpdateLocalStatus();
QueuedExport.Delete();
end;
local procedure UpdateLocalStatus()
begin
end;
}

View file

@ -0,0 +1,30 @@
---
bc-version: [all]
domain: performance
keywords: [job-queue, idempotency, retry, outbox, httpclient, external-effect]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Job queue external effects must be idempotent
> Contributions welcome — open a PR to refine or extend this article.
## Description
A job queue handler can successfully create something in an external system and then fail while updating Business Central. Business Central rolls back its database changes and retries the queued work, but it cannot roll back the external request. Without a way for the external system to recognize the repeated request, the retry can create a duplicate shipment, payment, notification, or other side effect.
## Best Practice
Use a stable request ID that exists before the job queue processes the outbox row. For example, include the outbox record's `SystemId` as an `idempotencyKey` value in the JSON body of every POST attempt. The external service must enforce uniqueness on that value: when it receives the key again, it returns the existing record instead of creating another one. Delete the outbox row only after the external call and all required local updates succeed.
A `Processed` flag set after the external call does not solve this failure window. If a later AL error rolls back that flag, the outbox row again looks unprocessed even though the external operation already happened.
See sample: `job-queue-external-effects-must-be-idempotent.good.al`.
## Anti Pattern
Sending a state-changing request from a job queue handler with no stable request ID understood by the external API. Specifically, look for this sequence: read an outbox row, call `HttpClient.Post` or another side-effecting API, update or delete local data, and propagate an error that can cause the same outbox row to be retried. The key may be part of the request body, URI, headers, or an existing business key; a naturally idempotent remote operation is already safe and should not be flagged.
See sample: `job-queue-external-effects-must-be-idempotent.bad.al`.

View file

@ -0,0 +1,17 @@
codeunit 50110 "Job Queue UI Bad"
{
TableNo = "Job Queue Entry";
trigger OnRun()
begin
if not Confirm('Process the queued export now?') then
exit;
ProcessExport(Rec."Parameter String");
Message('The queued export completed.');
end;
local procedure ProcessExport(ParameterString: Text)
begin
end;
}

View file

@ -0,0 +1,14 @@
codeunit 50110 "Job Queue UI Good"
{
TableNo = "Job Queue Entry";
trigger OnRun()
begin
Rec.TestField("Parameter String");
ProcessExport(Rec."Parameter String");
end;
local procedure ProcessExport(ParameterString: Text)
begin
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [job-queue, background-session, guiallowed, confirm, runmodal, client-callback]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Job queue handlers must not require user interaction
> Contributions welcome — open a PR to refine or extend this article.
## Description
A job queue handler runs in a background session with no client UI. Calls that require a client callback, such as `Confirm`, `Page.RunModal`, `Report.RunModal`, upload, or download, can stop the job with a non-retriable callback error. `Message` is suppressed and logged by the server, so it cannot communicate a result to the user who scheduled the job.
## Best Practice
Make a dedicated job queue entry point non-interactive. Validate parameters and data in AL, persist business-visible status when needed, and let failures propagate to the job queue log. If one procedure genuinely serves both foreground and background callers, isolate optional UI-only behavior behind `GuiAllowed`; do not use the guard to silently skip a decision that the operation requires.
See sample: `job-queue-handlers-must-not-require-ui.good.al`.
## Anti Pattern
Calling `Confirm`, `Page.Run`, `Page.RunModal`, `Report.Run`, `Report.RunModal`, `Hyperlink`, `File.Upload`, or `File.Download` from a codeunit run by the job queue. Another signal is using `Message` as the only success or failure notification: no user is attached to receive it.
See sample: `job-queue-handlers-must-not-require-ui.bad.al`.

View file

@ -0,0 +1,23 @@
codeunit 50111 "Job Queue Failure Bad"
{
TableNo = "Job Queue Entry";
trigger OnRun()
begin
if not TryProcessCustomer(Rec."Parameter String") then
exit;
end;
[TryFunction]
local procedure TryProcessCustomer(CustomerNo: Code[20])
var
Customer: Record Customer;
begin
Customer.Get(CustomerNo);
ProcessCustomer(Customer);
end;
local procedure ProcessCustomer(Customer: Record Customer)
begin
end;
}

View file

@ -0,0 +1,16 @@
codeunit 50111 "Job Queue Failure Good"
{
TableNo = "Job Queue Entry";
trigger OnRun()
var
Customer: Record Customer;
begin
Customer.Get(Rec."Parameter String");
ProcessCustomer(Customer);
end;
local procedure ProcessCustomer(Customer: Record Customer)
begin
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [job-queue, error-propagation, tryfunction, retry, dispatcher, job-queue-log]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Job queue handlers must propagate execution failures
> Contributions welcome — open a PR to refine or extend this article.
## Description
The job queue dispatcher can mark an entry as failed, record the error, and apply its configured retry behavior only when the handler terminates with an error. A handler that catches a failed `TryFunction` or Boolean-returning operation and then returns normally reports success to the dispatcher, even though its work did not complete.
## Best Practice
Let an error that invalidates the whole run propagate out of the job queue entry point. Add context only when it helps an operator diagnose the failure and does not expose sensitive data. Per-item failures may be collected deliberately, but the batch must persist or emit an observable aggregate outcome instead of silently treating incomplete work as success.
See sample: `job-queue-handlers-must-propagate-failures.good.al`.
## Anti Pattern
Calling a `TryFunction`, `Codeunit.Run`, or another Boolean-returning operation from a job queue handler and using `exit` or normal fall-through on failure without recording an intentional partial-success outcome. The dispatcher sees a successful return, so the entry's status and log do not represent the failed work and configured retries are not applied.
See sample: `job-queue-handlers-must-propagate-failures.bad.al`.

View file

@ -0,0 +1,18 @@
codeunit 50114 "Job Queue On Hold Bad"
{
TableNo = "Job Queue Entry";
trigger OnRun()
begin
repeat
if not ProcessNextBatch() then
exit;
Rec.Get(Rec.ID);
until Rec.Status = Rec.Status::"On Hold";
end;
local procedure ProcessNextBatch(): Boolean
begin
exit(false);
end;
}

View file

@ -0,0 +1,50 @@
table 50114 "Job Cancellation Control"
{
DataClassification = SystemMetadata;
fields
{
field(1; "Job Queue Entry ID"; Guid)
{
}
field(2; "Stop Requested"; Boolean)
{
}
}
keys
{
key(PK; "Job Queue Entry ID")
{
Clustered = true;
}
}
}
codeunit 50114 "Job Queue On Hold Good"
{
TableNo = "Job Queue Entry";
trigger OnRun()
begin
repeat
if not ProcessNextBatch() then
exit;
until IsStopRequested(Rec.ID);
end;
local procedure IsStopRequested(JobQueueEntryId: Guid): Boolean
var
JobCancellationControl: Record "Job Cancellation Control";
begin
if not JobCancellationControl.Get(JobQueueEntryId) then
exit(false);
exit(JobCancellationControl."Stop Requested");
end;
local procedure ProcessNextBatch(): Boolean
begin
exit(false);
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [job-queue, on-hold, cancellation, in-process, long-running, stop-request]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Putting a job queue entry on hold does not stop its current run
> Contributions welcome — open a PR to refine or extend this article.
## Description
The On Hold status prevents a job queue entry from starting again, but it does not cancel a run that is already in process. A long-running handler continues until it completes, fails, reaches a cancellation point implemented by the application, or its session is stopped externally.
## Best Practice
Use On Hold to pause future scheduling. When a long-running operation must support graceful cancellation, store a separate application-owned stop request and check it between bounded units of work. Exit only at a point where completed work and the checkpoint are consistent; use administrative session termination only when graceful cancellation is impossible.
See sample: `job-queue-on-hold-does-not-stop-running-work.good.al`.
## Anti Pattern
Polling the job queue entry's Status field from inside its handler and expecting a change to On Hold to cancel the active run. The status controls scheduling, not cooperative cancellation, so the handler can continue processing despite the operator's action.
See sample: `job-queue-on-hold-does-not-stop-running-work.bad.al`.

View file

@ -6,8 +6,8 @@ codeunit 50100 "Item Reindex Queue"
ReindexQueue: Codeunit "Reindex Queue";
begin
// Only the primary key is used in the loop body; load nothing else.
Item.SetLoadFields("No.");
Item.SetRange("Item Category Code", CategoryCode);
Item.SetLoadFields("No.");
if Item.FindSet() then
repeat

View file

@ -0,0 +1,15 @@
codeunit 50100 "Login Subscriber IO Bad"
{
[EventSubscriber(ObjectType::Codeunit, Codeunit::"System Initialization", OnAfterLogin, '', false, false)]
local procedure OnAfterLogin()
var
Client: HttpClient;
Response: HttpResponseMessage;
GLEntry: Record "G/L Entry";
begin
// Blocks UI, API, and job-queue session creation until HTTP and SQL finish.
Client.Get('https://example.local/warmup', Response);
GLEntry.SetLoadFields("Entry No.");
if GLEntry.FindLast() then;
end;
}

View file

@ -0,0 +1,30 @@
codeunit 50100 "Login Subscriber IO Good"
{
[EventSubscriber(ObjectType::Codeunit, Codeunit::"System Initialization", OnAfterLogin, '', false, false)]
local procedure OnAfterLogin()
var
TaskId: Guid;
StoredId: Text;
begin
// Guard to interactive sessions only; background task sessions also raise OnAfterLogin.
if not (Session.CurrentClientType() in [ClientType::Web, ClientType::Windows, ClientType::Desktop, ClientType::Tablet, ClientType::Phone]) then
exit;
// Idempotent: TaskExists requires the GUID returned by CreateTask, stored across logins.
if IsolatedStorage.Get('LoginSyncTaskId', DataScope::Company, StoredId) then
if Evaluate(TaskId, StoredId) then
if TaskScheduler.TaskExists(TaskId) then
exit;
TaskId := TaskScheduler.CreateTask(Codeunit::"Login Subscriber IO Work", 0, true, CompanyName(), CurrentDateTime() + 60000);
IsolatedStorage.Set('LoginSyncTaskId', Format(TaskId), DataScope::Company);
end;
}
codeunit 50101 "Login Subscriber IO Work"
{
trigger OnRun()
begin
// Isolated from session creation: outbound I/O is safe here.
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [oncompanyopen, onafterlogin, session-start, httpclient, subscriber, login]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Session-open subscribers must not do I/O
> Contributions welcome — open a PR to refine or extend this article.
## Description
`OnCompanyOpen`, `OnCompanyOpenCompleted`, and `System Initialization`.OnAfterLogin run while the session is being created. The platform waits until every subscriber returns before the UI, an API call, or a background session can proceed. `HttpClient` or a heavy `FindSet` here delays **every** session type, not just the user who "opened the company". Agents still put warmup sync, license checks, and HTTP probes on these events because they look like an application startup hook.
## Best Practice
Keep company-open subscribers to cheap in-memory work: set a flag, enqueue a job-queue entry, or `TaskScheduler.CreateTask`. Perform HTTP and large SQL after the session is running, in that background work. When the subscriber can run repeatedly, use `store-scheduled-task-id-to-avoid-duplicate-tasks.md` to avoid creating the same logical task more than once.
See sample: `oncompanyopen-subscribers-must-not-do-io.good.al`.
## Anti Pattern
An `OnAfterLogin` / `OnCompanyOpenCompleted` subscriber that calls `HttpClient` or scans a ledger. Detection signal: `HttpClient`, `FindSet`, or `CalcFields` inside a subscriber bound to those events.
See sample: `oncompanyopen-subscribers-must-not-do-io.bad.al`.

View file

@ -0,0 +1,31 @@
page 50100 "Cue Background Task Bad"
{
PageType = CardPart;
ApplicationArea = All;
layout
{
area(content)
{
cuegroup(Group)
{
field(OpenOrders; OpenOrderCount)
{
Caption = 'Open Sales Orders';
}
}
}
}
var
OpenOrderCount: Integer;
trigger OnOpenPage()
var
SalesHeader: Record "Sales Header";
begin
// Blocks Role Center render on an exact count of sales headers.
SalesHeader.SetRange("Document Type", SalesHeader."Document Type"::Order);
OpenOrderCount := SalesHeader.Count();
end;
}

View file

@ -0,0 +1,49 @@
page 50100 "Cue Background Task Good"
{
PageType = CardPart;
ApplicationArea = All;
layout
{
area(content)
{
cuegroup(Group)
{
field(OpenOrders; OpenOrderCount)
{
Caption = 'Open Sales Orders';
}
}
}
}
var
OpenOrderCount: Integer;
TaskId: Integer;
trigger OnAfterGetCurrRecord()
var
Args: Dictionary of [Text, Text];
begin
CurrPage.EnqueueBackgroundTask(TaskId, Codeunit::"Cue Open Order Count", Args);
end;
trigger OnPageBackgroundTaskCompleted(CompletedTaskId: Integer; Results: Dictionary of [Text, Text])
begin
if Results.ContainsKey('Count') then
Evaluate(OpenOrderCount, Results.Get('Count'));
end;
}
codeunit 50100 "Cue Open Order Count"
{
trigger OnRun()
var
SalesHeader: Record "Sales Header";
Results: Dictionary of [Text, Text];
begin
SalesHeader.SetRange("Document Type", SalesHeader."Document Type"::Order);
Results.Add('Count', Format(SalesHeader.CountApprox()));
Page.SetBackgroundTaskResult(Results);
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [15..]
domain: performance
keywords: [page-background-task, cue, rolecenter, enqueuebackgroundtask, ui-thread]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Calculate expensive cues on a page background task
> Contributions welcome — open a PR to refine or extend this article.
## Description
Role-center cues and CardPart totals that run `CalcFields`, scans, or HTTP on the UI thread freeze the shell until they finish. Page background tasks exist to return the page immediately and fill the number later. Enqueue mechanics, cancellation, and the read-only child session are covered in `microsoft/knowledge/ui/page-background-tasks.md`. This file is the performance trigger: a cue whose value is not needed to *open* the page must not run on the render path.
## Best Practice
Bind the cue to a page variable, enqueue a read-only calculation from `OnAfterGetCurrRecord` (not `OnAfterGetRecord` on a list), and apply the result in `OnPageBackgroundTaskCompleted`. Show a placeholder until then.
See sample: `page-background-tasks-for-expensive-cues.good.al`.
## Anti Pattern
`CalcFields` or a ledger `Count` in `OnOpenPage` / `OnAfterGetCurrRecord` of a CueGroup CardPart with no background task. The Role Center waits on SQL the user may never look at.
See sample: `page-background-tasks-for-expensive-cues.bad.al`.

View file

@ -0,0 +1,20 @@
codeunit 50100 "Pass Var Enumerator Bad"
{
procedure ListUsCustomerCities()
var
Customer: Record Customer;
begin
Customer.SetLoadFields(Name);
Customer.SetRange("Country/Region Code", 'US');
if Customer.FindSet() then
repeat
// By-value copy: JIT on City does not update the enumerator.
Message(Customer.Name + ' ' + CityOf(Customer));
until Customer.Next() = 0;
end;
local procedure CityOf(Customer: Record Customer): Text
begin
exit(Customer.City);
end;
}

View file

@ -0,0 +1,21 @@
codeunit 50100 "Pass Var Enumerator Good"
{
procedure ListUsCustomerCities()
var
Customer: Record Customer;
begin
Customer.SetLoadFields(Name);
Customer.SetRange("Country/Region Code", 'US');
if Customer.FindSet() then
repeat
EnsureCityLoaded(Customer);
Message(Customer.Name + ' ' + Customer.City);
until Customer.Next() = 0;
end;
local procedure EnsureCityLoaded(var Customer: Record Customer)
begin
if not Customer.AreFieldsLoaded(Customer.City) then
Customer.LoadFields(Customer.City);
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [setloadfields, jit-load, enumerator, var-parameter, pass-by-value, next]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Pass the iterated record var so a JIT load updates the enumerator
> Contributions welcome — open a PR to refine or extend this article.
## Description
A `FindSet`/`Next` loop builds an enumerator from the fields selected for load. Accessing an unloaded field triggers a JIT load. When the record is passed **by value**, the copy does not share that enumerator: the JIT loads the copy and leaves the enumerator unchanged, so **every later `Next()` JIT-loads again**. Passing `var` lets the first JIT update the enumerator. `AddLoadFields` on the original record before a by-value call is the other fix. This is independent of whether `SetLoadFields` was ordered before filters.
## Best Practice
Helpers that read extra fields on an in-flight iterator must take the record as `var`, or the caller must `AddLoadFields` those fields before the loop. Prefer declaring the extra fields up front so no JIT is needed.
See sample: `pass-var-record-to-preserve-partial-load-enumerator.good.al`.
## Anti Pattern
A `SetLoadFields` loop that passes the iterator by value into a helper which then reads a field that was not loaded. The first row pays one JIT; every subsequent row pays it again because the enumerator never learned the extra field.
See sample: `pass-var-record-to-preserve-partial-load-enumerator.bad.al`.

View file

@ -15,12 +15,12 @@ application-area: [all]
## Best Practice
Use `ModifyAll` when the loop directly assigns the same value, does not call `Validate`, needs no per-row calculation, and does not depend on `OnModify` unless the equivalent `RunTrigger` value is supplied. Check whether table-extension triggers, event subscribers, global triggers, or media fields force row-by-row fallback (see `triggers-and-media-field-regress-modifyall.md`).
Use `ModifyAll` when the loop directly assigns the same value, does not call `Validate`, needs no per-row calculation, and does not depend on `OnModify` unless the equivalent `RunTrigger` value is supplied. Check whether table trigger code, related subscribers, security filtering, `Media`/`MediaSet`, or companion fields force row-by-row fallback (see `triggers-and-media-field-regress-modifyall.md`). A visible loop for progress UX is acceptable only when evidence shows the equivalent bulk call already executes as individual operations and the loop preserves trigger and business semantics.
See sample: `prefer-modifyall-over-per-row-modify.good.al`.
## Anti Pattern
A loop that only assigns a constant and calls `Modify(false)` on a field with no validation side effects. Conversely, replacing `Validate(Field, Value); Modify(true)` with `ModifyAll(Field, Value)` is also an anti-pattern because it silently drops field validation and may drop table-trigger behavior.
A loop that only assigns a constant and calls `Modify(false)` on a field with no validation side effects or bulk fallback condition. A progress dialog alone does not exempt this loop. Conversely, replacing `Validate(Field, Value); Modify(true)` with `ModifyAll(Field, Value)` is also an anti-pattern because it silently drops field validation and may drop table-trigger behavior.
See sample: `prefer-modifyall-over-per-row-modify.bad.al`.

View file

@ -0,0 +1,9 @@
tableextension 50100 "G/L Entry Extra Ext" extends "G/L Entry"
{
fields
{
// Stored companion columns are joined on every G/L Entry read.
field(50100; "External Reference"; Text[50]) { }
field(50101; "Integration Payload"; Blob) { }
}
}

View file

@ -0,0 +1,19 @@
table 50100 "G/L Entry Extra"
{
Caption = 'G/L Entry Extra';
DataClassification = CustomerContent;
fields
{
field(1; "Entry No."; Integer)
{
TableRelation = "G/L Entry"."Entry No.";
}
field(2; "External Reference"; Text[50]) { }
}
keys
{
key(PK; "Entry No.") { Clustered = true; }
}
}

View file

@ -0,0 +1,29 @@
---
bc-version: ["23.."]
domain: performance
keywords: [tableextension, companion-table, gl-entry, related-table, flowfield, hot-table]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Prefer a related table over stored fields on hot ledgers
> Contributions welcome — open a PR to refine or extend this article.
## Description
Since v23, all extensions on the same base table share at most one companion-table join, and the platform automatically excludes that join on List, ListPart, and OData pages when partial records are in effect and no extension field is loaded. However, the join is still paid on every posting path and any AL code that accesses an extension field — or that runs without partial-record semantics. On hot tables — G/L Entry, Item Ledger Entry, Cust. Ledger Entry — even a single access per posted row adds up at volume. A related table keyed by the ledger `Entry No.`, optionally surfaced with a FlowField or FactBox, leaves the base read path entirely untouched. Agents extend G/L Entry because it is "where the posting already is".
## Best Practice
Put optional, sparse, or integration attributes in a related table with the ledger entry number as primary key. Show them from a FactBox or a FlowField.
Use a tableextension stored field only when the value must appear as a native list column and is read on almost every access.
See sample: `prefer-related-table-over-extension-on-hot-ledgers.good.al`.
## Anti Pattern
`tableextension` on `"G/L Entry"` (or another posting table) that adds several stored `Text`/`Blob` fields used only by one integration. The companion join is paid on every posting and on any AL code path that loads extension fields, even when those columns are not needed for the current operation.
See sample: `prefer-related-table-over-extension-on-hot-ledgers.bad.al`.

View file

@ -0,0 +1,28 @@
query 50100 "Query Bypass PK Cache Bad Q"
{
QueryType = Normal;
elements
{
dataitem(Customer; Customer)
{
filter(NoFilter; "No.") { }
column(Name; Name) { }
}
}
}
codeunit 50100 "Query Bypass PK Cache Bad"
{
procedure CustomerName(CustomerNo: Code[20]): Text
var
CustomerByNo: Query "Query Bypass PK Cache Bad Q";
begin
// Query Open/Read never hits the server PK cache.
CustomerByNo.SetRange(NoFilter, CustomerNo);
CustomerByNo.Open();
if CustomerByNo.Read() then
exit(CustomerByNo.Name);
CustomerByNo.Close();
end;
}

View file

@ -0,0 +1,12 @@
codeunit 50100 "Query Bypass PK Cache Good"
{
procedure CustomerName(CustomerNo: Code[20]): Text
var
Customer: Record Customer;
begin
// Repeated Get of the same No. is served from the transaction PK cache.
Customer.SetLoadFields(Name);
if Customer.Get(CustomerNo) then
exit(Customer.Name);
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [query, primary-key-cache, get, false-positive, n-plus-one, record-cache]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Query results bypass the primary-key cache
> Contributions welcome — open a PR to refine or extend this article.
## Description
The Business Central server caches primary-key `Get` calls within a transaction. Query objects do not use that cache: every `Open`/`Read` goes to SQL. `avoid-get-inside-loop-on-large-table.md` is right when an unbounded inner `Get`/`FindFirst` joins two large sets. It is wrong as a blanket rewrite of repeated `Get` on the same keys. Replacing a cached `Get` with a Query that re-executes per call can be slower. This file exists so reviewers stop treating every `Get` inside a loop as a Query candidate.
## Best Practice
Keep `Record.Get` for repeated lookups of the same primary keys in one transaction. Use a Query when the work is a true join or aggregation that the record API would express as nested scans. Do not flag a guarded `Get` on a repeating key as an N+1 solely because a Query could express the same columns.
See sample: `query-results-bypass-primary-key-cache.good.al`.
## Anti Pattern
Rewriting a helper that `Get`s Customer by `No.` on every sales line into a Query opened inside that helper. Distinct line customers still need a lookup; repeating customers were already served from the PK cache. The Query pays SQL every time.
See sample: `query-results-bypass-primary-key-cache.bad.al`.

View file

@ -0,0 +1,16 @@
codeunit 50100 "Reset Clears LoadFields Bad"
{
procedure ListUsCustomerNames()
var
Customer: Record Customer;
begin
Customer.SetLoadFields(Name);
// Reset restores a full-row load; the SetLoadFields above is discarded.
Customer.Reset();
Customer.SetRange("Country/Region Code", 'US');
if Customer.FindSet() then
repeat
Message(Customer.Name);
until Customer.Next() = 0;
end;
}

View file

@ -0,0 +1,15 @@
codeunit 50100 "Reset Clears LoadFields Good"
{
procedure ListUsCustomerNames()
var
Customer: Record Customer;
begin
Customer.Reset();
Customer.SetLoadFields(Name);
Customer.SetRange("Country/Region Code", 'US');
if Customer.FindSet() then
repeat
Message(Customer.Name);
until Customer.Next() = 0;
end;
}

View file

@ -0,0 +1,28 @@
---
bc-version: [all]
domain: performance
keywords: [reset, setloadfields, partial-record, load-selection, findset]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Reset and empty SetLoadFields restore a full-row load
> Contributions welcome — open a PR to refine or extend this article.
## Description
`SetLoadFields(...)` sticks to the record variable until something clears it. `Reset()` "changes fields select for loading back to all", and `SetLoadFields()` with no arguments does the same. A later `FindSet` or `Get` then materializes every normal field. Agents often place `SetLoadFields` first, then `Reset` to apply new filters, and assume the partial selection survives. It does not.
## Best Practice
Call `Reset` (or empty `SetLoadFields()`) first when the variable must be reused, then call `SetLoadFields` with the fields the next read actually uses, then apply filters and read. After `Reset`, a new `SetLoadFields` is required; the previous list is gone.
See sample: `reset-clears-partial-record-selection.good.al`.
## Anti Pattern
`SetLoadFields(...)` followed by `Reset()` (or by parameterless `SetLoadFields()`) and then `FindSet` without restoring the load list. The filters look correct; the SQL still selects every column.
See sample: `reset-clears-partial-record-selection.bad.al`.

View file

@ -0,0 +1,16 @@
codeunit 50100 "Skip LoadFields Write Bad"
{
procedure CopyActiveCustomers(var TempCustomer: Record Customer temporary)
var
Customer: Record Customer;
begin
// TransferFields requires all fields; partial load forces JIT per row.
Customer.SetLoadFields("No.", Name);
Customer.SetRange(Blocked, Customer.Blocked::" ");
if Customer.FindSet() then
repeat
TempCustomer.TransferFields(Customer);
TempCustomer.Insert();
until Customer.Next() = 0;
end;
}

View file

@ -0,0 +1,15 @@
codeunit 50100 "Skip LoadFields Write Good"
{
procedure CopyActiveCustomers(var TempCustomer: Record Customer temporary)
var
Customer: Record Customer;
begin
// TransferFields needs all fields; omit SetLoadFields so the initial read loads the full row.
Customer.SetRange(Blocked, Customer.Blocked::" ");
if Customer.FindSet() then
repeat
TempCustomer.TransferFields(Customer);
TempCustomer.Insert();
until Customer.Next() = 0;
end;
}

Some files were not shown because too many files have changed in this diff Show more