Quality rules

485 BCQuality rules

Microsoft's BCQuality knowledge base for AL: each rule with its good and bad examples, the objects it names and the pull requests that changed it. From microsoft/BCQuality under its MIT licence; the rule text is Microsoft's own. Agents: llms.txt.

performance 83

RuleLayerIn short
A FlowField needs a source-table key that covers its CalcFormulamicrosoftA FlowField is computed by SQL on demand.
A page or lookup's effective filter may be defined outside the changed hunkmicrosoftThe effective filter on a drill-down, lookup, or list result set is frequently defined outside any single changed hunk — on the table via a SourceTableView property or a TableRelation, or through SetRange/SetFilter calls in unchanged code that runs before the result is shown.
A primary-key Get() in a per-row helper is not an N+1 to cache manuallymicrosoftThe Business Central server caches primary-key reads within a transaction.
Add trigger-only fields to API pages with AddLoadFields in OnOpenPagemicrosoftAPI and OData pages load only the fields bound to page controls, so a field read only in trigger code triggers JIT loads.
Add trigger-only report fields in OnPreDataItemmicrosoftReport dataitem field selection is calculated at compile time and once per dataitem type during execution.
Admin and migration pages tolerate lower performance disciplinemicrosoftSome pages run rarely and against small datasets, and the upstream guidance explicitly calls for treating them as lower severity.
Aggregate source rows before persisting completed resultsmicrosoftA batch may repeatedly calculate the same group total while inserting and updating persistent working rows, even though only one completed result per group is needed.
AL auto-commits when code execution completesmicrosoftIn AL, write transactions are managed by the runtime, not by the developer.
AL boolean operators do not short-circuitmicrosoftAL 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.
AL methods limited during write transactions: commit before RunModal and Codeunit.RunmicrosoftOnce AL code has written to the database in the current transaction — an Insert, Modify, or Delete with no Commit since — the platform restricts four methods until that transaction is committed.
Apply early-exit guards before calling GetmicrosoftA Get (or any other database call) executed before a guard that may exit the procedure does a round-trip the procedure never uses.
Apply SetRange/SetFilter before iterating, not as an if-test inside the loopmicrosoftA SetRange or SetFilter placed before FindSet narrows the result set at the database.
Avoid cloning records before Modify or Delete in loopsmicrosoftMicrosoft's AL database-method performance guidance states that cloning an iterated record before Modify or Delete restarts the SQL SELECT and issues an extra SQL statement for every row.
Avoid Get / FindFirst inside a loop on a large inner tablemicrosoftA Get or FindFirst against another persistent table inside a loop can produce an N+1 access pattern: one outer query followed by repeated inner lookups.
Avoid growing globals in SingleInstance subscribersmicrosoftA codeunit with SingleInstance = true is allocated once per session and lives until the session ends.
Avoid RecordRef / FieldRef in hot loops when a typed record fitsmicrosoftRecordRef and FieldRef are slower than direct typed record access — the platform resolves the table and field at runtime instead of at compile time.
Avoid repeating validation when its inputs have not changedmicrosoftValidate runs field validation logic, which can invoke subscribers and additional reads or writes even if the assigned value is unchanged.
Batch number-series calls instead of GetNextNo per insertmicrosoftCodeunit "No.
CalcFields in both OnAfterGetRecord and OnAfterGetCurrRecord is not redundantmicrosoftOnAfterGetRecord fires once per row as the page loads records into the view; OnAfterGetCurrRecord fires when a record becomes the active/current record.
Calculate expensive cues on a page background taskmicrosoftRole-center cues and CardPart totals that run CalcFields, scans, or HTTP on the UI thread freeze the shell until they finish.
Choose MaintainSIFTIndex by read-write ratiomicrosoftMaintainSIFTIndex on a key decides whether SQL Server maintains the SIFT indexed view as underlying rows change.
Commit before Codeunit.Run when the caller already holds a write transactionmicrosoftCodeunit.Run cannot nest inside an open write transaction.
Compute data-driven Role Center headlines in the background, not when the page opensmicrosoftCode in a headline part's OnOpenPage, or in a subscriber to an event raised from it, runs every time the Role Center opens.
Database work in OnAfterGetCurrRecord is not a per-row or N+1 costmicrosoftOnAfterGetCurrRecord fires only when the current/active record changes — typically once when the page opens and once each time the user selects a different row — not once for every row rendered in a list.
Design a read-pattern key and verify whether it covers the querymicrosoftA secondary key should serve a particular read, not a list of fields that happen to look important.
Do not call ChangeCompany inside a per-row loopmicrosoftChangeCompany retargets a record variable to another company's data and drops the in-memory caches bound to the previous company.
Do not call CurrPage.Update inside OnAfterGetRecordmicrosoftOnAfterGetRecord on a list already runs once per visible row on scroll and refresh.
Do not call HttpClient inside an open write transactionmicrosoftThe 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.
Do not Commit inside loopsmicrosoftCommit ends the current write transaction.
Do not Get the record the page already loadedmicrosoftA list or card page's OnAfterGetRecord trigger fires *because* the platform has already fetched a row into Rec.
Do not hold locks while waiting for the usermicrosoftA Confirm, StrMenu, or other user prompt issued from inside a write transaction stalls the transaction — and therefore every lock it holds — until the user responds.
Do not LockTable in a read-only proceduremicrosoftLockTable is a transaction-wide signal: from the call onward, every read against that table in the same transaction acquires UPDLOCK.
Do not Modify inside OnAfterGetRecordmicrosoftA list page's OnAfterGetRecord fires once per visible row, every time the user scrolls, sorts, or refreshes.
Document reports should default to a Word layout, not RDLCmicrosoftFor a document report — an invoice, statement, order confirmation, or any report meant to be printed, emailed, or exported as a single-record document — Microsoft's own guidance recommends a Word rendering layout over RDLC: "RDL layouts can result in slower performance with document reports,…
Enforced singleton setup tables need no access optimizationmicrosoftAn access-pattern exemption is valid only for a table whose schema and write paths enforce at most one row for the relevant scope.
FindSet(true) applies UpdLock on the read; the two-parameter form is obsoletemicrosoftFindSet() and FindSet(false) are read-only — no locking.
Guard event subscribers with cheap checks before any database callmicrosoftEvent subscribers fire on every event matching their signature — for OnAfterValidateEvent on a hot field like Sales Line.Quantity, that is every quantity edit by every user.
Guard page trigger work with GuiAllowed for OData and ExcelmicrosoftPages exposed as OData, including Edit in Excel, still run AL page triggers for every row returned.
Hidden page FlowFields still calculate unless visible-only calculation is enabledmicrosoftBy default, a FlowField used directly as a page control's source is calculated when the page loads even when Visible = false or its visibility expression evaluates to false.
IsEmpty immediately before FindSet is an extra round-tripmicrosoftIsEmpty is the right API when the caller only needs existence — see microsoft/knowledge/performance/use-isempty-for-existence-check.md.
Job queue external effects must be idempotentmicrosoftA job queue handler can successfully create something in an external system and then fail while updating Business Central.
Job queue handlers must not require user interactionmicrosoftA job queue handler runs in a background session with no client UI.
Job queue handlers must propagate execution failuresmicrosoftThe 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.
Justify low-selectivity fields in key columnsmicrosoftA Boolean, small Option/Enum, or status field (Processed, Blocked, Status) in a key is a cost that needs a reason.
Keep eligible inserts together instead of re-reading their targetmicrosoftBusiness Central can automatically buffer eligible Insert calls.
Load common fields before branching on casemicrosoftWhen a known input determines which fields a subsequent record read will use, a single SetLoadFields containing every branch's fields loads unnecessary columns.
Load only primary key fields for reference workmicrosoftWork that uses a record only for its identity — passing it to another procedure that will re-fetch what it needs, queueing a key for later processing, running existence checks, or building a reference collection — does not need non-key payload fields.
MaintainSQLIndex = false on a key disables SIFT for FlowFields that depend on itmicrosoftMaintainSQLIndex = false on a key tells the platform not to materialize that key as a SQL index.
Order case branches by frequencymicrosoftAL documentation does not guarantee that a case statement uses a linear comparison strategy, so branch frequency alone is not proof of a performance issue.
Pass false to Insert/Modify/Delete when the table triggers do not need to firemicrosoftInsert(true), Modify(true), and Delete(true) run the table's OnInsert/OnModify/OnDelete trigger; the (false) form skips it.
Pass the iterated record var so a JIT load updates the enumeratormicrosoftA FindSet/Next loop builds an enumerator from the fields selected for load.
Point lookups at a dedicated lookup page, not the full listmicrosoftA TableRelation lookup opens the table's LookupPageId.
Prefer a Dictionary over a temporary table for pure lookupsmicrosoftAn AL Dictionary directly models an unordered unique key-to-value collection.
Prefer a related table over stored fields on hot ledgersmicrosoftSince 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.
Prefer ReadIsolation over LockTable for read-only scenariosmicrosoftWithout read scale-out, LockTable causes subsequent reads of that table in the transaction to use UPDLOCK.
Putting a job queue entry on hold does not stop its current runmicrosoftThe On Hold status prevents a job queue entry from starting again, but it does not cancel a run that is already in process.
Query results bypass the primary-key cachemicrosoftThe Business Central server caches primary-key Get calls within a transaction.
Removing SourceTableTemporary on an API page switches it from in-memory to persistentmicrosoftSourceTableTemporary = true on a page makes the page's record buffer in-memory only — reads and writes do not touch SQL.
Reset and empty SetLoadFields restore a full-row loadmicrosoftSetLoadFields(...) sticks to the record variable until something clears it.
Reuse repeated filtered results within a correct cache scopemicrosoftA loop can ask the same filtered existence or calculation question for many rows sharing a business key, or two phases can ask it for the same rows.
Review overlapping keys as a portfoliomicrosoftAdding a secondary key to a frequently written table maintains another SQL index for every affected write.
Session-open subscribers must not do I/OmicrosoftOnCompanyOpen, OnCompanyOpenCompleted, and System Initialization.OnAfterLogin run while the session is being created.
Set DataAccessIntent ReadOnly on analytical objectsmicrosoftDataAccessIntent was introduced at runtime 5.0 (BC 16) and has no effect in earlier versions.
SetCurrentKey is not a SQL index hint for record readsmicrosoftA common misconception is that SetCurrentKey tells SQL Server which index to use for a filtered FindSet/FindFirst query.
Skip SetLoadFields on write and copy pathsmicrosoftSetLoadFields is a read optimization.
Store the scheduled task ID to avoid duplicate tasksmicrosoftEvery call to TaskScheduler.CreateTask creates a new scheduled task and returns its unique GUID.
Temporary tables avoid SQL I/O, not in-memory workmicrosoftA temporary table stores its rows in Business Central Server memory instead of a physical SQL table.
Triggers, subscribers, and media fields can silently regress ModifyAll / DeleteAllmicrosoftModifyAll and DeleteAll can limit SQL calls, but Microsoft documents that they revert to individual calls when the table has trigger code, related modify/delete/global/database event subscribers, active security filtering, Media or MediaSet fields, or fields added through companion tables.
Use [TryFunction] for error catching, Codeunit.Run for atomic rollbackmicrosoft[TryFunction] lets a caller catch an error, but database changes made before that error are not rolled back.
Use a grouped query for distinct values and duplicate detectionmicrosoftThe AL Record type has no SELECT DISTINCT or GROUP BY ...
Use a job queue category to serialize conflicting jobsmicrosoftDifferent job queue entries can run at the same time.
Use AL TextBuilder for repeated text mutationmicrosoftAL TextBuilder is a reference type intended for modifying text without creating a new Text value for each change.
Use CalcSums for stored-field totals, not as a shortcut for FlowFieldsmicrosoftCalcFields evaluates a FlowField for one record; CalcSums totals stored numeric fields in a filtered source table.
Use case true of for long chains of dependent conditionsmicrosoftBecause 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…
Use Codeunit.Run to bound an atomic sub-operationmicrosoftCodeunit.Run(ID) is the AL-idiomatic way to run a unit of work as an atomic sub-operation with its own transactional boundary.
Use DeleteAll for filtered bulk deletionmicrosoftDeleteAll(false) is eligible for a set-based SQL delete with the record variable's filters applied, but it is not guaranteed to stay one statement.
Use FindSet with repeat..Next; do not pair FindFirst/FindLast/Get with NextmicrosoftTwo CodeCop rules carve out the loop pattern.
Use Get for primary-key lookups without losing filter conditionsmicrosoftGet(...) retrieves a record by primary key, but ignores normal record filters.
Use IsEmpty for existence checks, not Count() or FindFirst()microsoftWhen the caller only needs to know whether any row matches a filter, IsEmpty() is the API designed for the question.
Use ModifyAll only for equivalent bulk assignmentsmicrosoftModifyAll assigns one value to one field across the filtered set.
Use SetAutoCalcFields when each iterated row needs a FlowFieldmicrosoftRecord.SetAutoCalcFields has been available since runtime 1.0 and makes the specified FlowFields calculate as records are retrieved.
Use SetLoadFields to load only the fields the code readsmicrosoftSetLoadFields(...) declares the subset of normal fields the next read should materialize.
Validate on a partial record forces JIT loadsmicrosoftValidate runs the field's OnValidate trigger and TableRelation lookups.

