Merge pull request #263 from microsoft/main

Updating old branch to fix some actions
This commit is contained in:
Jeremy Vyska 2025-08-11 10:15:25 +02:00 committed by GitHub
commit 51224f6bc7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
268 changed files with 3905 additions and 1071 deletions

27
.devcontainer/Dockerfile Normal file
View file

@ -0,0 +1,27 @@
# syntax=docker/dockerfile:1
FROM mcr.microsoft.com/devcontainers/base:ubuntu-22.04
# VARIANT can be either 'hugo' for the standard version or 'hugo_extended' for the extended version.
ARG VARIANT=hugo_extended
# VERSION can be either 'latest' or a specific version number
ARG VERSION=latest
# Download Hugo
RUN case ${VERSION} in \
latest) \
export VERSION=$(curl -s https://api.github.com/repos/gohugoio/hugo/releases/latest | grep "tag_name" | awk '{print substr($2, 3, length($2)-4)}') ;;\
esac && \
echo ${VERSION} && \
case $(uname -m) in \
aarch64) \
export ARCH=ARM64 ;; \
*) \
export ARCH=64bit ;; \
esac && \
echo ${ARCH} && \
wget -O ${VERSION}.tar.gz https://github.com/gohugoio/hugo/releases/download/v${VERSION}/${VARIANT}_${VERSION}_Linux-${ARCH}.tar.gz && \
tar xf ${VERSION}.tar.gz && \
mv hugo /usr/bin/hugo
# Hugo dev server port
EXPOSE 1313

View file

@ -0,0 +1,35 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.217.4/containers/hugo
{
"name": "Hugo",
"build": {
"dockerfile": "Dockerfile"
},
"customizations": {
"vscode": {
// Set *default* container specific settings.json values on container create.
"settings": {
"html.format.templating": true
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"bungcip.better-toml",
"davidanson.vscode-markdownlint",
"GitHub.vscode-pull-request-github"
]
}
},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [
1313
],
"remoteUser": "vscode",
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": ""
"features": {
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers/features/go:1": {},
"ghcr.io/devcontainers/features/hugo:1": {},
"ghcr.io/devcontainers/features/node:1": {}
}
}

8
.gitattributes vendored Normal file
View file

@ -0,0 +1,8 @@
* text=auto eol=lf
*.{cmd,[cC][mM][dD]} text eol=crlf
*.{bat,[bB][aA][tT]} text eol=crlf
*.gif binary
*.jpeg binary
*.png binary
*.gz binary
*.jar binary

73
.github/workflows/hugo.yml vendored Normal file
View file

@ -0,0 +1,73 @@
# Sample workflow for building and deploying a Hugo site to GitHub Pages
name: Deploy Hugo site to Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["main"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
# Default to bash
defaults:
run:
shell: bash
jobs:
# Build job
build:
runs-on: ubuntu-latest
env:
HUGO_VERSION: 0.133.1
steps:
- name: Install Hugo CLI
run: |
wget -O ${{ runner.temp }}/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb \
&& sudo dpkg -i ${{ runner.temp }}/hugo.deb
- name: Install Dart Sass
run: sudo snap install dart-sass
- name: Checkout
uses: actions/checkout@v3
- name: Setup Pages
id: pages
uses: actions/configure-pages@v3
- name: Install Node.js dependencies
run: "[[ -f package-lock.json || -f npm-shrinkwrap.json ]] && npm ci || true"
- name: Build with Hugo
env:
# For maximum backward compatibility with Hugo modules
HUGO_ENVIRONMENT: production
HUGO_ENV: production
run: |
hugo \
--minify \
--baseURL "${{ steps.pages.outputs.base_url }}/"
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: ./public
# Deployment job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v2

View file

@ -1,49 +0,0 @@
name: hugo CI
on:
push:
branches:
- main # Set a branch name to trigger deployment
pull_request:
jobs:
deploy:
runs-on: ubuntu-20.04
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
steps:
- uses: actions/checkout@v2
with:
submodules: recursive # Fetch Hugo themes (true OR recursive)
fetch-depth: 0 # Fetch all history for .GitInfo and .Lastmod
- name: Setup Hugo
uses: peaceiris/actions-hugo@v2
with:
hugo-version: 'latest'
extended: true # Use extended Hugo
- name: Setup Node
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Cache dependencies
uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Prepare postcss-cli
run: npm ci
- name: Build
run: hugo --minify
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
if: ${{ github.ref == 'refs/heads/main' }}
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./public

3
.gitmodules vendored
View file

@ -1,3 +0,0 @@
[submodule "themes/docsy"]
path = themes/docsy
url = https://github.com/google/docsy.git

11
.vscode/tasks.json vendored Normal file
View file

@ -0,0 +1,11 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "Start local Hugo server",
"type": "shell",
"command": "hugo serve",
"problemMatcher": []
}
]
}

23
CITATION.cff Normal file
View file

@ -0,0 +1,23 @@
cff-version: 1.2.0
title: ALGuidelines.dev
abstract: |
"Microsoft ALGuidelines - A Community driven project.
Best Practices and Design Patterns for the AL Language."
keywords:
- AL
- "Design Patterns"
- "Best Practices"
authors:
- given-names: Eric
family-names: Wauters
- given-names: Arend-Jan
family-names: Kauffmann
- given-names: Henrik
family-names: Helgesen
orcid: https://orcid.org/0000-0002-3281-6712
- given-names: Jeremy
family-names: Vyska
license: MIT
url: "https://alguidelines.dev"
repository-code: "https://github.com/microsoft/alguidelines"

View file

@ -40,14 +40,7 @@ contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additio
### Setup ### Setup
1. Clone and setup **Run Hugo server**
```sh
# Clone all submodules
git submodule update --init --recursive --depth 1
# Install NPM dependencies
npm install
```
2. Run Hugo server
``` ```
$ hugo server $ hugo server
Web Server is available at http://localhost:1313/ (bind address 127.0.0.1) Web Server is available at http://localhost:1313/ (bind address 127.0.0.1)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

View file

@ -1,2 +1,7 @@
.td-page-meta--child { display: none !important; } .td-page-meta--child { display: none !important; }
.td-page-meta--project-issue { display: none !important; } .td-page-meta--project-issue { display: none !important; }
.td-content pre code {
font-family: Consolas, "Courier New", monospace;
size: 115%;
}

View file

