{"title":"Adopting namespaces in AL","url":"https://jonas-paprotka.de/docs/dev-itpro/developer/devenv-namespaces-structure/","by":"JOP-AL","license":"Copyright (c) Microsoft Corporation. CC BY 4.0, https://creativecommons.org/licenses/by/4.0/; code samples MIT. From https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-namespaces-structure, MicrosoftDocs/dynamics365smb-devitpro-pb at 828b6ee (2026-11-19). Changed: includes filled in, links to this site, and for agents shortened without dropping a fact.","credit":"Microsoft Corporation, CC BY 4.0","origin":"https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-namespaces-structure","source":{"name":"Business Central developer and IT pro docs","repo":"https://github.com/MicrosoftDocs/dynamics365smb-devitpro-pb","commit":"828b6ee72fcd75755627cd6011f3d20899217ab2","date":"2026-11-19"},"checked":"2026-11-19","description":"Learn about features, tools, and best practices for structuring and adopting namespaces in your AL code for Business Central.","date":"2026-06-09","meta":{"topic":"concept-article"},"outline":[{"level":1,"title":"Adopting namespaces in AL","slug":"adopting-namespaces-in-al","at":0,"chars":10074},{"level":2,"title":"Using a code action for automated namespace addition","slug":"using-a-code-action-for-automated-namespace-addition","at":653,"chars":2468},{"level":3,"title":"Namespace resolution logic","slug":"namespace-resolution-logic","at":949,"chars":1580},{"level":3,"title":"Example workflow","slug":"example-workflow","at":2529,"chars":592},{"level":2,"title":"Using a PowerShell script for bulk namespace addition","slug":"using-a-powershell-script-for-bulk-namespace-addition","at":3121,"chars":3857},{"level":2,"title":"Organize using statements","slug":"organize-using-statements","at":6978,"chars":592},{"level":3,"title":"Before sorting","slug":"before-sorting","at":7247,"chars":162},{"level":3,"title":"After sorting","slug":"after-sorting","at":7409,"chars":161},{"level":2,"title":"Best practices","slug":"best-practices","at":7570,"chars":625},{"level":2,"title":"Support for fully qualified names","slug":"support-for-fully-qualified-names","at":8195,"chars":1767},{"level":3,"title":"Running objects by fully qualified name","slug":"running-objects-by-fully-qualified-name","at":8553,"chars":903},{"level":3,"title":"Runtime namespace properties","slug":"runtime-namespace-properties","at":9456,"chars":506},{"level":2,"title":"Related information","slug":"related-information","at":9962,"chars":112}],"text":"# Adopting namespaces in AL\n> APPLIES TO: Business Central 2023 release wave 2 (version 23) and later\nNamespaces are used to organize code into logical groups and hierarchies and they ensure uniqueness in code names and allow reuse of names in different contexts. Namespaces also provide structure for the code base, making it easier to navigate and understand. See Namespaces in AL<devenv-namespaces-overview>.\nSeveral features and tools are available to help you progressively adopt namespaces in your AL projects. These tools automate repetitive tasks and provide guidance to streamline the transition of your codebase to use namespaces effectively.\n## Using a code action for automated namespace addition\n> APPLIES TO: Business Central 2026 release wave 1 and later\nA code action automatically adds namespaces to AL files that are missing them, helping you quickly bring your codebase into compliance with CodeCop rule analyzers/codecop-aa0247.\n### Namespace resolution logic\nWhen you invoke the code action, the system resolves the appropriate namespace using the following priority:\n1. Namespace template - The system reads and parses the al.namespaceTemplate setting. Use the `$(parentfolder)` placeholder to dynamically insert the parent directory name of the AL file. The value substituted for `$(parentfolder)` is normalized into a valid namespace identifier by using the same rules as the publisher/projectname fallback. The system accepts folder names that use kebab case, contain spaces, or start with a digit (for example `customer-pages`, `Sales App`, `1Sales`).\n2. Sibling file analysis - If the namespace template isn't defined or doesn't resolve to a valid identifier, the system examines other AL files in the same folder, extracts their namespace declarations, and uses the longest common namespace prefix.\n3. Publisher and project name - If no sibling files exist or they don't have a common namespace, the system falls back to publisher.projectname from app.json. The system splits both values on `.` and normalizes each segment into a valid namespace identifier. The system drops leading nonletter characters (digits, underscores, punctuation), collapses runs of disallowed characters into a single _, and removes trailing disallowed characters. For example, `\"My $$ Company\"` becomes My_Company and `\"1Sales\"` becomes Sales.\n4. Default namespace fallback - If none of the other resolution steps produce a valid namespace, the code action falls back to Default.Namespace so the action is always available.\n### Example workflow\nConsider a project structure like this:\n```\nMyApp/\n├── src/\n│   ├── Sales/\n│   │   ├── SalesOrder.Codeunit.al\n│   │   └── SalesInvoice.Codeunit.al\n│   └── Inventory/\n│       └── ItemCard.Page.al\n```\nIf your al.namespaceTemplate is set to `\"MyCompany.$(parentfolder)\"`, the code action suggests:\n MyCompany.Sales for files in the Sales folder\n MyCompany.Inventory for files in the Inventory folder\nIf the template isn't set and the file SalesOrder.Codeunit.al already defines a namespace, the code action suggests the same namespace for the SalesInvoice.Codeunit.al file.\n## Using a PowerShell script for bulk namespace addition\nFor most scenarios, the code action described in the previous section in combination with the al.namespaceTemplate setting should suffice. However, for situations where you require more granular control that can't be expressed through the namespaceTemplate configuration, we're sharing a PowerShell script that allows you to specify namespaces for multiple objects at a time, using your folder structure. Usually code is divided into folders according to some kind of structure, which is often what you would like to replicate to some degree in your namespaces.\nThe script shown in this article, allows you to specify what namespace to assign all your AL objects within a folder. After you run the script, you can then customize it a bit further. We recommend doing a commit once you have found the proper namespaces. You can then use the code action to apply using statements to your application.\nThe script takes a .csv file as input, which specifies what namespace to give to each file within a folder. The .csv file should contain a folder name and a namespace, as illustrated in the following example:\nFolder|Namespace\nMicrosoft Entra ID Graph|System.Azure.Identity\nMicrosoft Entra ID Licensing|System.Azure.Identity\nData Archive|System.DataAdministration\nRetention Policy|System.DataAdministration\nSharePoint|System.Integration.Sharepoint\n```csv\nFolder,Namespace\nMicrosoft Entra ID Graph,System.Azure.Identity\nMicrosoft Entra ID Licensing,System.Azure.Identity\nData Archive,System.DataAdministration\nRetention Policy,System.DataAdministration\nSharePoint,System.Integration.Sharepoint\n```\nCopy and paste the following code lines into your preferred script editor, then save the file as a .ps1 file. Now, open PowerShell as an administrator, locate the folder of the script, and run the script with the following command: `.\\<scriptname>.ps1`. The script prompts you to specify the .csv file and the base path of your application. The script goes through all the files in the base path and assigns the namespaces specified in the .csv file based on the given folder names.\n```powershell\nparam\n(\n    [Parameter(Mandatory=$true)]\n    [string] $CsvMappingFile,\n    [Parameter(Mandatory=$true)]\n    [string] $BasePath,\n    [ValidateSet(\"Add\",\"Ignore\")]\n    [string] $License = \"Ignore\",\n    [char] $Delimiter = \",\"\n)\n\n$files = Import-Csv $CsvMappingFile -Delimiter $Delimiter\n\n$licenseText =\n        \"// ------------------------------------------------------------------------------------------------`r`n\" +\n        \"// Copyright (c) <insert copyright>.`r`n\" +\n        \"// <Insert license>`r`n\" +\n        \"// ------------------------------------------------------------------------------------------------`r`n\"\n\nforeach ($file in $files) {\n    $folder = $file.Folder\n    $namespace = $file.Namespace\n    $namespaceLine = \"namespace $namespace;`r`n\"\n\n    $folderPath = Join-Path $BasePath $folder\n    $alFiles = Get-ChildItem -Path $folderPath -Filter \"*.al\" -File -Recurse\n\n    foreach ($alFile in $alFiles) {\n        $path = $alFile.FullName\n        $content = Get-Content $path -Raw\n\n        if ($content.IndexOf($licenseText) -eq -1) { # The file doesn't a contain license statement\n            if ($License -eq \"Ignore\") {\n                $content = $namespaceLine + $content\n            }\n            else {$content = $licenseText + \"`r`n\" + $namespaceLine + $content # Add a license statement\n            }\n        }\n        else {\n            $content = $content.Replace($licenseText, $licenseText + \"`r`n\" + $namespaceLine) # Keep the license and add a namespace\n        }\n\n        $content | Set-Content $path -NoNewline\n    }\n}\n\n```\nYou're now ready to open Visual Studio Code and use the AL code actions to apply all the missing using statements. See AL code actions<devenv-code-actions>.\n## Organize using statements\nTo maintain clean and readable code, especially in files with many namespace imports, keeping using statements alphabetically sorted is a good practice. A code action is available to automatically sort your using statements alphabetically.\n### Before sorting\n```al\nusing Microsoft.Sales.Document;\nusing System.Utilities;\nusing Microsoft.Inventory.Item;\nusing Microsoft.Finance.GeneralLedger.Setup;\n```\n### After sorting\n```al\nusing Microsoft.Finance.GeneralLedger.Setup;\nusing Microsoft.Inventory.Item;\nusing Microsoft.Sales.Document;\nusing System.Utilities;\n```\n## Best practices\nWhen adopting namespaces in your AL projects, consider the following best practices:\n Use namespace templates - Define al.namespaceTemplate in your workspace settings to ensure consistent namespace naming across your project.\n Organize by feature - Structure your folder hierarchy to align with your namespace strategy, such as Sales, Purchasing, Inventory.\n Sort using statements - Keep using statements alphabetically sorted for clean and readable imports.\n Review generated namespaces - Always verify that automatically generated namespaces match your organizational standards before committing changes.\n## Support for fully qualified names\n> APPLIES TO: Business Central 2026 release wave 1 and later\nBusiness Central 2026 release wave 1 introduces method overloads that accept fully qualified names for application objects. This enhancement simplifies the process of referencing objects across different namespaces, improving code clarity and maintainability.\n### Running objects by fully qualified name\nYou can now invoke codeunits, pages, and reports using their fully qualified names. Additionally, RecordRef.Open can be invoked with the fully qualified name of a table.\n```al\ncodeunit 10 MyCodeunit\n{\n    procedure MyProcedure()\n    var\n        rec: Record Customer;\n        recRef: RecordRef;\n    begin\n        // Run codeunit by fully qualified name\n        Codeunit.Run('MyNamespace.CodeunitName');\n\n        // Page methods by fully qualified name\n        Page.Run('MyNamespace.PageName');\n        Page.RunModal('MyNamespace.PageName');\n\n        // Report methods by fully qualified name\n        Report.Run('MyNamespace.ReportName');\n        Report.RunModal('MyNamespace.ReportName');\n        Report.Execute('MyNamespace.ReportName', 'foo', rec);\n\n        // Load record by fully qualified name\n        recRef.Open('MyNamespace.TableName');\n    end;\n}\n```\n### Runtime namespace properties\n> APPLIES TO: Business Central 2026 release wave 1 and later\nWith 2026 release wave 1, the Record and RecordRef instances expose a FullyQualifiedName property, enabling you to determine the complete namespace path of an object at runtime.\n```al\ncodeunit 10 MyCodeunit\n{\n    procedure MyProcedure()\n    var\n        rec: Record Customer;\n        recRef: RecordRef;\n    begin\n        Message(rec.FullyQualifiedName);\n        Message(recRef.FullyQualifiedName);\n    end;\n}\n```\n## Related information\nNamespaces in AL<devenv-namespaces-overview>\ndevenv-code-actions\ndevenv-programming-in-al"}