ui 45

RuleLayerIn short
A `DropDown` field remains hidden when its lookup-page control is hiddenmicrosoftA tableextension can append a field to the DropDown field group with addlast, but the client still omits that field when its control on the underlying lookup page has Visible = false.
A notification that must be recalled needs an Id the code can find againmicrosoftNotification.Recall() withdraws the notification whose Id it carries.
A page field bound to a table field inherits that field's ToolTipmicrosoftStarting with BC24 (2024 release wave 1), runtime 13.0 supports ToolTip on table fields.
A wizard collects its input in a temporary source table and saves on FinishmicrosoftAn assisted setup guide is a NavigatePage that the user can leave at any step.
An app has at most one primary setup object in Guided ExperiencemicrosoftAn extension tells Business Central which setup objects it brings by adding them as guided experience items through codeunit Guided Experience.
Control add-in accessibility is the developer's responsibilitymicrosoftWhen a developer builds a JavaScript control add-in, they bypass the Business Central framework's built-in accessibility support and take full responsibility for the accessibility of the rendered HTML, JavaScript, and CSS.
Control add-ins cannot use BC color tokens or themingmicrosoftA JavaScript control add-in has no access to Business Central's color tokens or theming system.
Cosmetic styles need no textual contextmicrosoftA field's Style property controls text formatting.
Default descending sort on historical pagesmicrosoftHistorical list pages should default to showing the newest records first.
Define per-record page outputs on every control-flow pathmicrosoftA global page variable belongs to the page instance, whereas Rec changes as OnAfterGetRecord processes records.
Expose setup that lives on a base page through a codeunitmicrosoftGuided experience items carry the ID of the extension that registered them, which is how Business Central lists the setup an app brings and runs it from Extension Management.
Filter ListPart FactBoxes With SubPageLink To The Parent RecordmicrosoftA FactBox is a page part that surfaces related data beside the main record so users avoid navigating away.
Gate Role Center content by permission with AccessByPermissionmicrosoftA page of type RoleCenter cannot have triggers (AL0378, error) or procedures (AL0569, warning that will become an error), and the AL compiler applies both rules to a pageextension whose target is a Role Center.
Grid and fixed-layout data-table heuristicmicrosoftBusiness Central renders grid() and fixed() layouts in two modes.
Group caption quality is not an accessibility issuemicrosoftGroup captions affect page organization, but missing, generic, or duplicate group captions are not accessibility violations per the BC accessibility rules.
Group ShowCaption = false outside grid/fixed is a layout choicemicrosoftIn a standard Card or Document page, a group with ShowCaption = false is a layout choice, not an accessibility violation.
Group-labeled first child exceptionmicrosoftShowCaption = false is acceptable on an editable field only when all of the following conditions are met:
Layout-table grids with visible captions are validmicrosoftA grid or fixed layout that does not meet all three data-table conditions renders as a layout table.
Load packaged control add-in resources with credentialed AJAXmicrosoftJavaScript in a Business Central control add-in can load a static resource from its extension package with AJAX, but the request needs the Business Central context and cookies.
Mark code-required page fields with ShowMandatorymicrosoftShowMandatory draws the red asterisk on a page field and, per the platform documentation, enforces no validation.
Nested grids are not supportedmicrosoftA grid nested inside another grid is not a supported pattern in Business Central.
Offload Slow Read-Only Page Calculations To Background TasksmicrosoftPages that compute statistics, aggregates, or external lookups inline block the page from rendering until the calculation finishes, producing a visible freeze on FactBoxes, cue tiles, and calculated fields.
OnDrillDown on non-editable fields renders as a linkmicrosoftThe Business Central client renders non-editable fields that have an OnDrillDown trigger as HTML <a> (anchor) elements.
Open documents from a mixed-type list through Page ManagementmicrosoftSome tables back several document pages, chosen by a type field.
Page client-expression properties must not use an `in [...]` listmicrosoftEnabled, Visible, Editable, and StyleExpr on page controls (the list is not exhaustive; HideValue is rejected the same way) can be bound to a client expression instead of a literal.
Pages must match one of Business Central's page-type conventionsmicrosoftBusiness Central's page types — RoleCenter, Card, List, CardPart, ListPart, Worksheet, Document, ListPlus, plus system dialog/special types such as NavigatePage, ConfirmationDialog, StandardDialog, HeadlinePart, and API (a selected list of conventional types this article covers design conventions…
Preserve list scope after `SetSelectionFilter`microsoftCurrPage.SetSelectionFilter(Rec) behaves differently depending on whether the user explicitly multi-selected rows.
Promote Actions With The Modern `actionref` Syntax, Never The Legacy `Promoted` PropertiesmicrosoftBusiness Central 2022 release wave 2 (v21) introduced the area(Promoted) block with actionref as the way to promote page actions, separating an action's definition from its promotion.
Register an assisted setup guide on every `OnRegisterAssistedSetup` eventmicrosoftThe Assisted Setup page lists the guides that are registered as guided experience items.
Semantic styles in a cuegroup are auto-labeledmicrosoftFields inside a cuegroup render as cue tiles.
Semantic styles need independent textual meaningmicrosoftThree Style values carry semantic meaning through color and must be backed by text that conveys the same meaning:
Sentence-phrase captions use sentence case, not title casemicrosoftBusiness Central caption capitalization depends on whether the caption reads as a noun phrase or a sentence/verb phrase.
Serialize control add-in AL calls and keep payloads smallmicrosoftInvokeExtensibilityMethod crosses from a control add-in into the Business Central service.
Set Field Importance To Drive FastTab Progressive DisclosuremicrosoftA FastTab field's Importance property controls whether the field is visible immediately, hidden behind "Show more", or surfaced on the collapsed FastTab header summary line.
ShowCaption = false on non-editable fieldsmicrosoftWhen a field is explicitly non-editable (Editable = false), it serves as content rather than as a form field.
ShowCaption in a PromptDialog prompt areamicrosoftOn PageType = PromptDialog pages, input fields inside area(Prompt) are labeled by the dialog's heading — the page Caption.
ShowCaption inside a repeater is harmlessmicrosoftFields inside a repeater() control are labeled by their column headers, not by their own captions.
ShowCaption on editable fieldsmicrosoftShowCaption must remain true (the default) on editable fields unless the field matches one of the officially supported "magic patterns".
Standalone content in a layout-table gridmicrosoftA non-editable field with ShowCaption = false is acceptable inside a layout-table grid only when the field is standalone content — it displays a value that is meaningful on its own (for example a status message or a description) and is not intended to label or be labeled by another field in the…
StyleExpr: Boolean toggle vs Text variablemicrosoftStyleExpr on a page field serves two distinct purposes depending on its type:
Tabular intent requires data-table conditionsmicrosoftThe most common accessibility bug in grid layouts is partially following the data-table conventions.
Use `UpdatePropagation = Both` when line edits must refresh the main pagemicrosoftA page part does not automatically refresh its parent page when the subpage changes.
Use Standard Promoted Action Group Names And PlacementsmicrosoftBusiness Central ships a fixed vocabulary of promoted action groups, and users build muscle memory around where each kind of action lives.
Validate request-page input in OnQueryClosePage, not only in OnPreReportmicrosoftOnPreReport runs after the request page has closed and before the data items are processed.
Wizard navigation actions need `InFooterBar` and the standard imagesmicrosoftA page with PageType = NavigatePage is a wizard: it has no action bar, and the user moves through it with Back, Next, and Finish buttons at the bottom.

style 41

RuleLayerIn short
`APIVersion` must follow the pattern `vX.Y` (or `beta`)microsoftThe APIVersion property on an API page is part of the public URL path: /api/<publisher>/<group>/<version>/<entitySetName>.
`case` action goes on the line after the possibilitymicrosoftIn an AL case statement, the action for each label is written on the line that follows the label, not on the same line.
`EntityName` is singular; `EntitySetName` is pluralmicrosoftEntityName and EntitySetName on an API page are the two halves of the OData naming contract.
`GenerateCaptions` supplies captions for objects that declare nonemicrosoftThe GenerateCaptions compiler feature in app.json generates a caption from the object name for pages, tables, reports, XMLports, and request pages that have no Caption or CaptionML of their own, and writes those captions to the XLIFF file so they can be translated.
`ML` properties and `TextConst` are not exported to the XLIFF filemicrosoftThe generated XLIFF file contains the strings of Caption, ToolTip, and the other label properties, of Label variables, and of report labels.
A `var` parameter must be called with a variable, never a literal or expressionmicrosoftWhen a procedure declares a parameter with var, that parameter is passed by reference: the callee writes back into the caller's own memory location.
A fixed set of named choices must use Enum, not a raw IntegermicrosoftWhen a variable or field represents a fixed set of named, mutually exclusive states — a difficulty level, a document type, a processing status — it should be typed as Enum (or Option when extending an object that still uses the legacy type).
A new procedure that changes the page's current record should take it as `var Record`microsoftAL passes parameters by value unless they are declared var, and a by-value Record parameter is a copy: changes the procedure makes "affect only the copy, not the variable itself" (Working with AL methods).
A page or view name must describe the table it showsmicrosoftA page (or filtered page View) whose name references one entity but whose SourceTable is a different entity misleads every consumer of the object's metadata.
Add XML documentation to public procedures on library/API codeunitsmicrosoftXML documentation comments (/// <summary>…</summary>, /// <param>…</param>, /// <returns>…</returns>) are expected on procedures that form the public surface of a library — codeunits intended to be called from outside the current app: System App modules, AppSource library codeunits, Access =…
API pages use camelCase, alphanumeric-only values for API propertiesmicrosoftAPI pages — pages declared with PageType = API — surface as OData/JSON endpoints.
Binary yes/no choices must be typed as Boolean, not Option or IntegermicrosoftWhen a field or variable represents a genuine true/false state — yes/no, on/off, active/inactive, blocked/not blocked — it should be typed Boolean.
Build links into the current environment's client with GetUrl, not a hand-written URLmicrosoftThis applies only to links that open a page, report, or record in the environment the code runs in.
Call objects by name, not by numeric IDmicrosoftPage.RunModal, Report.Run, Codeunit.Run, and the Page::, Report::, Codeunit::, Table::, XmlPort:: selectors accept either a numeric ID or a named alias.
Comments must not restate what the code already showsmicrosoftA comment above nearly every statement that just narrates what the statement already says (// Validate the customer number above SalesHeader.Validate("Sell-to Customer No.", CustomerNo)) adds noise without adding information.
Document each Label placeholder with the Comment parametermicrosoftLabel and TextConst strings that contain placeholders (%1, %2, …) need a Comment parameter that names what each placeholder is.
Incremental build and RAD publishing ignore translationsmicrosoftTwo development-time publishing modes leave translations out even when "features": [ "TranslationFile" ] is set in app.json and the per-language XLIFF files are correct.
Insert the product name with `ProductName`, not as literal text in a messagemicrosoftMessages, confirmations and errors sometimes name the product ("Welcome to Business Central", "This feature requires Dynamics 365 Business Central").
Intrinsic AL function calls use modern casing, not legacy ALL-CAPSmicrosoftAL is case-insensitive, so MESSAGE(...), ERROR(...), CONFIRM(...), and STRSUBSTNO(...) compile and run identically to Message(...), Error(...), Confirm(...), and StrSubstNo(...).
Keep business logic out of page objectsmicrosoftA page procedure that persists a business mutation directly (Rec.Modify() outside the standard record-bound save, or a cross-entry-point business rule implemented only in a page trigger) is an architecture violation even when it compiles: the rule only applies when a user opens that specific page,…
Keep object names within the 30-character platform limitmicrosoftBusiness Central object names — for tables, pages, codeunits, reports, queries, XML ports, enums, and permission sets — are limited to 30 characters in total.
Name AL source files `<ObjectName>.<ObjectType>.al`microsoftEach AL source file holds a single object, and the file name is expected to be of the form <ObjectName>.<ObjectType>.al — CustomerCard.Page.al, PostSalesInvoice.Codeunit.al, NoSeriesTests.Codeunit.al, SalesHeader.TableExt.al.
Omit `else` when the `then` branch ends with `exit`, `break`, `skip`, `quit`, or `error`microsoftWhen the then branch of an if ends in a terminating statement — exit, break, skip, quit, or error — the else branch becomes the natural fall-through.
Organize AL source by business feature, not object typemicrosoftFolder structure inside an AL app has no effect on compilation or runtime behavior — this is a repository-organization convention, not a platform requirement, and different projects reasonably choose differently.
Page fields can inherit their source table field's `Caption`microsoftA page field bound to a table field inherits the source field's Caption unless the page overrides it.
Page fields need an explicit or inherited `ToolTip` (CodeCop AA0218)microsoftUser-facing page fields need tooltip text, but it does not have to be declared on each page control.
Parse DateFormula constants with language-independent inputmicrosoftA DateFormula stores a formula in a language-independent representation, but Evaluate must first interpret its text input.
Pass date operands to SetFilter as replacement values, not as text in the filter stringmicrosoftThe String argument of SetFilter is parsed at run time as a filter expression.
Pass parameters directly to `Error()`, do not wrap with `StrSubstNo`microsoftError() accepts a format string and a variable number of arguments — Error(SomeLabelErr, Arg1, Arg2).
Prefix temporary record variables with `Temp`microsoftA Record variable declared with the temporary modifier behaves nothing like a normal record variable: it never touches the database, holds rows only for the lifetime of the variable, and is not visible to filters or queries on the underlying table.
Procedure-local Labels are validmicrosoftThe AL language supports Label variables at both object and procedure scope.
Renaming an object or member changes its translation IDsmicrosoftEach <trans-unit> in an XLIFF file has an id that identifies the object or object member that defines the text.
Resolve a namespace from the referenced object's source or symbols, never by guessingmicrosoftSince Business Central 2024 release wave 1, Microsoft's own objects are organized under a deep Microsoft.* namespace tree that has been renamed and restructured repeatedly.
Set `DelayedInsert = true` on API pagesmicrosoftOn a normal page, DelayedInsert = false is the default: the record is inserted into the table as soon as the user enters the first field, and subsequent fields are written via Modify triggers.
Set `Locked = true` on Labels that must not be translatedmicrosoftA Label is by default surfaced to translators and rewritten per locale.
The generated XLIFF file is rewritten on every buildmicrosoftWith "features": [ "TranslationFile" ] in app.json, each build writes a .xlf file into the Translations folder that contains every label, label property, and report label of the extension as <source> elements.
Translate another extension with its own translation IDsmicrosoftAn extension can ship translations for a different extension, for example a language app that translates the Base Application.
Use `AboutTitle` and `AboutText` to surface teaching tips on top-level pagesmicrosoftThe AboutTitle and AboutText properties on a page render a teaching tip — an onboarding callout that appears the first time a user opens the page.
Use FieldCaption/TableCaption (not FieldName/TableName) in user-facing textmicrosoftFieldName and TableName return the developer-facing identifier of a field or table — a fixed English string used in metadata and in code.
Write AL Build Artifacts to an Intentional Output LocationmicrosoftAn AL project's compiled .app file can be written to the project root by default, and current tooling explicitly supports choosing a different destination instead — ALTool's --outfolder option and the al_build agent tool's outputPath parameter both exist for this.
Write AL Identifiers in English OnlymicrosoftAll AL identifiers — variables, procedures, parameters, fields, object names, enum values, and label identifiers — must be written in English, regardless of the developer's native language.

data-modeling 38

RuleLayerIn short
`Round` direction symbols follow magnitude, not mathematical orderingmicrosoftAL's Round(Number, Precision, Direction) uses '>' to round away from zero and '<' to round toward zero.
`ValidateTableRelation = false` suppresses rename propagation, not just input validationmicrosoftRenaming a record updates it in all other locations that reference it through a TableRelation, with no code.
`xRec` is a before-image in `OnRename` and `OnDelete`, but mirrors `Rec` in `OnInsert` and `OnModify` from codemicrosoftxRec 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"*.
A document's own Print/Email actions call Report Selections directly; Document Sending Profile is scoped to Post-and-Sendmicrosofttable 60 "Document Sending Profile" is not a general gateway for every print/email path — it exists specifically for the combined Post and Send action: "You can set each customer up with a preferred method of sending sales documents, so that you do not have to select a sending option every time…
A master table's `No.` primary key comes from a number series in `OnInsert`microsoftIn Business Central, a master table (Customer, Vendor, Item, and any custom equivalent) uses a single primary-key field named No.
A new price source needs both a calculation candidate and a recalculation triggermicrosoftMaking a custom field usable as a price source on a sales line is two separate, independent pieces of wiring, and doing only one produces a line that looks like it's using the new source without ever actually being priced by it.
A setup table is a singleton: one blank-keyed row, no insert or deletemicrosoftAn application-area setup table (Sales & Receivables Setup, Inventory Setup, and any custom * Setup) holds exactly one record per company.
A table that owns dependent records must delete them in `OnDelete`microsoftTableRelation looks like referential integrity but only performs lookup and input validation.
A TableRelation field's length must match the related fieldmicrosoftTableRelation points a field at another table, or at a specific field of it with Table.Field.
Activate a new Price Calculation Handler through OnFindSupportedSetup, not just by implementing itmicrosoftenum 7011 "Price Calculation Handler" (implements "Price Calculation") is how a new pricing engine plugs into Business Central — extend the enum with a value pointing at a codeunit that implements the Price Calculation interface.
After Ship-and-Invoice posting, Item Ledger Entry carries the shipment document numbermicrosoftPosting a sales order with both Ship and Invoice in one call creates the Item Ledger Entry during the shipment leg of that combined post, so the entry's Document No.
An insert-only transfer routine may rely on cleanup its caller already performedmicrosoftA 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.
Application code must not change the WorkDatemicrosoftThe work date is a per-user session setting the user controls from the client (the date shown in the top-right corner, used to default posting dates and date filters).
Assign numbers with codeunit `"No. Series"`, not the obsolete `NoSeriesManagement`microsoftSince 2023 release wave 1 (v22) the number-series API is codeunit 310 "No.
Business state must have a domain ownermicrosoftBusiness Central's normal successful finalization removes a non-recurring Job Queue Entry.
Calculate a BLOB field before reading its streammicrosoftGet, Find, FindSet, and Next do not load the content of Blob fields.
Code that calculates a unit price rounds it to the currency's Unit-Amount Rounding PrecisionmicrosoftBusiness Central rounds a unit price only where its own code computes one, above all in the standard price calculation.
Create master records with `Insert(true)` unless the caller does the trigger's work itselfmicrosoftRecord.Insert() does not run OnInsert: RunTrigger defaults to false.
Custom document dispatch must not bypass Report SelectionsmicrosoftA codeunit that hardcodes which report to run (Report.RunModal(MyReportId, ...)), or builds its own email directly, instead of registering the document through table 77 "Report Selections" and calling its own Print/Email procedures, works for the one case it was written for — and loses everything…
Delete master and reference data with `Delete(true)` so the owning table's `OnDelete` decidesmicrosoftRecord.Delete() and Record.DeleteAll() do not run OnDelete unless RunTrigger is true; the default is false.
Design TableRelation branches for additive top-down extensionmicrosoftA tableextension can add to an existing TableRelation, but the combined relation is evaluated top-down after the original value.
Do not use SkipFieldsNotMatchingType to hide required TransferFields mismatchesmicrosoftRecord.TransferFields copies values between fields with matching field numbers.
Enforce `Blocked` where the master is used, not in the master itselfmicrosoftThe Blocked field on a master record (Item, Customer, Resource, or a custom master) is inert data.
Extend Find Entries (Navigate) for new document or transaction tablesmicrosoftpage 344 Navigate (caption "Find entries") lets a user enter a document number and posting date and see, across every document and ledger entry table BC knows about, how many matching records exist — then drill into any of those rows.
Extend Price Source Type and its matching document subset enum together, with the same IDmicrosoftenum 7003 "Price Source Type" (implements "Price Source", "Price Source Group") is the base list of who a price can apply to — Customer, Vendor, Customer Price Group, Campaign, and so on.
Generate report barcodes through the Barcode module, with the production font namemicrosoftBusiness Central's barcode support lives in the System Application's Barcode module (src/System Application/App/Barcode): interface "Barcode Font Provider" / "Barcode Font Provider 2D", enum "Barcode Symbology" / "Barcode Symbology 2D", and built-in implementations (codeunit 9215/9221).
Initialize document defaults in `InitRecord` after assigning the numbermicrosoftBusiness Central document headers assign their number series first and then call an InitRecord procedure that owns the remaining business defaults, such as posting and document dates.
Mirrored TransferFields cascade fields must match type and length exactlymicrosoftMost custom fields genuinely belong to only one table — a status used only before posting, a note relevant only afterwards, whatever the case may be.
Never Change a Published Table's Primary or Clustered Key Field ListmicrosoftOnce a table has shipped — to AppSource, or to any customer environment that has already upgraded onto it — its primary key, and any other key marked Clustered = true, is frozen.
Pictures must be stored in a Media/MediaSet field, not BLOBmicrosoftBLOB is still a valid AL field type for arbitrary binary data, but it is not the right choice for storing pictures or images.
Refresh `Last Date Modified` in both `OnModify` and `OnRename`microsoftMaster tables carry a non-editable Last Date Modified field of type Date.
Register a new document type through Report Selections, and wire it into Document Layouts correctlymicrosoftA custom document that needs printing/emailing should be registered through table 77 "Report Selections".
Sales, purchase, and service line prices follow the header's Prices Including VATmicrosoftLine prices are gross or net depending on the header's Prices Including VAT.
Share MediaSet items with Insert instead of field assignmentmicrosoftMedia and MediaSet fields store IDs that reference tenant media system tables.
Split posting routines into Check Line / Post Line / Post BatchmicrosoftBusiness Central's own journal-based posting routines consistently follow a three-codeunit split, each with one primary responsibility — Codeunit "Gen.
Tables must match one of Business Central's nine table-type conventionsmicrosoftBusiness Central's Base Application follows nine recurring table types — Master, Supplemental, Subsidiary, Ledger, Register, Journal, Document, Document History, and Setup.
TestField a Setup-Table Value Before Using It in a Correctness-Critical BranchmicrosoftA procedure that reads a field from a setup or configuration table inside a branch where the surrounding logic has already decided that value is required needs to guard against it being blank.
Wire dimension support through DimensionManagement, not ad hoc fieldsmicrosoftAdding dimension support to a custom table is not just a matter of adding a Code[20] field, and master tables and document/transactional tables wire into Codeunit "Dimension Management" through two different models — treating them as one mechanism is itself the mistake this article corrects:

security 31

RuleLayerIn short
`MaskType` conceals a value in the UI onlymicrosoftMaskType = Concealed on a table field or page field makes the client display the value masked, with a hide/show icon that lets the user reveal it.
A secret belongs in IsolatedStorage, never in a table fieldmicrosoftAPI keys, OAuth tokens, client secrets, and connection strings must not be stored in an ordinary table Text field — not even on a hidden setup table.
Access Internal is API hygiene, not an authorization boundarymicrosoftAccess = Internal controls compile-time symbol visibility.
AL has no built-in HtmlEncode — encode HTML output by hand or avoid itmicrosoftAL does not ship a built-in HtmlEncode (or equivalent) function.
Avoid wildcard grants in permission setsmicrosoftA permissionset object can grant access object-by-object or with the * wildcard.
Compose permission sets with IncludedPermissionSetsmicrosoftThe IncludedPermissionSets property lets one AL permission set reference another, composing rights out of smaller building blocks.
Do not concatenate external text into a SetFilter expressionmicrosoftThe String argument of SetFilter is a filter expression, not a value.
Do not expose security guards as `var` parameters on IntegrationEventmicrosoftA var parameter on an [IntegrationEvent] is a mutable hook: any subscriber can overwrite the value and the publisher will see the new value when control returns.
Do not grant rights beyond a user's entitlementmicrosoftEntitlements are license-level caps on what a user can access, derived automatically from the BC license tier.
Do not pass credentials or secrets through IntegrationEvent parametersmicrosoft[IntegrationEvent] publishes a hook that any extension can subscribe to.
Every exposed object must belong to a permission setmicrosoftAn object that is reachable from outside the app's own UI is only usable if it is also granted execute access through a permission set.
Filters that restrict what a page shows must not be set in filter group 0microsoftFilter group 0 is the standard group: it holds the filters the user sees and edits in the filter pane.
Grant the minimum InherentPermissions a procedure needsmicrosoft[InherentPermissions(PermissionObjectType::..., ...)] and [InherentEntitlements(Entitlement::...)] are method-level attributes that let a procedure perform an operation on the listed object even when the caller's permission set does not allow it.
Guard bulk operations with IsTemporarymicrosoftAn AL helper that accepts a var Rec: Record X parameter and performs a bulk operation (DeleteAll, ModifyAll, or an unfiltered loop that mutates every record) cannot tell from the signature alone whether the caller passed a temporary buffer or the real table.
Handle free-form input when ValidateTableRelation is falsemicrosoftValidateTableRelation = false intentionally lets a user keep free-form input even when it does not match TableRelation.
On-premises only: protect unavoidable SecretText.Unwrap callsmicrosoftSecretText.Unwrap() is supported only for Business Central on-premises and exists for compatibility.
Pick the right IsolatedStorage DataScope for the secret's lifetimemicrosoftIsolatedStorage read and write methods take a DataScope parameter that decides which slice of storage the value belongs to.
Prefer IsolatedStorage.SetEncrypted over Set for sensitive valuesmicrosoftIsolatedStorage exposes two write entry points: Set stores the value as-is, and SetEncrypted stores it encrypted at rest.
Prefer OAuth2 over API keys for external HTTP callsmicrosoftExternal HTTP integrations from AL can authenticate using OAuth 2.0 (client-credentials for service-to-service, authorization-code for user-delegated), API keys, basic authentication, or credentials in URLs.
Procedures that read or write IsolatedStorage must not be publicmicrosoftIsolatedStorage partitions its data by extension: values written by one extension are unreadable to another.
Procedures that RecordRef.Open a caller-provided table must not be publicmicrosoftWhen a codeunit holds permission to system tables — directly, via a permission set granted at install, or via [InherentPermissions] — and exposes a public procedure that accepts a table number (or a RecordId, from which the table number is derived) and calls RecordRef.Open on it, the procedure…
Protect sensitive data in temporary tablesmicrosoftA temporary record copies data out of the source table into session memory.
Restore the filter group after setting hidden filters, and do not reuse platform groupsmicrosoftFilterGroup(N) changes the current group for every later SetRange/SetFilter on that record variable until it is changed again.
Set secret request URIs on HttpRequestMessagemicrosoftThe secret URI API belongs to HttpRequestMessage, not HttpClient.
Storing GetLastErrorText() in table fields is a privacy finding, not a security findingmicrosoftIt is tempting to flag any code that calls GetLastErrorText() and writes the result into a table field (or displays it to end users) as a security issue, on the assumption that the error text might leak credentials or system internals.
Use [CommitBehavior] to protect an atomic operation from third-party commitsmicrosoft[CommitBehavior(CommitBehavior::Ignore)] and [CommitBehavior(CommitBehavior::Error)] are method-level attributes that restrict what an explicit Commit() does inside the annotated method's scope: Ignore silently discards the call; Error raises a runtime error.
Use indirect permissions when access must be code-mediatedmicrosoftIn a permissionset, uppercase letters (R, I, M, D) grant direct permissions: the assignee can read, insert, modify, or delete the table data through any UI or API surface.
Use SecretStrSubstNo to compose strings that contain secretsmicrosoftSecretStrSubstNo is the secret-preserving counterpart of StrSubstNo.
Use SecretText for credentials, API keys, and tokensmicrosoftSecretText is the AL data type for values that should never appear in a debugger session, in a log, or in a variable watch.
Validate responses from unauthenticated endpoints before trusting themmicrosoftWhen AL calls an external endpoint that does not authenticate *itself* to the client, the response is fully attacker-influenceable — cleartext MITM, a spoofed or compromised host, DNS/redirect games, or simply a misbehaving public service.
Validate URLs that come from table fields before calling themmicrosoftA URL stored in a table field is user-configurable: anyone with write access to the row can change it.

upgrade 27

RuleLayerIn short
`DataTransfer` does not fire validation triggers or event subscribersmicrosoftDataTransfer writes sets directly at the database layer, so row-based triggers and events do not run.
`InitValue` does not back-fill existing rowsmicrosoftInitValue on a field defines the value the platform assigns when a *new* record is inserted.
`ModuleInfo.AppVersion` changes meaning with execution contextmicrosoftModuleInfo.AppVersion() is the installed version during normal operation, the version being installed inside install code, and the target version inside upgrade code.
`OnUpgradePerCompany` / `OnUpgradePerDatabase` should call helpers, not inline logicmicrosoftThe OnUpgradePerCompany and OnUpgradePerDatabase triggers on an upgrade codeunit are dispatch points, not implementation slots.
Add new enum values only at the endmicrosoftAn AL enum is a fixed list of ordinal-named values.
Control upgrade execution with upgrade tags, not version checksmicrosoftEach piece of upgrade logic must run exactly once per company (or database) across the lifetime of an extension.
Detect first install with `DataVersion() = Version.Create('0.0.0.0')`microsoftOn the first install of an extension on a tenant the platform records a zero data version: AppInfo.DataVersion() returns Version.Create('0.0.0.0').
Give every obsolete element a reason and tagmicrosoftAL has two obsoletion mechanisms, depending on the symbol:
Guard every database read in upgrade code with `if`microsoftInside an upgrade codeunit (or any procedure transitively invoked from OnUpgradePerCompany / OnUpgradePerDatabase), an unguarded Record.Get, Record.FindSet, or Record.FindLast raises a runtime error when the row or set is missing.
Hybrid migration codeunits are not standard upgrade codeunitsmicrosoftCodeunits like HybridBC14, HybridSL, HybridGP, and HybridBaseDeployment implement one-time migration paths from a specific source system into Business Central.
Install code does not run during a version upgrademicrosoftAn install codeunit runs when an extension is installed for the first time or an uninstalled version is installed again.
Keep upgrade validation checks boundedmicrosoftTriggers such as OnValidateUpgradePerCompany run on every upgrade pass.
Log telemetry; do not raise errors that block the upgrademicrosoftWhen upgrade code encounters unexpected data — a record it expected to find, a relationship it assumed to be intact — the response is to log telemetry and continue, not to raise an error.
Never nest upgrade tag checks or blend two migrations under one tagmicrosoftUpgrade tag *checks* should stay flat: never nest one tag's existence check inside another tag's guarded body, and never let one tagged procedure quietly perform a second, functionally distinct migration — that turns two upgrade steps into one that can't be tracked, skipped, or fixed…
No external calls inside upgrade codeunitsmicrosoftUpgrade code runs in a constrained execution window: the tenant is mid-upgrade, no users are signed in, and a failure aborts the entire transaction.
ObsoleteReason need not restate the removal version; ObsoleteTag carries itmicrosoftAn obsoleted object, field, key, enum, or enum value carries both ObsoleteReason and ObsoleteTag, and the two properties have different jobs.
Prefer `DataTransfer` for set-based upgrade field updatesmicrosoftDataTransfer performs supported field initialization and field-to-field copies using set-based SQL instead of per-record AL writes.
Primary-key and field-type changes are safe only on tables without existing datamicrosoftPrimary-key changes and field-type changes (for example widening Integer to BigInteger) rewrite the on-disk layout of every row in the table.
Register upgrade tags that must be seeded for new companiesmicrosoftSetUpgradeTag(Tag) directly records a completed per-company upgrade step; HasUpgradeTag(Tag) can then guard that step on later upgrades.
Separate install or upgrade codeunits have no execution ordermicrosoftAn extension can contain multiple Install or Upgrade codeunits, but Business Central does not guarantee the order in which codeunits of the same subtype execute.
Skip non-essential runtime work when `GetExecutionContext() = ExecutionContext::Upgrade`microsoftRuntime procedures (table triggers, install routines, helpers called from many places) sometimes fire during the upgrade window because the upgrade itself touches the data they react to.
Stage obsoletion `Pending → Removed`; write upgrade code on removalmicrosoftObsoleteState has a deliberate two-step lifecycle.
The `version` of a dependency in `app.json` is a minimummicrosoftEach entry in the dependencies list of app.json names another extension by id, name, publisher, and version.
Unreleased schema changes need no upgrade or migration pathmicrosoftUpgrade and migration findings protect data and schema that have already shipped to customers.
Upgrade check triggers do not migrate datamicrosoftOnCheckPreconditionsPerCompany/PerDatabase run before the upgrade to verify that it can start.
Upgrade code must not use ChangeCompanymicrosoftThe platform upgrades each company in its own context: OnUpgradePerCompany (like the other PerCompany upgrade and install triggers) runs once per company, in a separate system session opened for that company, while PerDatabase triggers run in a session that opens no company.
Upgrade logic must live in a codeunit with `Subtype = Upgrade`microsoftA codeunit only participates in the upgrade pipeline when it sets Subtype = Upgrade.

events 25

RuleLayerIn short
Adding a parameter to an event is not a breaking changemicrosoftAdding a parameter to an existing event publisher does not break existing subscribers.
An isolated event's rollback does not undo var parameters or other in-memory statemicrosoftWhen a subscriber to an isolated event fails, the platform rolls back only the Insert, Modify, and Delete calls it made on normal tables.
Avoid loosely typed event parametersmicrosoftPassing RecordRef or xRec as event parameters weakens the contract.
ChangeCompany leaves triggers and trigger-event subscribers running in the calling companymicrosoftChangeCompany redirects the data access of one record variable to another company's table.
Choose static vs manual subscribers deliberately and bind manual ones with BindSubscriptionmicrosoftAn [EventSubscriber] codeunit is static by default (EventSubscriberInstance = StaticAutomatic): it is always bound, so it fires for every raise of the event in every session.
Database trigger setup flags may only be set to truemicrosoftThe OnDatabaseInsert, OnDatabaseModify, OnDatabaseDelete, and OnDatabaseRename events let one subscriber react to writes on any table, receiving the record as a RecordRef.
Declare event publishers local or internalmicrosoftThe access modifier on an [IntegrationEvent] or [BusinessEvent] publisher controls who may *raise* the procedure, not who may *subscribe* to it.
Do not add IsHandled to an existing eventmicrosoftAdding a var IsHandled: Boolean parameter to an event that already shipped without one silently changes the event's purpose — from a plain notification into an overridable seam.
Do not bypass critical operations with IsHandledmicrosoftThe IsHandled override pattern lets a subscriber skip the guarded code entirely.
Do not change shipped event attribute flagsmicrosoftIncludeSender and, on Integration events, GlobalVarAccess have been event-contract flags since runtime 1.0.
Do not publish events inside loopsmicrosoftRaising an event on every iteration of a loop multiplies the cost of every subscriber by the number of records.
Do not raise integration events inside a TryFunction whose result the caller consumesmicrosoftA TryFunction whose caller consumes its Boolean result catches all errors raised during its execution — including errors thrown by event subscribers.
Event parameter additions depend on publisher access, not positionmicrosoftEvent subscribers bind publisher parameters by name and can omit parameters they do not use.
Expose process context through a manually bound flag, not a single-instance booleanmicrosoftWhen 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.
Isolated events are isolated only when no write transaction is openmicrosoftSetting Isolated = true on a BusinessEvent, IntegrationEvent, or InternalEvent (runtime 9.0 / BC20 and later) runs each subscriber in its own transaction: a failing subscriber is rolled back and the next subscriber, then the caller, continue.
Name event parameters without abbreviationsmicrosoftEvent parameter names are part of the public contract a subscriber codes against, so they must be self-explanatory.
Name events by publisher positionmicrosoftAn event name should tell a subscriber where in the publisher the event fires.
Prefer reusing or extending existing eventsmicrosoftBefore adding a publisher, check whether an event already fires at that point in the code.
Prefer this over IncludeSender in new codeunit eventsmicrosoftWhen designing a new publisher, setting IncludeSender to true on [IntegrationEvent] or [BusinessEvent] gives subscribers the publishing object as an implicit sender parameter.
Prefix temporary record event parameters with TempmicrosoftWhen a record passed to an event is a temporary record — an in-memory buffer not persisted to the database — its parameter name must start with Temp.
Preserve OnAfter execution when IsHandled skips the bodymicrosoftA routine that exposes both an OnBefore… event (with var IsHandled) and a paired OnAfter… event has a subtle trap.
Publish thin OnBefore/OnAfter integration events to expose extension pointsmicrosoftA key operation — a posting, release, or validation routine — becomes a hard wall for partners when it ships no integration events: the only way to change it is to overwrite or duplicate the base code.
Reset IsHandled before publishing only when its value can carry overmicrosoftA 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.
Treat local and internal events as subscriber contractsmicrosoftThe local and internal access modifiers on Business and Integration event publishers restrict who can raise the procedure; they do not prevent dependent extensions from subscribing.
Use the IsHandled pattern to make base behaviour overridablemicrosoftAL has no method overriding, so a procedure that runs its body unconditionally cannot be replaced by an extension without editing base code.

testing 21

RuleLayerIn short
Build fixtures with the test Library codeunits, not hand-rolled Init/InsertmicrosoftBC ships a layer of test Library codeunits — LibrarySales, LibraryPurchase, LibraryERM, LibraryInventory, LibraryRandom and many more — whose job is to create valid records.
Commit shared fixture data created inside a lazy Initialize(), or later tests lose itmicrosoftA test method with no [TransactionModel(...)] attribute defaults to AutoCommit (see transactionmodel-attribute-governs-test-transactions.md): a method that completes without error commits automatically at its own boundary, with no explicit Commit() needed.
Compare posted-table license failures with the same-environment baselinemicrosoftA test fixture that directly inserts into a posted or ledger table can fail with Your license does not grant you the following permissions on TableData <table>: Insert when that environment's license allows only indirect insertion through an authorized object.
Configure TestIsolation on the test runnermicrosoftTestIsolation is a property of a Subtype = TestRunner codeunit, not of the test codeunit being executed.
Cover the full precondition chain in GIVEN, not just the primary recordmicrosoftA [GIVEN] block is only correct if it sets up every precondition the code under test actually reads, not just the record the scenario is "about." For most master-data tests, creating the primary record is enough.
Exclude a known-valid TableRelation exception via OnAfterRemoveTableRelationmicrosoftCodeunit 134926 "Table Relation Test" (shipped in BCApps' test app — only consumers that depend on the BC test libraries can subscribe to it) reads Table Relations Metadata tenant-wide across every installed app, not just the current one, and validates each field's type and length against what its…
Generate Test Data Programmatically, Never Assume Existing RecordsmicrosoftA BC test company normally contains initialized system/setup data — an AL test suite should not assume an empty database, but it must be independent of unrelated business records: create the records and setup it owns rather than looking up a specific code, number, or name assumed to already exist,…
Generate unique test fixture values with LibraryUtility helpers, not hardcoded literalsmicrosoftA fixture helper that assigns a hardcoded literal to a primary-key field, or to any field the test relies on as a unique lookup identifier, collides the moment two tests, or two runs of the same test, create that fixture without cleanup — and a literal longer than the field allows raises a…
Include app-specific scenarios in a PerformanceTest app's BCPT suitemicrosoftA PerformanceTest app that ships with only the generic Microsoft BCPT samples (creating sales orders, purchase orders, posting item journals) measures Business Central's own baseline performance, not the extension it was built to test.
Keep exactly one WHEN per test, with narrow exceptions for flow and defect-then-fix testsmicrosoftThis is a testing-design practice, not a BC platform requirement — no AL API enforces it, and it should not gate a change the way a platform-contradicted claim would.
Match TransactionModel to the commit behavior of the code under testmicrosoft[TransactionModel(...)] declares how a test method interacts with the database's write transaction.
Permission tests must actually lower the execution contextmicrosoftTestPermissions describes how a test runner should establish the permission context; the enum value does not itself assign the business permission set being tested.
Pin asserterror to a specific error with ExpectedError and ExpectedErrorCodemicrosoftasserterror passes when the guarded statement raises any error at all.
RecordRef.Open with Temp = true cannot check the real tablemicrosoftRecordRef.Open(No: Integer [, Temp: Boolean] [, CompanyName: Text]) always takes a real table number.
Reset per-test state before the IsInitialized guardmicrosoftStandard Business Central test codeunits call a local Initialize procedure at the start of every test method.
Separate UI-layer and logic-layer tests into different codeunitsmicrosoftA test codeunit that drives pages through TestPage — opening pages, reading FactBox parts, triggering field OnValidate through the page — is testing a different layer than a codeunit that calls business-logic procedures directly.
Tag test codeunits with FEATURE, SCENARIO, GIVEN, WHEN, and THEN commentsmicrosoftTest codeunits are easier to trust and to review when they carry a four-level comment structure taken from Behaviour-/Acceptance-Test-Driven Development: [FEATURE] once at the top of the codeunit naming the functional area under test, [SCENARIO] above each test procedure stating one falsifiable…
Use Assert.IsFalse to check a boolean result, not asserterror around Assert.IsTruemicrosoftasserterror exists to assert that a statement raises a runtime error; it is not a general-purpose way to invert a boolean check.
Verify field editability with TestPage.Editable(), opened in edit modemicrosoftWhether a field can actually be changed is a distinct state from whether it is shown or enabled — Editable() and Enabled() are separate TestField functions.
Verify field visibility and enabled state with TestPage.Visible()/.Enabled()microsoftA UI test codeunit does not need to inspect table or page properties indirectly to confirm a field is shown or enabled under given conditions.
Wire UI handlers and verify meaningful outcomesmicrosoftA test runs headless, so every UI call on the executed path must be intercepted by a matching handler named in [HandlerFunctions(...)].

agents 20

RuleLayerIn short
Agent permissions intersect the assigner's; agents cannot configure userscommunityAn agent is a user, but it cannot configure users or other agents, and it cannot open sensitive pages such as user cards or permission-set assignment.
Agent setup pages use ConfigurationDialog and the Agent Setup PartcommunityInstance setup is not a Card or StandardDialog.
Agent setup tables are keyed by User Security IDcommunityEach agent instance is a user.
AnalyzeAgentTaskMessage: Error stops the task; Warning still requires reviewcommunityIAgentTaskExecution.AnalyzeAgentTaskMessage runs on inbound and outbound messages.
Bind extra agent subscribers only inside an agent sessioncommunityPage-filter tweaks, extra validation, and prompt dialogs for the agent should not run for every user.
Default agent permission sets must exist in AL and stay least privilegecommunityIAgentFactory.GetDefaultAccessControls fills a temporary Access Control Buffer used when an instance is created.
Do not create agent instances from install, upgrade, or background sessionscommunityAgent.Create requires an interactive user session.
Give the agent a dedicated profile that hides unrelated UIcommunityThe agent only sees what its profile shows.
Instruction documents use responsibilities, guidelines, then ordered stepscommunityThe runtime treats instructions as the agent's standing prompt.
Instructions describe outcomes, not page action or tool namescommunityAgent tools are the UI the profile exposes.
Keep the agent setup page source temporary until UpdatecommunityConfigurationDialog setup is a draft: the user can Cancel without writing.
Other apps cannot call the toolkit APIs on your agent; publish your own APIcommunityFor isolation, Agent, Agent Task Builder, and related toolkit codeunits error when the target instance belongs to another app.
Reapply resource instructions to existing agent instances on upgradecommunityStatic instructions stored as an app resource are copied onto an instance only when you call SetInstructions.
Register a Copilot capability for the agent on installcommunityEach agent type needs a Copilot Capability enum value that the factory links as the feature switch and billing surface.
Set agent instructions as SecretText on the instancecommunityInstructions are instance data, not an enum caption.
ShowCanCreateAgent only hides UI create, not programmatic createcommunityIAgentFactory.ShowCanCreateAgent controls whether the type appears in the in-client create UI.
Skip incoming message review only after the caller validated the payloadcommunityIncoming task messages default to requiring user approval before the agent runs.
The default agent profile must be an AL profile in the appcommunityIAgentFactory.GetDefaultProfile assigns the Role Center and page customizations the agent UI-navigates.
Use the toolkit instruction keywords for review, mail, and memorycommunityThe agent runtime looks for specific phrases: ask for assistance, request a review, reply, write an email, memorize, Set field, use lookup, Invoke action.
Wire all three agent interfaces on the metadata providercommunityAn AL agent type is registered by extending Agent Metadata Provider.

privacy 20

RuleLayerIn short
`FeatureTelemetry` `CustomDimensions` follow the same privacy rules as `Session.LogMessage`microsoftCodeunit "Feature Telemetry" is the second telemetry surface in AL.
Check the custom Privacy Notice before external data transfermicrosoftBusiness Central's Codeunit "Privacy Notice" creates notices and records per-integration approval.
DataClassification is a table-field property, not a page-field propertymicrosoftDataClassification is defined on table fields.
DataClassification is required on table fields containing sensitive datamicrosoftDataClassification tells the platform what kind of data a table field stores so that telemetry, GDPR data-subject requests, and the platform's audit surfaces can treat it correctly.
Displaying fields on a page (or in a UI dialog) is not a privacy concernmicrosoftEvery page in Business Central — Card, List, API, ListPart, request pages — renders data to an authenticated user who has been granted permission to see it.
Do not embed customer data in the telemetry message textmicrosoftSession.LogMessage's message argument is a plain Text.
Error dialogs emit Error method trace telemetrymicrosoftWhen Error displays a dialog, Business Central emits the RT0030 Error method trace telemetry signal.
Every `Session.LogMessage` call must specify `DataClassification`microsoftSession.LogMessage writes a record to the telemetry pipeline.
Extension-owned log tables must be registered as retention-policy allowed tablesmicrosoftThe retention policy engine only ever deletes from tables that appear in its allowed-tables list, and an extension may register only tables it owns — it cannot add a base application table or a table from another extension.
FeatureTelemetry.LogError emits more than caller custom dimensionsmicrosoftFeatureTelemetry.LogError emits its ErrorText as the telemetry message and adds it as alErrorText.
FlowFields and FlowFilters are classified `SystemMetadata` automaticallymicrosoftFlowField and FlowFilter are not stored fields — a FlowField is computed from a CalcFormula at read time and a FlowFilter is a transient filter scoped to the record variable.
In data migration code, classify the destination — not the migration itselfmicrosoftMigration codeunits such as HybridSL, HybridGP, and HybridBC exist to copy sensitive data — TINs, Federal IDs, social security numbers, financial records — from a source system into Business Central.
In-memory variables, dictionaries, lists and temporary tables are not a privacy concernmicrosoftAL runs in a managed server environment.
Pass a Label directly as the first Error argumentmicrosoftError method trace telemetry includes the AL error string only when the first Error argument is a Label or TextConst.
Register custom integrations with Codeunit Privacy NoticemicrosoftThe current extension point is Codeunit "Privacy Notice".
Registering a table does not delete anything — consider shipping a default setupmicrosoftAddAllowedTable only makes a table selectable on the Retention Policies page.
Resolve every `ToBeClassified` before releasemicrosoftDataClassification = ToBeClassified is the sentinel value the AL compiler accepts while a developer has not yet decided what a new field actually stores.
Review each ErrorInfo text surface by its actual exposuremicrosoftRuntime 3.0 (BC 14) provides ErrorInfo.Message, DataClassification, and ErrorType.
Table-level DataClassification is inherited by fieldsmicrosoftA valid table-level DataClassification is the effective default for the Normal fields declared inside that table object when they do not declare their own value, and AppSourceCop AS0016 accepts those fields rather than reporting them as unclassified.
Treat `GetLastErrorText()` as potential customer contentmicrosoftParameterless GetLastErrorText() can contain customer content such as field values, record keys, and file names.

web-services 19

RuleLayerIn short
Address API records by SystemId, not by a renamable business keymicrosoftEvery BC table carries a SystemId — an immutable GUID assigned at insert and never reused.
An API query is read-only and does not support webhooksmicrosoftA custom API can be exposed by a page with PageType = API or by a query with QueryType = API, and the two are not interchangeable.
Check for JSON null before converting a valuemicrosoftAn optional property in a JSON payload can be missing or present with the value null, and the two cases behave differently in AL.
Check HTTP status before consuming the response bodymicrosoftA successful AL HttpClient call only confirms that the platform completed the HTTP exchange.
Declare API routing properties and an explicit stable versionmicrosoftAn API page needs APIPublisher, APIGroup, EntityName, EntitySetName, and a backing SourceTable to define its routed entity.
Describe API objects intended for Business Central MCP toolsmicrosoftFor API pages and API queries exposed through the Business Central online MCP server, the documented tool-description precedence is AboutText, then EntitySetCaption, then a camel-cased EntityName.
Expose business operations as bound actions, not as writable status flagsmicrosoftAn API consumer that needs to *do* something to a record — post it, ship it, release it — should call an explicit operation, not mutate a field and hope a side effect fires.
Format exchanged values with standard format 9microsoftFormat(Value) uses standard format 0, the display format, and follows the current user's regional settings.
Give API pages least-privilege write accessmicrosoftA general-purpose API page that exposes many fields should not be widened to allow writes on one additional field.
Handle HttpClient platform failure before accessing the responsemicrosoftAL HttpClient methods can fail before a usable HTTP response exists because of an invalid request, DNS or network failure, certificate validation, timeout, a disabled extension setting, or the response-size limit.
Keep Consumer-Provided Key Fields Editable on API PagesmicrosoftA field listed in ODataKeyFields cannot have Editable = false when the API page allows inserts and the field's value must be supplied by the caller.
Link API parts on SystemId and choose the correct multiplicitymicrosoftMultiplicity is available from runtime 6.3 (Business Central 17.3) and defaults an API page part to a 1:N collection.
Lock down write operations on read-only API pagesmicrosoftAn API meant purely for reading — a reporting or lookup endpoint — is not read-only just because nobody intends to write to it.
Read only committed data from APIs that must not expose in-flight writesmicrosoftThis is about the data-consistency contract of an API endpoint: what a consumer receives when it reads.
Recalculate Stored Derived Fields Before Exposing Them on API PagesmicrosoftA stored field whose value is derived from other fields inside an OnValidate trigger only updates when that specific trigger fires.
Set the text encoding when converting exchanged text to or from BLOB bytesmicrosoftBlob.CreateInStream and Blob.CreateOutStream take an optional TextEncoding; when it is omitted, the stream uses MSDos (OEM) encoding, whose code page depends on the server's system locale.
Under OData schema version 2.0 an API enum field is a contract by member name; under 1.0 it is the captionmicrosoftWhat an API page publishes for an enum field depends on the OData $schemaversion the caller receives, and never on the ordinal.
Verify webhook eligibility and complete every validationToken handshakemicrosoftBusiness Central can subscribe only to eligible API pages, not every endpoint that can be read through an API.
Version changed API shapes with a new page objectmicrosoftOnce an API version is published, external clients depend on its exact shape — entity names, fields, keys, and behavior — as a stable contract.

error-handling 12

RuleLayerIn short
A bare call to a [TryFunction] propagates its error; it is not a swallowed failuremicrosoftA bare call to a [TryFunction] procedure propagates errors like any ordinary method call.
A declined `Confirm` in `OnValidate` must abort or revert, not skip a required side effectmicrosoftBy the time a field's OnValidate body runs, the field already holds its new value.
An unchecked Record.Get raises an error when the record is missing; it is not silently ignoredmicrosoftRecord.Get returns a Boolean, but its behavior when no record is found depends on whether the return value is consumed.
Choose `TestField` For Conditional Checks And `FieldError` For Already-Failed ValidationmicrosoftTestField and FieldError look interchangeable but behave differently, and choosing the wrong one produces either dead code or a check that never fires.
Collect validation errors with ErrorBehavior::Collect and handle the collected listmicrosoftBy default a procedure stops on the first Error, so a user fixing ten bad rows must rerun the operation ten times.
Consume a TryFunction return value when the caller handles the failuremicrosoftA [TryFunction] catches errors only when the caller uses its Boolean return value.
Log writes that must capture failures must survive transaction rollbackmicrosoftInserting a log record inside the same transaction as the operation it logs looks correct until the operation errors: the transaction rolls back and takes the log entry with it.
Match defensive vs. offensive error handling to the blast radius of being wrongmicrosoftWhether code should guard gracefully (defensive) or fail loudly (offensive/fail-fast) is not a matter of habit or a blanket house style — it depends on what happens downstream if the guarded condition is silently defaulted or skipped.
Page record triggers return true by default; a missing exit(true) does not block the operationmicrosoftThe Boolean page record triggers OnInsertRecord, OnModifyRecord, OnDeleteRecord, and OnQueryClosePage return true by default.
Prefer ErrorInfo with recommended actions over a plain Error for recoverable failuresmicrosoftA plain Error('text') ends the operation with a dead-end dialog: the user reads the message but the system offers no way forward.
Rely On FieldError's Auto-Generated Context And Pass Only A Lowercase PredicatemicrosoftRec.FieldError(FieldNo) does not just print the text you give it.
Set ErrorInfo.ErrorType to Internal for defects you want in telemetry but not in the user's facemicrosoftErrorInfo.ErrorType controls where an error's message is shown.

reporting 12

RuleLayerIn short
A layout added in a report extension is not used until it is selectedmicrosoftA reportextension can add layouts through its rendering section, but deploying the extension does not make any of them the report's layout.
Choose ReportExtension dataitem triggers by their order around the base triggermicrosoftReportExtension dataitem triggers run at defined points around the corresponding base-report trigger.
Clear a Report variable before an independent RunModal executionmicrosoftReport.Run() automatically clears the report variable after execution, but Report.RunModal() does not.
CurrReport.Break ends the current triggermicrosoftCurrReport.Break() inside a report dataitem trigger does more than leave an AL loop.
CurrReport.Quit rolls back report changes and skips OnPostReportmicrosoftCurrReport.Quit() aborts the report without committing database changes made during its execution.
CurrReport.Skip: separate current-trigger exit from later triggersmicrosoftCurrReport.Skip() omits the current record from the report dataset.
Declare report layouts in the rendering section, not with the legacy layout propertiesmicrosoftSince runtime 9.0 (BC20), reports declare layouts in a rendering section of named layout entries, each with Type, LayoutFile, Caption, and Summary, and choose the default by name with DefaultRenderingLayout.
Do not rename or remove columns of a report dataset that has shippedmicrosoftA report's dataset column names are the contract that every layout binds to, including layouts that are not in your source code.
Report output in a loop needs one client downloadmicrosoftThe Business Central Web client can deliver only one file per request.
ReportExtension report triggers run after base report triggersmicrosoftOnPreReport and OnPostReport on a ReportExtension run after the corresponding triggers on the base report.
SetTableView cannot broaden DataItemTableViewmicrosoftReport.SetTableView() applies the supplied record view by narrowing the view already defined by the report dataitem's DataItemTableView.
Stop when RunRequestPage returns empty parametersmicrosoftReport.RunRequestPage() returns an empty string when the user chooses Cancel.

appsource 10

RuleLayerIn short
AppSource permission sets must cover setup and usage without SUPERmicrosoftAn AppSource app must provide permission sets that let assigned users complete the app's setup and normal usage without SUPER.
Define profiles as AL objectscommunityProfiles delivered by a Marketplace extension must be declared as AL profile objects.
Do not hard-code time-zone offsetscommunityMarketplace extensions run for users and services in many time zones.
Keep the Copilot help URL to two path levelsmicrosoftThe help URL declared in app.json is what Copilot uses to ground answers about your app.
Keep web-service paths free of UI callscommunityPages and codeunits exposed as web services run without an interactive client.
Place page extension actions with addfirst or addlastcommunityPlace new page-extension actions at the beginning or end of an existing action group with addfirst or addlast.
Set UsageCategory on searchable entry pointscommunityPages and reports that users are expected to open directly must set UsageCategory.
The File data type's direct I/O methods are OnPrem-onlymicrosoftThe classic File variable type — Open/Create/Read/Write/Close against a path on the local or server filesystem — is scoped OnPrem-only.
Update the app version at every releasemicrosoftAt every release — a branch merged to main, a tagged release build, or an AppSource submission — the app's version is consciously updated, not left to the pipeline alone.
Use invariant date literalscommunityWrite fixed dates in AL with the invariant yyyymmddD syntax.

scm 10

RuleLayerIn short
Cancel reservations through reservation managementmicrosoftPersistent "Reservation Entry" rows are not disposable allocation markers.
Carry out requisition actions through the standard workflowmicrosoftA requisition/planning line is a pending change to a supply/demand network, not just a template for a purchase line.
Change item applications through posting routinesmicrosoftAn "Item Application Entry" connects quantity application to cost flow; changing its inbound entry number is not merely fixing a foreign key.
Derive base quantities through the line's unit of measuremicrosoftInventory, item ledger entries, reservations, item tracking, and warehouse quantities are measured in the item's base unit of measure.
Post calculated revaluation through the item journal batchmicrosoftA calculated revaluation line with nonblank "Inventory Value Per" represents an aggregate, not a finalized posting against one item ledger entry.
Post item ledger changes through item journalsmicrosoftAn item ledger entry is not an independently insertable stock balance.
Post transfers through shipment and receipt codeunitsmicrosoftA two-step transfer order preserves a continuous quantity, reservation, and cost/application lineage from the source through in-transit to the destination.
Reconcile warehouse adjustments with the item ledgermicrosoftAt a Directed Put-away and Pick location, registering an ordinary warehouse quantity or physical-inventory adjustment and synchronizing it to inventory are distinct steps.
Transfer item tracking through source reservation codeunitsmicrosoftMoving lot/serial tracking between document lines is a source-ownership operation, not a copy of visible tracking fields.
Use date-aware availability for promisingmicrosoftItem.Inventory is an on-hand quantity, not an available-to-promise answer.

breaking-changes 9

RuleLayerIn short
Changing an unreleased symbol is not a breaking changemicrosoftBreaking-change rules protect contracts that have already shipped to customers or are exposed to external extensions.
Choose access modifiers deliberatelymicrosoftAccess is a decision about what you are willing to support forever.
Deprecate public members through the Obsolete lifecycle, never delete them outrightmicrosoftDeleting or renaming a published procedure (or object) in a single release is a hard break: dependent extensions that reference it stop compiling the moment they pick up the new version, with no warning window to migrate.
Do not build on code already marked obsoletemicrosoftA member carrying [Obsolete], or wrapped in a #if not CLEANxx conditional-compilation block, is already scheduled for deletion — the CLEANxx symbol is flipped on in a future release to strip that code out.
Do not change the signature of a published proceduremicrosoftA 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.
Do not widen access to expose sensitive data through a public APImicrosoftEvery member you make publicly reachable becomes a contract you must keep — and when that member returns a secret, the contract leaks the secret.
Obsolete published table fields instead of deleting, renaming, or renumbering themmicrosoftA shipped table field carries both a source-level contract and persisted data.
Relocating a field to a tableextension in the same app is not a deletionmicrosoftMoving a field out of a base-table definition (or a base-app layer modification of one) into a tableextension that extends the same table, within the same app and keeping the same field ID and name, is a relocation — not a deletion or a rename.
Send email through the Email module, not Codeunit Mail (397)microsoftOlder AL code sends email by calling Codeunit Mail (397).

finance 9

RuleLayerIn short
Apply and unapply entries through the application workflow, not status flagsmicrosoftCustomer/vendor settlement is a posting operation involving detailed ledger entries, not just a change to Open on the main entry.
Change a transaction's dimension set reference, not a shared set's membershipmicrosoftThe same Dimension Set ID can be referenced by an unposted journal line and by many already-posted entries.
Change posted customer/vendor due dates through the entry-edit workflowmicrosoftA posted customer or vendor due date is supported editable operational data, but it is also represented by Initial Entry Due Date on related detailed ledger entries.
Copy complete posting dimension sets, not only shortcut projectionsmicrosoftWhen a journal line or posting document inherits dimensions, its Dimension Set ID identifies the complete combination of Dimension Set Entry rows.
Correct posted financial content through posting workflows, not row surgerymicrosoftChanging a posted entry's original amount, account, posting date, or tax amounts in place does not correct the related ledger, register, or source document.
Create financial ledger entries through the owning posting enginemicrosoftStandard financial ledger entries are outputs of posting, not independent rows an extension manufactures.
Pass the transaction number, not a ledger-entry number, to ReverseTransactionmicrosoftReversal Entry.ReverseTransaction expects a transaction number, while ReverseRegister expects a G/L register number.
Preserve the journal batch's document-balancing policymicrosoftA balanced G/L total does not prove that a general-journal batch satisfies its template's document-balancing policy.
Supply a VAT-inclusive journal Amount for automatic Normal VATmicrosoftFor a general-journal line using Automatic VAT Entry and Normal VAT, Amount includes VAT.

telemetry 7

RuleLayerIn short
Call FeatureTelemetry.LogUsage only after successful usemicrosoftFeatureTelemetry.LogUsage means that a user successfully used the feature.
Choose TelemetryScope by who must receive the signalmicrosoftTelemetryScope::ExtensionPublisher sends a custom trace only to the Application Insights resource configured by the extension publisher.
Emit FeatureTelemetry uptake states in lifecycle ordermicrosoftFeatureTelemetry.LogUptake accepts Discovered, Set up, Used, and Undiscovered, but the platform records the forward transition only as Discovered to Set up to Used.
Match telemetry Verbosity to the signal's actual severitymicrosoftVerbosity becomes the Application Insights severityLevel and participates in on-premises diagnostic trace filtering.
Register exactly one Telemetry Logger implementation per publishermicrosoftThe Telemetry and Feature Telemetry codeunits reach an extension publisher's telemetry through an implementation of the "Telemetry Logger" interface registered with "Telemetry Loggers".OnRegisterTelemetryLogger.
Telemetry event IDs must be stable, unique, and non-placeholdermicrosoftThe first parameter of Session.LogMessage is the event ID.
Treat custom dimension keys as a stable telemetry schemamicrosoftBusiness Central prefixes AL custom-dimension keys with al in Application Insights, so an AL key named Result becomes alResult.

interfaces 6

RuleLayerIn short
Assign a codeunit to an interface variable for injectable, testable dependenciesmicrosoftAn interface variable can hold any codeunit that implements the interface, assigned directly — no enum is required.
Extend published interfaces; do not edit themmicrosoftAdding a method to a shipped interface changes the contract every implementing codeunit must satisfy.
Guard optional interface casts with `is`microsoftFrom runtime 15.0, AL can type-test an interface or Variant with is and cast it to another interface with as.
Handle unknown enum ordinals with UnknownValueImplementationmicrosoftAn enum ordinal can remain in persisted data after the enum extension that declared it is uninstalled.
Prefer an interface with enum-backed implementation over a case statement for variant behaviourmicrosoftWhen behaviour varies by a discrete "type" — a shipping method, a posting strategy, a payment provider — the obvious first draft is a case over an enum with one branch per variant.
Set DefaultImplementation on an enum so an unmapped value still resolves to an interfacemicrosoftAn enum that implements an interface maps each declared value to a codeunit through the Implementation property.

query 6

RuleLayerIn short
A lower query data item without SqlJoinType is a left outer joinmicrosoftWhen a lower dataitem in a query sets DataItemLink but omits SqlJoinType, the join is LeftOuterJoin.
DataItemTableFilter cannot be overwritten at runtimemicrosoftDataItemTableFilter defines a static filter on a Query dataitem.
Every non-aggregated query column is a group keymicrosoftAs soon as one query column sets Method to Sum, Count, Average, Min, or Max, the query groups its result by all other columns, including columns of other data items and columns that use a date method (Day, Month, Year).
Reopening a Query resets its cursor but keeps its filtersmicrosoftCalling Open() on an already open query first closes the current dataset and opens it again.
Set Query filters before OpenmicrosoftQuery.SetFilter and Query.SetRange automatically close an open query dataset.
SetFilter and SetRange overwrite Query ColumnFiltermicrosoftColumnFilter on a Query column or filter row defines a dynamic filter.

copilot 5

RuleLayerIn short
Call Azure OpenAI through the System.AI module, not a hand-built HttpClient requestcommunityThe System Application's AI module (Azure OpenAI, AOAI Chat Messages, AOAI Chat Completion Params, AOAI Operation Response) is the supported way to call Azure OpenAI from AL.
Check the AOAI Operation Response before using generated outputcommunityGenerateChatCompletion, GenerateTextCompletion, and GenerateEmbeddings in codeunit Azure OpenAI report the outcome of the service call in the AOAI Operation Response passed by var; a failed completion does not stop the AL code.
Keep user input and record text out of the system messagecommunityAOAI Chat Messages separates roles: the system message (SetPrimarySystemMessage, AddSystemMessage) holds the metaprompt that defines the model's task, output format, and guard rails; user messages (AddUserMessage) carry what the user typed and the business data to work on.
Register a Copilot capability on install and on upgradecommunityEvery extension that calls the AI module must register its Copilot Capability enum value with codeunit Copilot Capability; using a capability that the calling extension has not registered raises an error.
Save PromptDialog proposals only when the user keeps themcommunityA PromptDialog page shows AI-generated content as a proposal.

xmlport 4

RuleLayerIn short
A text XMLport uses MS-DOS encoding unless `TextEncoding` is setmicrosoftAn XMLport whose Format is VariableText or FixedText reads and writes text in the encoding given by its TextEncoding property, and the default value is MSDOS.
Pass the filtered record to the XMLport call to limit its datamicrosoftXmlport.Export, Xmlport.Import, and Xmlport.Run accept an optional record argument, and the XMLport uses any filters attached to that record.
The `Import` argument of `Xmlport.Run` must match the XMLport's `Direction`microsoftXmlport.Run(Number [, RequestWindow] [, Import] [, Record]) takes an optional Import argument that says whether the XMLport imports or exports, and its default is true.
The return value of `Xmlport.Import` and `Xmlport.Export` decides who handles a failuremicrosoftXmlport.Import and Xmlport.Export have an optional Boolean return value: true when the operation succeeded, otherwise false.

Review skills 25

RuleLayerIn short
AL agents reviewcommunityReviews AL source changes against agent guidance from BCQuality.
AL AppSource reviewmicrosoftPerforms an AL AppSource review against source and app metadata guidance from BCQuality.
AL breaking changes reviewmicrosoftReviews AL source changes against breaking-changes guidance from BCQuality.
AL code reviewmicrosoftReviews AL source changes by composing the AL review leaf skills, one per knowledge domain.
AL Copilot reviewcommunityReviews AL source changes that build Copilot features on the System.AI module against Copilot guidance from BCQuality.
AL data-modeling reviewmicrosoftPerforms an AL data-modeling review against guidance from BCQuality.
AL development plan guidancemicrosoftProduces a read-only BCQuality knowledge bundle for an existing Business Central AL development plan.
AL error handling reviewmicrosoftReviews AL source changes against error-handling guidance from BCQuality.
AL events reviewmicrosoftReviews AL source changes against events-and-subscribers guidance from BCQuality.
AL Finance reviewmicrosoftReviews financial journal posting, ledger corrections, applications, VAT handling, and posting-linked dimensions against BCQuality Finance guidance.
AL interfaces reviewmicrosoftReviews AL source changes against interface and enum-with-implementation guidance from BCQuality.
AL knowledge consultationmicrosoftAnswer a Business Central development question with cited knowledge, without reviewing source code.
AL performance reviewmicrosoftReviews AL source changes against performance guidance from BCQuality.
AL privacy reviewmicrosoftReviews AL source changes against privacy and data-classification guidance from BCQuality.
AL Query reviewmicrosoftReviews AL Query objects and Query instance usage against BCQuality guidance.
AL reporting reviewmicrosoftReviews AL Report and ReportExtension code against BCQuality reporting guidance.
AL security reviewmicrosoftReviews AL source changes against security guidance from BCQuality.
AL style reviewmicrosoftReviews AL source changes against naming, labelling, localization, and code-convention guidance from BCQuality.
AL Supply Chain Management reviewmicrosoftReviews SCM inventory costing, item application, reservations, order tracking, item tracking, warehouse, transfer, and planning workflows in AL.
AL telemetry reviewmicrosoftPerforms an AL telemetry review against guidance from BCQuality.
AL testing reviewmicrosoftPerforms an AL testing review against guidance from BCQuality.
AL UI and accessibility reviewmicrosoftReviews AL page and control add-in UI files, AL code that sends or recalls notifications, and AL code that registers guided experience setup items, against UI text, caption, tooltip, notification, and accessibility guidance from BCQuality.
AL upgrade reviewmicrosoftReviews AL source changes against upgrade-code and migration guidance from BCQuality.
AL web services reviewmicrosoftReviews AL API surfaces, outbound HTTP integrations, and webhook handlers against web-services guidance from BCQuality.
AL XMLport reviewmicrosoftReviews AL XMLport objects and XMLport calls against BCQuality guidance.