@ -534,6 +534,10 @@ input[type="search"]::placeholder {
display: none; display: none;
} }
.show-mobile-inline {
display: none;
}
@media (max-width: 1299px) { @media (max-width: 1299px) {
.hero { .hero {
background: url("/images/hero-bg.webp") no-repeat; background: url("/images/hero-bg.webp") no-repeat;
@ -556,6 +560,10 @@ input[type="search"]::placeholder {
display: block; display: block;
} }
.show-mobile-inline {
display: inline;
}
.hero { .hero {
background: url("/images/hero-bg.webp") no-repeat; background: url("/images/hero-bg.webp") no-repeat;
background-size: cover; background-size: cover;

View file

@ -1,21 +0,0 @@
+++
chapter = true
pre = "<b><i class='fas fa-clone'></i> </b>"
title = "Discussions"
weight = 200
+++
# [Discussions](https://github.com/microsoft/alguidelines/discussions)
We enabled the "Discussions" forum on the github-page of our repository for you to discuss anything "Design Pattern" or "Best Practices" related.
You can find the discussions here: https://github.com/microsoft/alguidelines/discussions.
Feel free to browse through them, find certain topics and/or participate in the discussions!
## Create your own discussion
You are obviously also free to start a new discussion. You can simply do that by using the "New Discussion" button on the top right.
Or use this link: https://github.com/microsoft/alguidelines/discussions/new?category=bc-patterns

View file

@ -123,16 +123,16 @@ images: ["images/og-image-fission.png"]
</div> </div>
<div class="col-lg-4"> <div class="col-lg-4">
<div class="card-shadow"> <div class="card-shadow">
<span class="card-badge">PATTERN</span> <span class="card-badge">NEW</span>
<h4 class="section-text-bold mt-4"> <h4 class="section-text-bold mt-4">
Event Bridge Vibe Coding for AL
</h4> </h4>
<div class="card-shadow-content"> <div class="card-shadow-content">
<p class="section-text"> <p class="section-text">
In the world of interfaces, it is important to preserve (certain) events over multiple implementation of the interface. AI-optimized coding rules and guidelines designed to enhance the AL developer experience in modern AI-powered IDEs like VS Code and Cursor.
</p> </p>
<a href="/docs/patterns/event-bridge-pattern/"> <a href="/docs/vibe-coding/">
<button class="hero-mid align-self-end">Read Now</button> <button class="hero-mid-2 align-self-end">Explore Rules</button>
</a> </a>
</div> </div>
</div> </div>
@ -140,15 +140,15 @@ images: ["images/og-image-fission.png"]
<div class="col-lg-4"> <div class="col-lg-4">
<div class="card-shadow"> <div class="card-shadow">
<span class="card-badge">BEST PRACTICE</span> <span class="card-badge">TAG</span>
<h4 class="section-text-bold mt-4"> <h4 class="section-text-bold mt-4">
CASE Action on next line API
</h4> </h4>
<div class="card-shadow-content"> <div class="card-shadow-content">
<p class="section-text"> <p class="section-text">
A CASE action should start on a line after the possibility. Two API Related Design Patterns and one Best Practice for working with API's
</p> </p>
<a href="/docs/bestpractices/case-actions/" <a href="/tags/api/"
><button class="hero-mid-2 align-self-end">Read Now</button></a ><button class="hero-mid-2 align-self-end">Read Now</button></a
> >
</div> </div>
@ -159,14 +159,14 @@ images: ["images/og-image-fission.png"]
<div class="card-shadow"> <div class="card-shadow">
<span class="card-badge">PATTERN</span> <span class="card-badge">PATTERN</span>
<h4 class="section-text-bold mt-4"> <h4 class="section-text-bold mt-4">
Façade Event Bridge
</h4> </h4>
<div class="card-shadow-content"> <div class="card-shadow-content">
<p class="section-text"> <p class="section-text">
The intent of this pattern is to provide a unified API to a single or a collection of potentially complex subsystems. In the world of interfaces, it is important to preserve (certain) events over multiple implementation of the interface.
</p> </p>
<a <a
href="/docs/patterns/facade-pattern/" href="/docs/patterns/event-bridge-pattern/"
><button class="hero-mid-2 align-self-end">Read Now</button></a ><button class="hero-mid-2 align-self-end">Read Now</button></a
> >
</div> </div>

View file

@ -0,0 +1,96 @@
---
title: "Custom Telemetry"
tags: ["AL","Telemetry"]
categories: ["Best Practice"]
---
_Created by Microsoft, Described by Arend-Jan Kauffmann_
## Description
With AL it is possible to emit custom telemetry signals to Azure Application Insights. There are a number of considerations that you should keep in mind when designing custom telemetry signals.
- Think about it as an API
- Naming conventions and telemetry schema
- Objects emitting telemetry signals
- Candidate data for telemetry
- How customers use telemetry
- Privacy
## Think about it as an API
Customers will build analytics and monitoring solutions on top of their telemetry data.
Therefore, signal must be treated as any other API
- documented
- versioned
- discoverable
- non-breaking
## Naming conventions and telemetry schema
To make it easy for the consumer of telemetry to work with the data, please
- use **PascalCasing**. This makes all fields in Application Insights look the same (signal logged through the AL LogMessage method will have "al" prefixed to dimension names.
- **Do not use special characters or spaces** for fields/custom dimension keys. This makes the KQL queries so much easier to write
- for custom dimensions, consider using prefixes that helps the telemetry consumer understand where the dimension is coming from (e.g. HttpStatusCode, SqlStatement, ...)
Consider always having a **"message"** field that expresses in human readable form what the telemetry event is about.
If you do, let message names follow the Object ActionInPastTense pattern
Some examples
- Web Service Called:
- Email attempt failed
- Authorization to environment succeeded
```al
local procedure ProcessHttpResponse(var Request: HttpRequestMessage; var Response: HttpResponseMessage)
var
CustomTelemetryDimensions: Dictionary of [Text,Text];
begin
if Response.HttpStatusCode <> 200 then begin
CustomTelemetryDimensions.Add('Url', Request.GetRequestUri);
CustomTelemetryDimensions.Add('HttpStatusCode', Format(Response.HttpStatusCode));
CustomTelemetryDimensions.Add('ReasonPhrase', Response.ReasonPhrase);
Session.LogMessage(
'MyExt0001',
'Web service call failed',
Verbosity::Error,
DataClassification::SystemMetadata,
TelemetryScope::ExtensionPublisher,
CustomTelemetryDimensions);
end;
end;
```
## Objects emitting telemetry signals
Telemetry data includes information about the object that emitted the telemetry signal. It's recommended to call Session.LogMessage() **from within the object** that causes a situation that you want to have telemetry for. That will make it easier to analyze where exactly in the code an issue occurred.
Of course it is possible to have a single object as a central place to emit telemetry signals. The telemetry data includes a callstack, so eventually it would be possible to trace back to the exact place where an issue occurred. But that requires a more complicated query, so it would be better to emit telemetry signals right from place in the code where an issue occurred.
## Candidate data for telemetry
Telemetry must be **actionable** for the customer. Do not emit signals that they cannot act on (knowing about CPU performance counters on the database is useless if the partner cannot scale the database).
Also, note that customers pay for data ingestion. So be mindful to not flood their telemetry resources. Consider to use TelemetryScope::ExtensionPublisher by default and only use TelemetryScope::All in case the customer can also act on the data.
If you do not know where to start, consider using telemetry for deflection. In Dynamics 365 Business Central, they started with signal about authorization (successful/failed) to deflect support cases that was due to disabled users/wrong licenses.
## How customers use telemetry
The following are known scenarios for customer telemetry
- The tenant admin (typically an IT-pro) wants to troubleshoot a performance problem and they need more details than what is provided in the analytics reports in the admin center.
- The customer wants to analyze (and correct) errors happening in the environment (typically an IT-pro)
- The customer wants to analyze usage of features (typically an analytics user, maybe with BI experience)
Customers typically start in the Application Insights portal and then move on to use more advanced tools for analytics (KQL, Power BI, Excel, ...). Once they have seen the light, they will likely start alerting on telemetry using Azure Monitor Alerts or setting up Power Automate flows.
Business Central have developed a telemetry maturity model (based on the Gartner BI maturity model) for how organizations can evolve to use telemetry proactively in their business processes.
## Privacy
Telemetry must be **privacy compliant**.
For privacy reasons, events that have a DataClassification other than SystemMetadata aren't sent to Application Insight resources set up on the tenant. During development of your extension, it's good practice to have a privacy review of the use of LOGMESSAGE calls to ensure that customer data isn't mistakenly leaked into Application Insights resources.

View file

@ -1,10 +1,10 @@
--- ---
title: "DeleteAll" title: "DeleteAll"
tags: ["Performance"] tags: ["AL","Performance"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
<_Created by waldo, Described by waldo_\> _Created by waldo, Described by waldo_
## Description ## Description
@ -25,11 +25,3 @@ Therefore it's good practice to always check if the table is empty when performi
if not EmptyTableWLD.IsEmpty() then if not EmptyTableWLD.IsEmpty() then
EmptyTableWLD.DeleteAll(true); EmptyTableWLD.DeleteAll(true);
``` ```
## Discussions
You can discuss the guideline [here](https://github.com/microsoft/alguidelines/discussions/107)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -0,0 +1,69 @@
---
title: "SetLoadFields"
tags: ["AL","Readability"]
categories: ["Best Practice"]
---
See the documentation on learn.microsoft.com for more information about [SetLoadFields](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/record/record-setloadfields-method).
For the performance of your code it is important that you use SetLoadFields as much as possible.
If you want to retrieve a record from the database to check if the record is available always use SetLoadFields on the primary key fields of the table so only those fields will be retrieved from the database.
## Bad code
```AL
if not Item.Get(ItemNo) then
exit();
```
## Good code
```AL
Item.SetLoadFields("No.");
if not Item.Get(ItemNo) then
exit();
```
Place the SetLoadFields in the code before the line of the Get (or find). (there is no need to record filter fields in the SetLoadFields because these will be retrieved automatically).
## Bad code
```AL
Item.SetLoadFields("Item Category Code");
Item.SetRange("Third Party Item Exists", false);
Item.FindFirst();
```
## Good code
```AL
Item.SetRange("Third Party Item Exists", false);
Item.SetLoadFields("Item Category Code");
Item.FindFirst();
```
Place the SetLoadFields in the code before the case statement
## Bad code
```AL
Item.SetLoadFields("Item Category Code");
ItemCategoryCode := FindItemCategoryCode;
case true of
Item.Get(ItemNo):
SetItemCategoryCode(Item, ItemCategoryCode);
end;
```
## Good code
```AL
ItemCategoryCode := FindItemCategoryCode;
Item.SetLoadFields("Item Category Code");
case true of
Item.Get(ItemNo):
SetItemCategoryCode(Item, ItemCategoryCode);
end;
```

View file

@ -1,6 +1,6 @@
--- ---
title: "Subscriber Codeunits" title: "Subscriber Codeunits"
tags: ["Performance"] tags: ["AL","Performance"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
@ -18,15 +18,18 @@ In general, subscribers have to be put in codeunits. There are a few performanc
Let's discuss all points Let's discuss all points
## Keep the codeunit as small as possible ## Keep the codeunit as small as possible
Every time a subscriber gets called, a new instance of the codeunit is being loaded in memory, which takes memory and processing power. The smaller the codeunit, the less memory, and the faster it is. Every time a subscriber gets called, a new instance of the codeunit is being loaded in memory, which takes memory and processing power. The smaller the codeunit, the less memory, and the faster it is.
Therefore, it's suggested to split the subscribers by functionality and avoid putting business logic in the actual codeunit. Tip: put all business logic in an "[Method Codeunit](https://alguidelines.dev/bcpatterns/generic-method-pattern/)". Therefore, it's suggested to split the subscribers by functionality and avoid putting business logic in the actual codeunit. Tip: put all business logic in an "[Method Codeunit](https://alguidelines.dev/docs/patterns/generic-method-pattern/)".
Examples: Examples:
- if you app does things on Sales and Purchase, create a Sales-subs codeunit, and a Purchase-subs. - if you app does things on Sales and Purchase, create a Sales-subs codeunit, and a Purchase-subs.
- if you have multiple functionalities in your app (let's call'm modules), create a subs-codeunit per module, and only add the subscribers in there that are necessary for that module. - if you have multiple functionalities in your app (let's call'm modules), create a subs-codeunit per module, and only add the subscribers in there that are necessary for that module.
### Bad code ### Bad code
```AL ```AL
codeunit 2037325 "Setup Subs" codeunit 2037325 "Setup Subs"
{ {
@ -73,6 +76,7 @@ codeunit 2037325 "Setup Subs"
end; end;
} }
``` ```
### Good code ### Good code
Split into 2 codeunits, and move the business logic out. Split into 2 codeunits, and move the business logic out.
@ -112,6 +116,7 @@ codeunit 2037324 "RHE Setup Subs"
To avoid the extra "loading of the content" while a subscriber is being executed, use Single Instance codeunit for subscribers. Do take into account, of course, that it would share the state across the entire session. To avoid the extra "loading of the content" while a subscriber is being executed, use Single Instance codeunit for subscribers. Do take into account, of course, that it would share the state across the entire session.
### Bad code ### Bad code
```AL ```AL
codeunit 2037324 "RHE Setup Subs" codeunit 2037324 "RHE Setup Subs"
{ {
@ -124,7 +129,9 @@ codeunit 2037324 "RHE Setup Subs"
end; end;
} }
``` ```
### Good code ### Good code
```AL ```AL
codeunit 2037324 "RHE Setup Subs" codeunit 2037324 "RHE Setup Subs"
{ {
@ -145,6 +152,7 @@ codeunit 2037324 "RHE Setup Subs"
If possible, only execute the subscriber when really necessary by using Manual Binding. If possible, only execute the subscriber when really necessary by using Manual Binding.
### Bad code ### Bad code
```AL ```AL
//subscriber - code should actually only run when Color=Red. //subscriber - code should actually only run when Color=Red.
[EventSubscriber(ObjectType::Table, Database::"Just Some Table WLD", 'OnAfterValidateEvent', 'Message 2', false, false)] [EventSubscriber(ObjectType::Table, Database::"Just Some Table WLD", 'OnAfterValidateEvent', 'Message 2', false, false)]
@ -162,7 +170,9 @@ If possible, only execute the subscriber when really necessary by using Manual B
JustSomeTable.Validate("Message 2", format(Random(1000))); JustSomeTable.Validate("Message 2", format(Random(1000)));
until JustSomeTable.Next() < 1; until JustSomeTable.Next() < 1;
``` ```
### Good code ### Good code
```AL ```AL
if JustSomeTable.FindSet() then if JustSomeTable.FindSet() then
repeat repeat
@ -177,21 +187,15 @@ If possible, only execute the subscriber when really necessary by using Manual B
``` ```
## Avoid OnInsert/OnModify/OnDelete ## Avoid OnInsert/OnModify/OnDelete
The reason for this is, that it breaks the batch-calls: The reason for this is, that it breaks the batch-calls:
- Any "OnInsert" subscriber breaks the bulk inserts, simply because it needs to perform an operation after every record that was inserted - Any "OnInsert" subscriber breaks the bulk inserts, simply because it needs to perform an operation after every record that was inserted
- Any "OnModify" subscriber slows down the "ModifyAll", simply because it needs to perform an operation after every record that was modified. I fact: 1 SQL call is turned into a loop of SQL calls. - Any "OnModify" subscriber slows down the "ModifyAll", simply because it needs to perform an operation after every record that was modified. I fact: 1 SQL call is turned into a loop of SQL calls.
- Any "OnDelete" subscriber slows down the "DeleteAll", simply because it needs to perform an operation after every record that was deleted. I fact: 1 SQL call is turned into a loop of SQL calls. - Any "OnDelete" subscriber slows down the "DeleteAll", simply because it needs to perform an operation after every record that was deleted. I fact: 1 SQL call is turned into a loop of SQL calls.
Avoid subscribers to these events. Avoid subscribers to these events.
## [Discussions](https://github.com/microsoft/alguidelines/discussions/92)
You can discuss this guidelines [here](https://github.com/microsoft/alguidelines/discussions/92).
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.
## References ## References
The [Generic Method Pattern](https://alguidelines.dev/bcpatterns/generic-method-pattern/) The [Generic Method Pattern](https://alguidelines.dev/docs/patterns/generic-method-pattern/)

View file

@ -5,9 +5,8 @@ description: >
AL Code Best Practices AL Code Best Practices
--- ---
# Business Central Best Practices
This section will be cover things that aren't as simple as Design Patterns, but will help make sure your development is: This section will be cover things that aren't as simple as Design Patterns, but will help make sure your development is:
- high-performance - high-performance
- complies with good designs - complies with good designs
- has high maintainability - has high maintainability
@ -19,3 +18,7 @@ Generally, all readability rules are Microsoft style choices only. You can use t
## Performance ## Performance
Some guidelines are simply better for performance considerations rather than readability or anything else. In this section, let's look into some.. Some guidelines are simply better for performance considerations rather than readability or anything else. In this section, let's look into some..
## Discussion
All discussion related to Best Practice are to be found on the Github Repo's Discussion pages, found [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices)

View file

@ -0,0 +1,187 @@
---
title: "API Page / Query"
tags: ["AL","API"]
categories: ["Best Practice"]
---
_Created by Arend-Jan Kauffmann, Described by Arend-Jan Kauffmann_
## Description
API pages are different from UI pages. They require different properties and don't behave the same. Because API pages are used for integration with external applications, they should be treated as contracts. To achieve this, the following topics are important.
- Separate API app
- Page properties
- Versioning
- Field properties
- Default fields
## Separate API app
It's a good practice to develop API pages in a separate app instead of combining them in a solution. By doing so, it provides better maintainability and is a good way of separation of concerns.
## Page properties
An API page must define a minimum set of properties. Some of these properties will be part of the URL of the API endpoint. It is recommended to define the properties in the same order as they appear in the URL.
The properties that must be defined are:
- PageType = API / QueryType = API
- APIPublisher
- APIGroup
- APIVersion
- EntitySetName
- EntityName
- DelayedInsert (only Page)
- ODataKeyFields
### APIPublisher
The name of the API publisher is usually the company creating the API. It is the first custom part in the URL for a given endpoint. The value is case insensitive.
Example:
```al
APIPublisher = 'contoso';
```
### APIGroup
Sets the group of the API endpoint that page or query is exposed in. In the URL the APIGroup comes after the APIPublisher. It can be used to distinguish different API apps or groups of APIs from each other. The value is case insensitive.
Example:
```al
APIGroup = 'app1';
```
### APIVersion
Sets the version(s) of the API endpoint the page or query is exposed in. This property is not mandatory. If it is not specified, then APIs will be exposed as version 'beta'.
The APIVersion can be set to 'beta' or have the format 'vx.y'.
Example:
```al
APIVersion = 'beta';
```
or
```al
APIVersion = 'v1.0';
```
#### _Multiple API versions_
You should __never__ break existing versions. Any breaking change requires to create a new version.
It is possible to expose an API in multiple versions:
```al
APIVersion = 'beta', 'v1.0';
```
This allows to publish a new version of an API app without copying all individual objects and updating the version numbers. Only those API objects that are changed in a new version need to be copied. The other objects only need an addition to the APIVersion property to become available in the new version endpoint.
### EntitySetName
The EntitySetName is the plural entity name. Think of it as the name of the collection of entities. It is recommended to use camelCasing for this property. The value is case sensitive!
Example:
```al
EntitySetName = 'itemCategories';
```
### EntityName
The EntityName sets the singular entity name for the API page or query. This name is not used in the URL. Instead, the EntityName is used in the metadata information. It is recommended to use camelCasing for this property.
Example:
```al
EntityName = 'itemCategory';
```
### DelayedInsert
This property is required on an editable API page. It does not apply to an API query object. If ```Editable = false``` is set on the API page, then DelayedInsert is not required.
All APIs pages apply the behavior to first specify all field values and then insert the record at once.
Example:
```al
DelayedInsert = true;
```
### Full example
Together, the page properties look like:
```al
PageType = API;
APIPublisher = 'contoso';
APIGroup = 'app1';
APIVersion = 'v1.0';
EntitySetName = 'itemCategories';
EntityName = 'itemCategory';
DelayedInsert = true;
```
The full url will look like: ```https://{url}/api/contoso/app1/v1.0/companies({id})/itemCategories```
### ODataKeyFields
The ```EntitySetName``` property in the URL can be extended with an identifier to indicate a single record.
Example:
```
.../itemCategories(768b6173-9b19-40ea-8e5d-ce181ec0d645)
```
The property ```ODataKeyFields``` defines which field(s) will be used for the identifier value. It is highly recommended to always use the SystemId field for this property. The SystemId field is immutable and will never change for a record.
The field that is defined in this property should be part of the API page.
## Field properties
The base structure of an API page is similar to a UI list page:
```al
layout
{
area(Content)
{
repeater(records)
{
...
}
}
}
```
When specifying the fields there are some considerations to keep in mind.
```
field(displayName; Rec.Name) { }
```
There are no mandatory properties. The property ```ApplicationArea``` does not play a role in API pages, so it can be skipped. The property ```Caption``` is also optional and should only be used in case the external application requires captions and the caption should be different from the standard caption as defined in the table.
The name of the field, in the example above ```displayName```, should be defined in camelCasing. It may not contain spaces, dots, or other special characters.
It is common use to give certain fields a more describing name. Some examples are:
* id for field SystemId
* number for field "No."
* displayName for field Name
## Mandatory fields
These fields should always be part of the API Page:
* SystemId
* This field should be exposed with the name ```id```
* SystemModifiedAt
* This field should be exposed with the name ```lastModifiedDateTime```. If you choose a different name, then the webhook functionality will not work properly.
Example:
```al
layout
{
area(Content)
{
repeater(records)
{
field(id; Rec.SystemId) { }
field(lastModifiedDateTime; Rec.SystemModifiedAt) { }
}
}
}
```

View file

@ -1,6 +1,6 @@
--- ---
title: "begin as an afterword" title: "begin as an afterword"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
@ -26,9 +26,3 @@ When `begin` follows `then`, `else`, `do`, it should be on the same line, preced
... ...
end; end;
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=begin+as+an+After+Word+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,6 +1,6 @@
--- ---
title: "Begin-End - Compound Only" title: "Begin-End - Compound Only"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
@ -8,7 +8,9 @@ _Created by Microsoft, Described by waldo_
Only use begin..end to enclose [compound statements](https://docs.microsoft.com/en-us/cpp/c-language/compound-statement-c?view=msvc-170#:~:text=A%20compound%20statement%20%28also%20called%20a%20%22block%22%29%20typically,appear%20at%20the%20head%20of%20a%20compound%20statement.). Only use begin..end to enclose [compound statements](https://docs.microsoft.com/en-us/cpp/c-language/compound-statement-c?view=msvc-170#:~:text=A%20compound%20statement%20%28also%20called%20a%20%22block%22%29%20typically,appear%20at%20the%20head%20of%20a%20compound%20statement.).
## Bad code ## Example 1
### Bad code
```AL ```AL
if FindSet() then begin if FindSet() then begin
@ -18,7 +20,7 @@ if FindSet() then begin
end; end;
``` ```
## Good code ### Good code
```AL ```AL
if FindSet() then if FindSet() then
@ -27,7 +29,9 @@ if FindSet() then
until next() = 0; until next() = 0;
``` ```
## Bad code ## Example 2
### Bad code
```AL ```AL
if IsAssemblyOutputLine then begin if IsAssemblyOutputLine then begin
@ -35,7 +39,7 @@ if IsAssemblyOutputLine then begin
end; end;
``` ```
## Good code ### Good code
```AL ```AL
if IsAssemblyOutputLine then if IsAssemblyOutputLine then
@ -53,8 +57,9 @@ end else
(not X) (not X)
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=begin+end+compound+only+category%3A%22BC+Best+Practices%22) ## Tips
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices). The [AZ AL Dev Tools/AL Code Outline](https://marketplace.visualstudio.com/items?itemName=andrzejzwierzchowski.al-code-outline) extension adds two new commands to Visual Studio Code to remove begin..end around single statements.
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article. - `Remove Begin..End around Single Statements from the Active Editor` : removes begin..end around single statement from the current editor
- `Remove Begin..End around Single Statements from the Active Project` : removes begin..end around single statement from the current project

View file

@ -1,6 +1,6 @@
--- ---
title: "Binary Operator to Start Line" title: "Binary Operator to Start Line"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
@ -14,20 +14,14 @@ Do not start a line with a binary operator.
```AL ```AL
"Quantity to Ship" := "Quantity to Ship" :=
Quantity Quantity
- "Quantity Shipped" - "Quantity Shipped"
``` ```
## Good code ## Good code
```AL ```AL
"Quantity to Ship" := "Quantity to Ship" :=
Quantity - Quantity -
"Quantity Shipped" "Quantity Shipped"
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=binary+operator+to+start+line+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -0,0 +1,115 @@
---
title: "When not to use Blank Lines"
tags: ["AL","Readability"]
categories: ["Best Practice"]
---
## Description
Do not use blank lines:
- at the beginning or end of any functions (after `begin` and before `end`)
- inside multiline expression
- after blank lines
## Example 1
### Bad code
```al
procedure MATRIX_OnDrillDown(MATRIX_ColumnOrdinal: Integer)
begin
SetupDrillDownCol(MATRIX_ColumnOrdinal);
DrillDown(false, ValueType);
end;
```
### Good code
```al
procedure MATRIX_OnDrillDown(MATRIX_ColumnOrdinal: Integer)
begin
SetupDrillDownCol(MATRIX_ColumnOrdinal);
DrillDown(false, ValueType);
end;
```
## Example 2
### Bad code
```al
if NameIsValid and
Name2IsValid
then
```
### Good code
```al
if NameIsValid and
Name2IsValid
then
```
## Example 3
### Bad code
```al
var
GLSetup: Record "General Ledger Setup";
GLSetupRead: Boolean;
local procedure GetGLSetup()
begin
if not GLSetupRead then
GLSetup.Get();
GLSetupRead := true;
OnAfterGetGLSetup(GLSetup);
end;
[IntegrationEvent(false, false)]
local procedure OnAfterGetGLSetup(var GLSetup: Record "General Ledger Setup")
begin
end;
```
### Good code
```al
var
GLSetup: Record "General Ledger Setup";
GLSetupRead: Boolean;
local procedure GetGLSetup()
begin
if not GLSetupRead then
GLSetup.Get();
GLSetupRead := true;
OnAfterGetGLSetup(GLSetup);
end;
[IntegrationEvent(false, false)]
local procedure OnAfterGetGLSetup(var GLSetup: Record "General Ledger Setup")
begin
end;
```
## Tips
The [AZ AL Dev Tools/AL Code Outline](https://marketplace.visualstudio.com/items?itemName=andrzejzwierzchowski.al-code-outline) extension adds two new commands to Visual Studio Code to remove empty duplicate lines.
- `Remove Empty Lines from the Active Editor` : removes empty duplicate lines from the current editor
- `Remove Empty Lines from the Active Project` : removes empty duplicate lines from the current project

View file

@ -1,6 +1,6 @@
--- ---
title: "CASE Action on next line" title: "CASE Action on next line"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
@ -29,9 +29,3 @@ A CASE action should start on a line after the possibility.
Letter2 := '11'; Letter2 := '11';
end; end;
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=case+action+on+next+line+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,12 +1,13 @@
--- ---
title: "Comment Spacing" title: "Comment Spacing"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
Always start comments with // followed by one space character. Always start comments with // followed by one space character.
## Bad code ## Bad code
@ -15,15 +16,8 @@ Always start comments with // followed by one space character.
RowNo += 1000; //Move way below the budget RowNo += 1000; //Move way below the budget
``` ```
## Good code ## Good code
```al ```al
RowNo += 1000; // Move way below the budget RowNo += 1000; // Move way below the budget
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=comment+spacing+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,6 +1,6 @@
--- ---
title: "end else pair" title: "end else pair"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
@ -33,9 +33,3 @@ The `end else` pair should always appear on the same line.
... ...
end; end;
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=end+else/pair+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -0,0 +1,109 @@
---
title: "if not then exit"
tags: ["AL"]
categories: ["Best Practice"]
---
_Created by sirhc101, Described by sirhc101_
## Description
In general when we are working with tables we want to make sure, the filtered dataset includes records and does not result in a runtime error, so we use `if` to handle the result of `Find()`, `FindSet()`, `Get()`, etc.
This automatically causes on indent in source code and often the source code does not just contain one but two or more tables involved which leads to multi-level indentation.
Basically this is a result of bad coding structure but maybe sometimes necessary. On the other hand this causes multiple `end;` usages and leads to the usage of colorization and other helpers to see which `begin` belongs to which `end;`.
Instead of using `if (Record.FindSet()) then` to fetch records from a database it's good practice to use `if (not Record.FindSet()) then` following by an `exit();` to not further process the source code and make it clear for other developers where they can stop reading in certain cases.
Furthermore, this more or less automatically leads to smaller and better structured procedures and reduces the complexity of the source code.
## Bad code
```al
SalesHeader.Reset();
SalesHeader.SetRange("Document Type", SalesHeader."Document Type"::Order);
SalesHeader.SetRange(Status, SalesHeader.Status::Open);
if (SalesHeader.FindSet(false)) then begin
repeat
SalesLine.Reset();
SalesLine.SetRange("Document Type", SalesHeader."Document Type"::Order);
SalesLine.SetRange("Document No.", SalesHeader."No.");
if (SalesLine.FindSet(true)) then begin
repeat
DoSomething();
until SalesLine.Next() = 0;
end;
until SalesHeader.Next() = 0;
DoSomethingElse();
end;
```
or
```al
SalesLine.Reset();
SalesLine.SetRange("Document Type", SalesHeader."Document Type"::Order);
if (SalesLine.FindSet(true)) then begin
repeat
case SalesLine."Type" of
SalesLine."Type"::Item:
DoSomethingItem();
SalesLine."Type"::Resource:
DoSomethingResource();
end;
until SalesLine.Next() = 0;
end;
```
## Good code
```al
procedure DoSomethingSalesOrder()
var
SalesHeader: Record "Sales Header";
begin
SalesHeader.SetRange("Document Type", SalesHeader."Document Type"::Order);
SalesHeader.SetRange(Status, SalesHeader.Status::Open);
if (not SalesHeader.FindSet(false)) then
exit;
repeat
DoSomethingSalesLine(SalesHeader);
until SalesHeader.Next() = 0;
DoSomethingElse();
end;
procedure DoSomethingSalesLine(var SalesHeader: Record "Sales Header")
var
SalesLine: Record "Sales Line";
begin
SalesLine.Reset();
SalesLine.SetRange("Document Type", SalesHeader."Document Type"::Order);
SalesLine.SetRange("Document No.", SalesHeader."No.");
if (not SalesLine.FindSet(true)) then
exit;
repeat
DoSomething();
until SalesLine.Next() = 0;
end;
```
or
```al
SalesLine.SetRange("Document Type", SalesHeader."Document Type"::Order);
if (not SalesLine.FindSet(true)) then
exit;
repeat
case SalesLine."Type" of
SalesLine."Type"::Item:
DoSomethingItem();
SalesLine."Type"::Resource:
DoSomethingResource();
end;
until SalesLine.Next() = 0;
```

View file

@ -0,0 +1,60 @@
---
title: "IsTemporary record safeguard"
tags: ["AL"]
categories: ["Best Practice"]
---
_Created by Kine, Described by Kine_
## Description
When you are working with temporary tables or real tables, you can have code, where you assume that Record variable is or is not temporary. Best practice is to not assume, but test it to be sure. In history,
many developers went through painful period when they did unwanted "DeleteAll" over real table in production database, because they were only assuming something (mostly it happened only once to them).
Therefore it is good practice to use [Record.IsTemporary()](https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/record/record-istemporary-method) method to test this predicate, mainly when you are doing destructive action.
Another case when it is good practice to use this test is when you are subscribing to triggers on table. In most cases, you do not want to run your code when the trigger is running over temporary record. And you cannot assume, that
this specific table will not be used as temporary by someone else. Reacting to the trigger as if it was triggered by real table change could lead to corrupted data or unpredictable errors and the reason could be hard to find.
## Bad code
```al
ShouldBeTemporary.DeleteAll(true);
```
or
```al
[EventSubscriber(ObjectType::Table, Database::"Some Table", 'OnAfterInsertEvent', '', false, false)]
local procedure DoSomethingOnAfterInsertSomeTable(var Rec: Record "Some Table")
begin
DoSomething(Rec);
end;
```
## Good code
```al
if ShouldBeTemporary.IsTemporary() then
ShouldBeTemporary.DeleteAll(true);
```
or
```al
if not ShouldBeTemporary.IsTemporary() then
Error(RecNotTemporaryErr);
ShouldBeTemporary.DeleteAll(true);
```
or
```al
[EventSubscriber(ObjectType::Table, Database::"Some Table", 'OnAfterInsertEvent', '', false, false)]
local procedure DoSomethingOnAfterInsertSomeTable(var Rec: Record "Some Table")
begin
if Rec.IsTemporary() then
Exit;
DoSomething(Rec);
end;
```

View file

@ -0,0 +1,39 @@
---
title: "Keyboard Shortcuts"
tags: ["AL","Productivity"]
categories: ["Best Practice"]
---
_Created by Christian Lenz, Described by Christian Lenz_
## Description
To increase developer productivity while coding, use keyboard shortcuts that are available in the specific context to execute actions faster.
This is a selection of the community's favorites (more to come).
**Windows**
| What | Where | How |
|---|---|---|
| Delete word | Editor | CTRL + Backspace |
**VS Code**
| What | Where | How |
|---|---|---|
| Switch Tab | Editor | ALT + <Arrow Left/Right> |
| Move Line Up/Down | Editor | ALT + <Arrow Up/Down> |
| Copy Line Below/Above | Editor | ALT + SHIFT + <Arrow Up/Down> |
| Delete Line | Editor | CTRL + X (without selection) |
| Add Selection To Next Match | Editor | CTRL + D |
| Select All Occurences Of Find Match | Editor | CTRL + SHIFT + L |
| Add Cursors To Line Ends | Editor | SHIFT + ALT + I (after selecting lines) |
| Add Cursor Above/Below | Editor | CTRL + ALT + <Arrow Up/Down> |
| Place Multiple Cursors Manually | Editor | ALT + Click |
| Fast Scrolling | Editor | ALT + Mouse Wheel |
| Go To Symbol In File | Editor | CTRL + SHIFT + O |
| Breadcrumbs - Open And Select | Editor | CTRL + SHIFT + . |
| Go Back / Forward | Go To Definition | ALT + <Arrow Left/Right> |

View file

@ -1,12 +1,13 @@
--- ---
title: "Keyword Pairs - Indentation" title: "Keyword Pairs - Indentation"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
The `if..then` pair, `while..do` pair, and `for..do` pair must appear on the same line or the same level of indentation. If possible, you can align the lines it is even much more readable. The `if..then` pair, `while..do` pair, and `for..do` pair must appear on the same line or the same level of indentation. If possible, you can align the lines it is even much more readable.
## Bad code ## Bad code
@ -23,9 +24,3 @@ The `if..then` pair, `while..do` pair, and `for..do` pair must appear on the sam
(a = b) (a = b)
then then
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=keyword+pair+indentation+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,11 +1,12 @@
--- ---
title: "Line Start Keywords" title: "Line Start Keywords"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
<_Created by Microsoft, Described by waldo_\> _Created by Microsoft, Described by waldo_
## Description ## Description
The `end`, `if`, `repeat`, `for`, `while`, `else` and `case` statement should always start a line. The `end`, `if`, `repeat`, `for`, `while`, `else` and `case` statement should always start a line.
## Bad code ## Bad code
@ -28,10 +29,3 @@ The `end`, `if`, `repeat`, `for`, `while`, `else` and `case` statement should al
if IsSalesCycleCode then if IsSalesCycleCode then
ValidatSalesCycleCode(); ValidatSalesCycleCode();
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=line+start+keyword+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,12 +1,13 @@
--- ---
title: "Lonely Repeat" title: "Lonely Repeat"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
The `repeat` statement should always be alone on a line. The `repeat` statement should always be alone on a line.
## Bad code ## Bad code
@ -21,9 +22,3 @@ The `repeat` statement should always be alone on a line.
if ReservEntry.FindSet() then if ReservEntry.FindSet() then
repeat repeat
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=lonely+repeat+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,12 +1,13 @@
--- ---
title: "Named Invocations" title: "Named Invocations"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
When calling an object statically use the Object Name, not the Object Id. When calling an object statically use the Object Name, not the Object Id.
## Bad code ## Bad code
@ -21,8 +22,8 @@ When calling an object statically use the Object Name, not the Object Id.
Page.RunModal(Page::"Posted Sales Shipment Lines", SalesShptLine); Page.RunModal(Page::"Posted Sales Shipment Lines", SalesShptLine);
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=named+invocations+category%3A%22BC+Best+Practices%22) ## Tips
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices). The [BusinessCentral.LinterCop](https://marketplace.visualstudio.com/items?itemName=StefanMaron.businesscentral-lintercop) extension adds a new rule to check your code for hardcoded object IDs.
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article. - [LC0012](https://github.com/StefanMaron/BusinessCentral.LinterCop/wiki/LC0012): Using hardcoded IDs in functions like Codeunit.Run() is not allowed.

View file

@ -1,44 +1,41 @@
--- ---
title: "One Statement per Line" title: "One Statement per Line"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
A line of code should not have more than one statement. A line of code should not have more than one statement.
## Bad code ## Example 1
### Bad code
```al ```al
if OppEntry.Find('-') then exit; if OppEntry.Find('-') then exit;
``` ```
### Good code
## Good code
```al ```al
if OppEntry.Find('-') then if OppEntry.Find('-') then
exit; exit;
``` ```
## Bad code ## Example 2
### Bad code
```al ```al
TotalCost += Cost; TotalAmt += Amt; TotalCost += Cost; TotalAmt += Amt;
``` ```
### Good code
## Good code
```al ```al
TotalCost += Cost; TotalCost += Cost;
TotalAmt += Amt; TotalAmt += Amt;
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=one+statement+per+line+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,18 +1,19 @@
--- ---
title: "Seperate if and else" title: "Seperate if and else"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
`if` and `else` statements should be on separate lines. `if` and `else` statements should be on separate lines.
## Bad code ## Bad code
```al ```al
if Atom = '\>' then HasLogicalOperator := true else begin if Atom = '>' then HasLogicalOperator := true else begin
... ...
end; end;
``` ```
@ -20,16 +21,9 @@ _Created by Microsoft, Described by waldo_
## Good code ## Good code
```al ```al
if Atom = '\>' then if Atom = '>' then
HasLogicalOperator := true HasLogicalOperator := true
else begin else begin
... ...
end; end;
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=separate+if+and+else+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,45 +1,52 @@
--- ---
title: "Spacing Binary Operators" title: "Spacing Binary Operators"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
There must be exactly one space character on each side of a binary operator such as = + - AND OR =. The parameter comma operator however, should have a space after the comma. There must be exactly one space character on each side of a binary operator such as = + - AND OR =. The parameter comma operator however, should have a space after the comma.
## Bad code ## Example 1
### Bad code
```al ```al
"Line Discount %" := "Line Discount Amount"/"Line Value"*100; "Line Discount %" := "Line Discount Amount"/"Line Value"*100;
``` ```
## Good code ### Good code
```al ```al
"Line Discount %" := "Line Discount Amount" / "Line Value" * 100; "Line Discount %" := "Line Discount Amount" / "Line Value" * 100;
``` ```
## Bad code ## Example 2
### Bad code
```al ```al
StartDate := CalcDate('<+'+Format(Days+i)+'D\>',StartDate); StartDate := CalcDate('<+'+Format(Days+i)+'D\>',StartDate);
``` ```
## Good code ### Good code
```al ```al
StartDate := CalcDate('<+' + Format(Days + i) + 'D\>', StartDate); StartDate := CalcDate('<+' + Format(Days + i) + 'D\>', StartDate);
``` ```
## Bad code ## Example 3
### Bad code
```al ```al
StartDate:=0D; // Initialize StartDate:=0D; // Initialize
``` ```
## Good code ### Good code
```al ```al
StartDate := 0D; // Initialize StartDate := 0D; // Initialize

View file

@ -1,6 +1,6 @@
--- ---
title: "Suggested Abbreviations" title: "Suggested Abbreviations"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
@ -359,9 +359,3 @@ If there is no other choice, then use the suggestions below.
| % | Pct | | % | Pct |
| 3-tier | Three-Tier | | 3-tier | Three-Tier |
| Outlook Synch | Osynch | | Outlook Synch | Osynch |
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=abbreviations+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,12 +1,13 @@
--- ---
title: "Unnecessary else" title: "Unnecessary else"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
`else` should not be used when the last action in the `then` part is an `exit`, `break`, `skip`, `quit`, `error`. `else` should not be used when the last action in the `then` part is an `exit`, `break`, `skip`, `quit`, `error`.
## Bad code ## Bad code
@ -22,6 +23,7 @@ _Created by Microsoft, Described by waldo_
``` ```
## Good code ## Good code
```al ```al
procedure SomeProcedure() procedure SomeProcedure()
begin begin
@ -30,10 +32,3 @@ _Created by Microsoft, Described by waldo_
Error(BinCodeChangeNotAllowedErr, ...); Error(BinCodeChangeNotAllowedErr, ...);
end; end;
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=unnecessary+else+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,6 +1,6 @@
--- ---
title: "Unnecessary true/false" title: "Unnecessary true/false"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
@ -9,33 +9,30 @@ _Created by Microsoft, Described by waldo_
## Description ## Description
Do not use `true` or `false` keywords unnecessarily if the expression is already an logical expression. Do not use `true` or `false` keywords unnecessarily if the expression is already an logical expression.
## Bad code ## Example 1
### Bad code
```al ```al
if IsPositive() = true then if IsPositive() = true then
``` ```
## Good code ### Good code
```al ```al
if IsPositive() then if IsPositive() then
``` ```
## Example 2
## Bad code ### Bad code
```al ```al
if Complete <> true then if Complete <> true then
``` ```
## Good code ### Good code
```al ```al
if not Complete then if not Complete then
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=unnecessary+true+false+category%3A%22BC+Best+Practices%22)
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,12 +1,13 @@
--- ---
title: "Variable Naming" title: "Variable Naming"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
Variables that refer to a AL object must contain the objects name, abbreviated where necessary. Variables that refer to a AL object must contain the objects name, abbreviated where necessary.
A variable must begin with a capital letter. A variable must begin with a capital letter.
@ -15,34 +16,48 @@ Blanks, periods, and other characters (such as parentheses) that would make quot
If a variable is a compound of two or more words or abbreviations, each word or abbreviation should begin with a capital letter. If a variable is a compound of two or more words or abbreviations, each word or abbreviation should begin with a capital letter.
## Bad code ## Example 1
### Bad code
```al ```al
WIPBuffer: Record "Job WIP Buffer" WIPBuffer: Record "Job WIP Buffer"
``` ```
## Good code
### Good code
```al ```al
JobWIPBuffer: Record "Job WIP Buffer" JobWIPBuffer: Record "Job WIP Buffer"
``` ```
## Bad code
## Example 2
### Bad code
```al ```al
Postline: Codeunit "Gen. Jnl.-Post Line"; Postline: Codeunit "Gen. Jnl.-Post Line";
``` ```
## Good code
### Good code
```al ```al
GenJnlPostLine: Codeunit "Gen. Jnl.-Post Line"; GenJnlPostLine: Codeunit "Gen. Jnl.-Post Line";
``` ```
## Bad code
## Example 3
### Bad code
```al ```al
"Amount (LCY)": Decimal; "Amount (LCY)": Decimal;
``` ```
## Good code
### Good code
```al ```al
AmountLCY: Decimal; AmountLCY: Decimal;
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=one+variable+naming+category%3A%22BC+Best+Practices%22) ## Tips
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices). The [AL Variable Helper](https://marketplace.visualstudio.com/items?itemName=rasmus.al-var-helper) extension provides Intellisense support to assign correct variable names in AL.
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,12 +1,13 @@
--- ---
title: "Variables Declarations Order" title: "Variables Declarations Order"
tags: ["Readability"] tags: ["AL","Readability"]
categories: ["Best Practice"] categories: ["Best Practice"]
--- ---
_Created by Microsoft, Described by waldo_ _Created by Microsoft, Described by waldo_
## Description ## Description
Variables declarations should be ordered by type. In general, object and complex variable types are listed first followed by simple variables. The order should be: Variables declarations should be ordered by type. In general, object and complex variable types are listed first followed by simple variables. The order should be:
- Record - Record
@ -25,7 +26,6 @@ Variables declarations should be ordered by type. In general, object and complex
(Ref: [Microsoft Docs](https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/analyzers/codecop-aa0021)) (Ref: [Microsoft Docs](https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/analyzers/codecop-aa0021))
## Bad code ## Bad code
```al ```al
@ -40,8 +40,9 @@ Variables declarations should be ordered by type. In general, object and complex
StartingDateFilter: Text; StartingDateFilter: Text;
``` ```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=one+variables+declarations+order+category%3A%22BC+Best+Practices%22) ## Tips
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices). The [AZ AL Dev Tools/AL Code Outline](https://marketplace.visualstudio.com/items?itemName=andrzejzwierzchowski.al-code-outline) extension adds two new commands to Visual Studio Code to sorts variables.
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article. - `Sort Variables in the Active Editor` : sorts variables in the current editor
- `Sort Variables in the Active Project` : sorts variables in the current project

View file

@ -38,6 +38,66 @@ Results in:
end; end;
``` ```
## Diagrams with Mermaid
When providing a documentation, diagrams come in handy. [Mermaid](https://mermaid-js.github.io/mermaid/#/) lets you create diagrams and visualizations using text and code.
For example the following markdown section:
````
```mermaid
classDiagram
Animal <|-- Duck
Animal <|-- Fish
Animal <|-- Zebra
Animal : +int age
Animal : +String gender
Animal: +isMammal()
Animal: +mate()
class Duck{
+String beakColor
+swim()
+quack()
}
class Fish{
-int sizeInFeet
-canEat()
}
class Zebra{
+bool is_wild
+run()
}
```
````
Results in:
```mermaid
classDiagram
Animal <|-- Duck
Animal <|-- Fish
Animal <|-- Zebra
Animal : +int age
Animal : +String gender
Animal: +isMammal()
Animal: +mate()
class Duck{
+String beakColor
+swim()
+quack()
}
class Fish{
-int sizeInFeet
-canEat()
}
class Zebra{
+bool is_wild
+run()
}
```
Can't wait to get started? Use the Mermaid [Live Editor](https://mermaid.live/edit).
## Hugo Shortcodes ## Hugo Shortcodes
Since we're using "Hugo", we can use it's shortcode. Here is a reference: [https://gohugo.io/content-management/shortcodes/](https://gohugo.io/content-management/shortcodes/) Since we're using "Hugo", we can use it's shortcode. Here is a reference: [https://gohugo.io/content-management/shortcodes/](https://gohugo.io/content-management/shortcodes/)

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View file

@ -0,0 +1,57 @@
---
title: "Manually on Windows 11"
---
This guide will walk You thrugh installing Hugo on a Windows 11 PC. For the official install guide, You can wisit <https://gohugo.io/getting-started/installing/>.
## Download Binaries
The path of least resistance is to just download the .zip file from the official Hugo GitHub Repository [here](https://github.com/gohugoio/hugo/releases).
The theme that are used, needs the extended version of Hugo, so make sure to download the **extended** version by ensuring the file name starts with `hugo_extended...`
{{% alert title="info" color="info" %}}
For the purpose of this install guide, we are assuming You will want to follow the "standard" used by Hugo for installing. We will be creating a `Hugo` folder in the root of `C:\`. That folder will have a `Bin` folder for the binaries, and a `Sites` folder for each website You are building.
Once You are done, You should have a folder structure that looks like this:
```text
C:\Hugo
├── Bin # Binaries
└┬─ Sites # Hugo Site Repositories
└── alguidelines # Hugo Source for alguidelines.dev
```
{{% /alert %}}
![image](SelectExtended.png)
After downloading the .zip file, extract the zip-file to `c:\Hugo\Bin`
![image](Extract.png)
![image](ExtractToBin.png)
## Add Hugo to Path
After copying the binaries to Your PC, You will need to add Hugo binaries to the `%PATH%` system environment variables.
To do that, search for `environment`
![image](SearchForEnv.png)
once you see the `Edit the system environment variables`, open it and select `Environment Variables`
![image](SystemProperties.png)
Once the Environment Variables screen is open, highlight the `Path` lines and press the `Edit...` button
![image](EnvironmentVariables.png)
Now press `New` and add the `C:\Hugo\Bin` to the path. Press `OK` and `OK` to save the new `Path`
![image](EnvironmentVariablesPath.png)
Once complete. You should now be able to preview the Hugo site on <http://localhost:1313> by opening a command promt, and open the `C:\Hugo\Sites\alguidelines` folder and execute `Hugo Serve`
![image](HugoServe.png)

View file

@ -0,0 +1,35 @@
---
Title: Devcontainer with VS Code
---
## Use a local devcontainer
If you don't want any local setup (apart from Docker Desktop), but still run your own Hugo instance, you can make use of the preconfigured devcontainer. If you want to learn more about the concept, visit [https://code.visualstudio.com/docs/remote/containers](https://code.visualstudio.com/docs/remote/containers). To use it, you need to take the following steps:
1. Start [Docker Desktop](https://www.docker.com/products/docker-desktop) and [switch to Linux containers](https://docs.docker.com/desktop/windows/#switch-between-windows-and-linux-containers) by right-clicking on the Docker logo in the system tray and selecting "Switch to Linux containers...". If you only see "Switch to Windows containers...", then you are already switched to Linux containers. If anything goes wrong, check if you are on the latest version of Docker Desktop and have [the WSL2 integration enabled](https://docs.docker.com/desktop/windows/wsl/#install). If you have all that in place and it still doesn't work, check the extended installation documentation [here](https://code.visualstudio.com/docs/remote/containers#_installation)
{{% alert title="Consequences of switching" color="info" %}}
When switching to Linux, you will probably see a warning that tells you that you "will not be able to manage the Windows containers until you switch back to Windows containers". That means that the Docker Desktop management GUI can only show either the Windows containers or the Linux containers and if you switch to Linux, you consequently won't see the Windows containers until you switch back. But the Windows containers will continue to run, you won't loose data and you can keep using them e.g. for Business Central development, you just can't manage them through the Docker Desktop GUI
{{% /alert %}}
2. Install the [Remote development extension pack](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack) in Visual Studio Code
3. Run the action "Remote containers: Clone Repository in Container Volume" and select the fork you created. If you haven't done that before, go through the [docs](https://alguidelines.dev/docs/contributing/forkandpr/#step-1-fork).
4. Wait for a bit. When you do this for the first time, it can take a couple of minutes. Next time it will be faster...
5. After a while, you will have VS Code with the cloned repository and the terminal should show something like "Done. Press any key to close the terminal."
6. Run the action "Tasks: Run task" and select "Start local Hugo Server" from the list. If you don't see that entry, you might have to reload your VS Code window and try again
7. After Hugo has generated the site, you will get a notification that offers you to "Open a browser". Click on that and you will see your local instance of the AL guidelines! Again, on the first try it will be a bit slow and sluggish, but the second one should be fast.
8. Now you can make changes and just save them. If you open the terminal, you will see a message that tells you that a change was detected and the site was rebuilt. After that, the change should automatically appear in your browser
Here is a walkthrough of the full process:
<video width=100% controls>
<source src="alguidelines walkthrough.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
## Use GitHub Codespaces
What is also great about this, is that you can also use [GitHub Codespaces](https://github.com/features/codespaces) with that setup. In that case, steps 1-5 become two clicks... Here is another full walkthrough:
<video width=100% controls>
<source src="alguidelines codespace.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

View file

@ -0,0 +1,22 @@
---
Title: Powershell on Windows 11
description: >
Install Hugo with a simple Powershell Script and chocolatey
---
It is possible to use a powershell script and Chocolatey to install and other dependencies. Execute the following script:
```powershell
Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
choco install -y nodejs
choco install -y hugo-extended
```
Once complete, in root of of the repository execute the following commands
```powershell
git submodule update --init --recursive --depth 1
npm install
```

View file

@ -0,0 +1,9 @@
---
title: Install Hugo
---
There are multiple ways to install Hugo for you to properly preview your contributions. Please select the scenario that matches your setup.
For the official install guide, you can visit <https://gohugo.io/getting-started/installing/>
{{< youtube G7umPCU-8xc >}}

View file

@ -0,0 +1,31 @@
---
title: "Title Here"
tags: ["AL"]
categories: ["Best Practice"]
---
<!-- This is a guideline, some parts are optional (if there's no content, remove the whole paragraph). -->
<!-- The "Readability" and "Performance" tags are often used. You can, however, add multiple tags, but please do not change the Category -->
_Created by <!-- John Smith --><!--, Cronus International.--> Described by <!-- Jane Doe--><!--, Contoso, LLC-->_
## Description
In depth description on what this Pattern is all about
- basic components
- how the interact
- steps to implement
- considerations to take
## Bad code
```al
PutCodeblocksHere()
```
## Good code
```al
PutCodeblocksHere()
```

View file

@ -1,36 +0,0 @@
+++
title = "Title of the Guideline"
weight = 1180
+++
This is a guideline, some parts are optional (if there's no content, remove the whole paragraph).
<_Created by (company), Described by (company)_\>
## Description
In depth description on what this Pattern is all about
- basic components
- how the interact
- steps to implement
- considerations to take
## Bad code
```al
PutCodeblocksHere()
```
## Good code
```al
PutCodeblocksHere()
```
## [Discussions](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices?discussions_q=TITLEOFYOURGUIDELINEGOESHERE+category%3A%22BC+Best+Practices%22)
<Please replace the "TITLEOFYOURGUIDELINEGOESHERE" in the link above, with the Title+of+the+Guideline (indeed, with "space" replaced by a "+") - and remove this line. \>
You can find discussions on all "Best Practices" [here](https://github.com/microsoft/alguidelines/discussions/categories/bc-best-practices).
If you don't find the discussion of this guideline, please feel free to create a new one with the same title as this article.

View file

@ -1,10 +1,12 @@
+++ ---
title = "Title of the pattern" title: "Title Here"
weight = 1180 tags: ["AL"]
+++ categories: ["Pattern"]
This is a guideline, some parts are optional (if there's no content, remove the whole paragraph). ---
<_Created by (company), Described by (company)_\> <!-- This is a guideline, some parts are optional (if there's no content, remove the whole paragraph). -->
_Created by <!-- John Smith --><!--, Cronus International.--> Described by <!-- Jane Doe--><!--, Contoso, LLC-->_
## Abstract ## Abstract
@ -21,6 +23,7 @@ What happens before this pattern is used? How can it go wrong? 1-5 lines.
## Description ## Description
In depth description on what this Pattern is all about In depth description on what this Pattern is all about
- basic components - basic components
- how the interact - how the interact
- steps to implement - steps to implement
@ -41,7 +44,3 @@ Usually, there are occasions where NOT to implement the pattern. List the disad
## List of references ## List of references
Youtube-link? BaseApp? Tweet? ... Youtube-link? BaseApp? Tweet? ...
## Discussions
Create a discussions-page of your pattern, and add the sentence "You can discuss this pattern [here](https://github.com/microsoft/alguidelines/discussions/42)" with the right link to that discussions-page.

View file

@ -1,14 +1,12 @@
+++ ---
chapter = true title: "Templates"
pre = "<b><i class='fas fa-clone'></i> </b>" ---
title = "Templates"
weight = 100
+++
# Templates We have created some template-files that you can simply copy and use. Look at them as "Patterns for describing patterns"
We have foreseen some template-files that you can simply copy and use. Look at them as "Patterns for describing patterns" 😉. We currently offer the following templates:
We have foreseen a Template: - for [Patterns](/contributing/templates/patterns/) ([raw](https://raw.githubusercontent.com/microsoft/alguidelines/main/content/docs/Contributing/Templates/Patterns/index.md))
- for [patterns](/contributing/templates/patterns/) - for [Best Practice](/contributing/templates/bestpractice/) ([raw](https://raw.githubusercontent.com/microsoft/alguidelines/main/content/docs/Contributing/Templates/BestPractice/index.md))
- for [guidelines](/contributing/templates/guidelines/)
opening the "raw" link, will allow for the best copy/paste result.

View file

@ -2,6 +2,7 @@
chapter = true chapter = true
title = "2. Anti-Patterns" title = "2. Anti-Patterns"
weight = 130 weight = 130
tags = ["C/AL"]
+++ +++
Some of the software development practices, had **not** stood the test of time. Despite that, some are still being used today by developers everywhere. Some of the software development practices, had **not** stood the test of time. Despite that, some are still being used today by developers everywhere.

View file

@ -1,6 +1,7 @@
+++ +++
title = "Nav Upgrade" title = "Nav Upgrade"
weight = 840 weight = 840
tags = ["C/AL"]
+++ +++
## Anti-Patterns in NAV Upgrade ## Anti-Patterns in NAV Upgrade

View file

@ -1,6 +1,7 @@
+++ +++
title = "Reusable Bugs" title = "Reusable Bugs"
weight = 1020 weight = 1020
tags = ["C/AL"]
+++ +++
_By Bogdana Botez, Andreas Moth, Eric Wauters (waldo), Elly Nkya, Nikola Kukrika_ _By Bogdana Botez, Andreas Moth, Eric Wauters (waldo), Elly Nkya, Nikola Kukrika_

View file

@ -2,6 +2,8 @@
chapter = true chapter = true
title = "3. CAL Coding Guidelines" title = "3. CAL Coding Guidelines"
weight = 150 weight = 150
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
We've decided to publish our current C/AL coding guidelines. They are actual, as per January 2015 when this is published (but might fall out of sync as time goes by). We've decided to publish our current C/AL coding guidelines. They are actual, as per January 2015 when this is published (but might fall out of sync as time goes by).

View file

@ -1,6 +1,8 @@
+++ +++
title = "Design" title = "Design"
weight = 490 weight = 490
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
## C/AL Coding Guidelines ## C/AL Coding Guidelines

View file

@ -1,6 +1,8 @@
+++ +++
title = "By Reference Parameters" title = "By Reference Parameters"
weight = 280 weight = 280
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Do not declare parameters by reference if their values are not intended to be changed. Do not declare parameters by reference if their values are not intended to be changed.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Class Coupling" title = "Class Coupling"
weight = 320 weight = 320
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Do not write functions that have high class coupling. This makes the code hard to maintain. Do not write functions that have high class coupling. This makes the code hard to maintain.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Cyclomatic Complexity" title = "Cyclomatic Complexity"
weight = 460 weight = 460
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Do not write functions that have high cyclomatic complexity. This makes the code hard to maintain. Do not write functions that have high cyclomatic complexity. This makes the code hard to maintain.

View file

@ -1,5 +1,7 @@
+++ +++
title = "Encapsulate Local Functionality" title = "Encapsulate Local Functionality"
weight = 530 weight = 530
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Any function used local must be defined as local. Any function used local must be defined as local.

View file

@ -1,6 +1,8 @@
+++ +++
title = "FINDSET FINDFIRST FINDLAST" title = "FINDSET FINDFIRST FINDLAST"
weight = 600 weight = 600
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
FINDSET, FIND('+') or FIND('-') should only be used when NEXT is used and vice versa. FINDSET, FIND('+') or FIND('-') should only be used when NEXT is used and vice versa.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Initialized Variables" title = "Initialized Variables"
weight = 660 weight = 660
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Variables should always be set to a specific value, before they are used. Variables should always be set to a specific value, before they are used.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Maintainability Index" title = "Maintainability Index"
weight = 770 weight = 770
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
[Maintainability Index][anchor0]: Do not write functions that have a very low maintainability index. This makes the code hard to maintain. [Maintainability Index][anchor0]: Do not write functions that have a very low maintainability index. This makes the code hard to maintain.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Parameter Placeholders" title = "Parameter Placeholders"
weight = 920 weight = 920
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
The number of parameters passed to a string must match the placeholders. The number of parameters passed to a string must match the placeholders.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Static Object Invocation" title = "Static Object Invocation"
weight = 1160 weight = 1160
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Call objects statically whenever possible. It reduces extra noise and removes extra variables. Downside: changing the name of the object which is called statically will need a code update. Call objects statically whenever possible. It reduces extra noise and removes extra variables. Downside: changing the name of the object which is called statically will need a code update.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Unreachable Code" title = "Unreachable Code"
weight = 1310 weight = 1310
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Do not write code that will never be hit. Do not write code that will never be hit.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Unused Initialized Variables" title = "Unused Initialized Variables"
weight = 1320 weight = 1320
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
The value assigned to a variable must be used. Else the variable is not necessary. The value assigned to a variable must be used. Else the variable is not necessary.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Unused Variables" title = "Unused Variables"
weight = 1330 weight = 1330
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Do not declare variables that are unused. Do not declare variables that are unused.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Variable Capacity Mismatch" title = "Variable Capacity Mismatch"
weight = 1410 weight = 1410
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Do not assign a value to a variable whose capacity is smaller. Do not assign a value to a variable whose capacity is smaller.

View file

@ -1,6 +1,8 @@
+++ +++
title = "WITH Scope Name Collision" title = "WITH Scope Name Collision"
weight = 1450 weight = 1450
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Do not use the WITH scope when it has a variable whose name is the same as a local variable. This can lead to wrong code assumptions. Do not use the WITH scope when it has a variable whose name is the same as a local variable. This can lead to wrong code assumptions.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Internally used DotNet Types" title = "Internally used DotNet Types"
weight = 690 weight = 690
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
_(Dynamics NAV 2015)_ _(Dynamics NAV 2015)_

View file

@ -1,6 +1,8 @@
+++ +++
title = "Internationalization" title = "Internationalization"
weight = 700 weight = 700
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
## C/AL Coding Guidelines ## C/AL Coding Guidelines

View file

@ -1,6 +1,8 @@
+++ +++
title = "Using Calcdate" title = "Using Calcdate"
weight = 1370 weight = 1370
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
CALCDATE should only be used with DateFormula variables. Alternatively the string should be enclosed using the <> symbols. CALCDATE should only be used with DateFormula variables. Alternatively the string should be enclosed using the <> symbols.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Localizability" title = "Localizability"
weight = 750 weight = 750
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
## C/AL Coding Guidelines ## C/AL Coding Guidelines

View file

@ -1,6 +1,8 @@
+++ +++
title = "CaptionML on System Pages" title = "CaptionML on System Pages"
weight = 300 weight = 300
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
CaptionML should always be specified on a page field for a system table. By default, system tables do not have captions, so if you need to use them in the UI then captions need to be added. CaptionML should always be specified on a page field for a system table. By default, system tables do not have captions, so if you need to use them in the UI then captions need to be added.

View file

@ -1,6 +1,8 @@
+++ +++
title = "FIELDCAPTION and TABLECAPTION" title = "FIELDCAPTION and TABLECAPTION"
weight = 580 weight = 580
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
For user messages, errors etc., use FIELDCAPTION not FIELDNAME and TABLECAPTION not TABLENAME. For user messages, errors etc., use FIELDCAPTION not FIELDNAME and TABLECAPTION not TABLENAME.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Global Text Constants" title = "Global Text Constants"
weight = 610 weight = 610
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Declare Text Constant as global variables. Declare Text Constant as global variables.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Use Text Constants" title = "Use Text Constants"
weight = 1360 weight = 1360
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
Pass user messages using Text Constants. It makes translation easy. Pass user messages using Text Constants. It makes translation easy.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Using OptionCaptionML" title = "Using OptionCaptionML"
weight = 1380 weight = 1380
tags = ["C/AL"]
categories = ["Best Practice"]
+++ +++
The OptionCaptionML should be filled in for sourceexpression using option data types. The OptionCaptionML should be filled in for sourceexpression using option data types.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Readability" title = "Readability"
weight = 980 weight = 980
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
## C/AL Coding Guidelines ## C/AL Coding Guidelines

View file

@ -1,6 +1,8 @@
+++ +++
title = "Begin as an 'After Word'" title = "Begin as an 'After Word'"
weight = 230 weight = 230
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
When BEGIN follows THEN, ELSE, DO, it should be on the same line, preceded by one space character. When BEGIN follows THEN, ELSE, DO, it should be on the same line, preceded by one space character.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Begin-End - Compound Only" title = "Begin-End - Compound Only"
weight = 240 weight = 240
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
Only use BEGIN..END to enclose compound statements. Only use BEGIN..END to enclose compound statements.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Binary Operator to Start Line" title = "Binary Operator to Start Line"
weight = 250 weight = 250
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
Do not start a line with a binary operator. Do not start a line with a binary operator.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Blank Lines" title = "Blank Lines"
weight = 260 weight = 260
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
Do not use blank lines at the beginning or end of any functions, after BEGIN, before END, or inside multiline expressions. Do not use blank lines at the beginning or end of any functions, after BEGIN, before END, or inside multiline expressions.

View file

@ -1,6 +1,8 @@
+++ +++
title = "CASE Action" title = "CASE Action"
weight = 310 weight = 310
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
A CASE action should start on a line after the possibility. A CASE action should start on a line after the possibility.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Colon usage in CASE" title = "Colon usage in CASE"
weight = 340 weight = 340
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
The last possibility on a CASE statement must be immediately followed by a colon. The last possibility on a CASE statement must be immediately followed by a colon.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Comments inside Curly Brackets" title = "Comments inside Curly Brackets"
weight = 350 weight = 350
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
Never use curly bracket comments. During development, the "Block comment" functionality can be used instead. However, in production code, block comments are not recommended. Never use curly bracket comments. During development, the "Block comment" functionality can be used instead. However, in production code, block comments are not recommended.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Comment Spacing" title = "Comment Spacing"
weight = 360 weight = 360
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
Always start comments with // followed by one space character. Always start comments with // followed by one space character.

View file

@ -1,6 +1,8 @@
+++ +++
title = "END ELSE Pair" title = "END ELSE Pair"
weight = 540 weight = 540
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
The END ELSE pair should always appear on the same line. The END ELSE pair should always appear on the same line.

View file

@ -1,6 +1,8 @@
+++ +++
title = "Indentation" title = "Indentation"
weight = 650 weight = 650
tags = ["C/AL","Readability"]
categories = ["Best Practice"]
+++ +++
In general, use an indentation of two space characters. Logical expressions in the IF, WHILE, and UNTIL parts are indented at least 3, 6, and 6 spaces respectively. In general, use an indentation of two space characters. Logical expressions in the IF, WHILE, and UNTIL parts are indented at least 3, 6, and 6 spaces respectively.

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