Creating Installation and Upgrade Codeunits
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 8 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Lesson: Creating Installation and Upgrade Codeunits in AL
Introduction: The Lifecycle of an AL Extension
When you develop extensions for Business Central using the AL (Application Language) environment, you are not just writing code that performs a specific task; you are managing the lifecycle of that code. An extension is a living entity that gets installed, updated, and potentially uninstalled. Managing these transitions is critical to maintaining data integrity, ensuring user experience consistency, and preventing system errors.
Installation and Upgrade codeunits are the primary mechanisms provided by the AL framework to handle these transitions. Without these codeunits, you would have no way to programmatically set up default data, configure application settings, or migrate existing records when your extension's schema changes. Understanding how to design these objects is a fundamental skill for any developer who wants to move beyond building simple, static pages and start creating professional-grade, reliable business applications.
In this lesson, we will explore the architecture of these codeunits, the specific triggers they expose, and the best practices for ensuring your code remains stable across different versions of your product.
Not read yet
The Role of Installation Codeunits
An installation codeunit is triggered when an extension is first installed on a specific tenant. Its primary purpose is to prepare the environment for the extension to function. Think of this as the "factory settings" or "initialization" phase of your application.
When is the Installation Codeunit Executed?
The installation codeunit runs automatically when a user installs your extension via the Extension Management page or through an automated deployment pipeline. It is important to note that this code runs within a transaction; if any part of your installation code fails, the entire installation will be rolled back. This ensures that you never end up with a "partially installed" state that could lead to corrupted data or a broken user interface.
Key Triggers in Installation Codeunits
There are two primary triggers you will use within an installation codeunit:
OnInstallAppPerCompany: This trigger runs once for each company in the tenant. This is where you should perform data-related initialization, such as inserting default records into your custom tables.OnInstallAppPerDatabase: This trigger runs once for the entire tenant. Use this for global configurations that are not company-specific, such as setting up global permission sets or system-wide settings.
Callout: Per-Company vs. Per-Database It is vital to understand the scope of your initialization logic. If you insert data into a table that is marked as
DataClassification = CustomerContentand is company-specific, you must do it in theOnInstallAppPerCompanytrigger. If you attempt to access company-specific data from theOnInstallAppPerDatabasetrigger, you will likely encounter errors because the system has not yet switched to the appropriate company context.
Practical Example: Initializing Default Data
Imagine you have a custom extension that tracks "Task Priorities." You want to ensure that three default priorities—Low, Medium, and High—are created automatically when the user installs the app.
codeunit 50100 "Install Handler"
{
Subtype = Install;
trigger OnInstallAppPerCompany()
begin
// Check if the setup data already exists to avoid duplication
if IsTableEmpty() then
InsertDefaultPriorities();
end;
local procedure IsTableEmpty(): Boolean
var
Priority: Record "Task Priority";
begin
exit(Priority.IsEmpty);
end;
local procedure InsertDefaultPriorities()
var
Priority: Record "Task Priority";
begin
Priority.Init();
Priority.Code := 'LOW';
Priority.Description := 'Low Priority';
Priority.Insert();
Priority.Init();
Priority.Code := 'MEDIUM';
Priority.Description := 'Medium Priority';
Priority.Insert();
Priority.Init();
Priority.Code := 'HIGH';
Priority.Description := 'High Priority';
Priority.Insert();
end;
}
Not read yet
The Role of Upgrade Codeunits
Upgrade codeunits are arguably more complex and critical than installation codeunits. While installation happens once, upgrades happen repeatedly as you release new versions of your software. An upgrade codeunit is responsible for migrating data, updating schemas, and ensuring that the transition from Version A to Version B is seamless for the end user.
Understanding the Upgrade Lifecycle
The upgrade process is divided into several distinct steps, each handled by specific triggers within the upgrade codeunit. The AL framework follows a strict sequence:
OnCheckPreconditions: Validates that the system is in a state where an upgrade can proceed.OnUpgradePerCompany/OnUpgradePerDatabase: These are the core triggers where you move data from old fields to new fields or perform calculations.OnValidateUpgrade: A final check to ensure that the data integrity has been maintained post-upgrade.
Best Practices for Upgrade Codeunits
When writing upgrade code, you must assume the environment is live. Never perform operations that could lock the database for an extended period, as this will frustrate users and potentially time out the upgrade process.
- Always check for the existence of data: Before moving data from a field, verify that the field still exists and contains the expected information.
- Use
DataUpgradeMgt: The system provides helper modules for data migration. Familiarize yourself with these to avoid reinventing the wheel. - Avoid complex logic: Keep your upgrade logic simple. If you need to run complex business processes, consider scheduling them as a background task after the upgrade is complete.
Warning: Data Loss During Schema Changes When you remove a field from a table in a new version of your extension, the data in that field is deleted by the platform. If you need to preserve that data, you must perform the migration before the field is removed in your code. This requires careful versioning: you first release a version that migrates the data to a new location, and then in a subsequent version, you remove the old field.
Practical Example: Migrating Field Data
Suppose you are renaming a field from OldDescription to NewDescription because of a change in business requirements. You need to move the data from the old field to the new one during the upgrade process.
codeunit 50101 "Upgrade Handler"
{
Subtype = Upgrade;
trigger OnUpgradePerCompany()
begin
MigrateDescriptions();
end;
local procedure MigrateDescriptions()
var
MyTable: Record "My Custom Table";
begin
if MyTable.FindSet() then
repeat
// Only migrate if we haven't already (check if new field is empty)
if (MyTable.NewDescription = '') and (MyTable.OldDescription <> '') then begin
MyTable.NewDescription := MyTable.OldDescription;
MyTable.Modify();
end;
until MyTable.Next() = 0;
end;
}
Not read yet
Comparing Installation and Upgrade Codeunits
| Feature | Installation Codeunit | Upgrade Codeunit |
|---|---|---|
| Purpose | Initial setup and configuration | Schema migration and data updates |
| Frequency | Once (upon installation) | Every time the app version is increased |
| Transactionality | Full rollback on error | Partial/Full rollback depending on phase |
| Primary Goal | Define default state | Preserve data across version changes |
| Subtype | Install |
Upgrade |
Detailed Step-by-Step: Creating a Robust Upgrade Process
Building a professional upgrade process requires more than just writing code; it requires a disciplined approach to versioning and testing. Follow these steps to ensure your upgrades are successful.
Step 1: Define the Versioning Strategy
Always increment your version property in the app.json file. The platform uses this version number to determine if an upgrade is required. If the version is the same, the upgrade code will not trigger.
Step 2: Implement the Upgrade Codeunit
Create a file named UpgradeCodeunit.al and set the Subtype to Upgrade. Organize your logic into small, testable procedures. Use the OnUpgradePerCompany trigger to iterate through the records that require updates.
Step 3: Implement Pre-Condition Checks
Before modifying any data, verify that the prerequisites are met. For example, if you are changing a data type, ensure that the data currently in the field is compatible with the new type. If it is not, you might need to implement a transformation function.
Step 4: Testing the Upgrade
This is the most critical step. You must simulate the upgrade process:
- Install Version 1.0 of your app in a sandbox environment.
- Populate the tables with test data.
- Publish Version 1.1 (which contains your upgrade code).
- Run the upgrade process.
- Verify that the data is correctly moved and that the application behaves as expected.
Callout: Idempotency Your upgrade code should be idempotent. This means that if the code runs multiple times, the result should be the same as if it ran once. In our example above, we checked
if MyTable.NewDescription = ''before performing the move. This ensures that if the upgrade process is interrupted and restarted, we don't accidentally overwrite data or cause errors.
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced developers fall into traps when dealing with system-level codeunits. Here are the most common mistakes and how to avoid them.
1. Hardcoding Data
Avoid hardcoding IDs or specific record values if possible. Use standard setup tables or configuration files. If you must hardcode, ensure that the values are documented and consistent across all environments.
2. Ignoring Error Handling
When writing installation code, an unhandled error results in a failed installation. Always use try-catch logic or ensure that your code logic is robust enough to handle unexpected states. For instance, if you are attempting to insert a record that might already exist, check for its existence first using Get() or FindSet().
3. Forgetting About Multi-Company Environments
Business Central is inherently multi-company. If your code assumes it is running in a single-company environment, you will cause issues for users with multiple companies. Always use CompanyOpen or verify the context before attempting to access data.
4. Over-Engineering
Keep it simple. The goal of an installation/upgrade codeunit is to get the app to a "ready to use" state. It is not the place for complex business logic, UI interactions, or heavy processing. If you need to perform heavy calculations, use a Job Queue or an asynchronous background task.
5. Lack of Logging
When an upgrade fails, it can be difficult to diagnose why. Incorporate basic logging into your upgrade code. You can use the Message or Error functions for simple feedback, or write to a custom "Upgrade Log" table to track what the code did and when.
Not read yet
Advanced Considerations: Handling Breaking Changes
Sometimes, a change is so significant that a simple upgrade script isn't enough. For example, if you are splitting a large table into two smaller, related tables, you need to perform a data migration that involves:
- Creating the new tables.
- Copying data from the old table to the new tables.
- Updating any existing references (e.g., in foreign keys or page extensions).
- Deleting the old data.
In these scenarios, consider using a staging table. You can copy the data into a temporary, non-visible table first, perform the transformations there, and then map it to the final destination. This keeps your production data safe while you perform the "heavy lifting" of the migration.
Handling Permissions
Installation code often requires elevated permissions to create records or modify system tables. If your app is installed by a user who lacks these permissions, the installation will fail. Ensure your app's Permissions property in the app.json file is configured correctly to allow the installation codeunit to perform its duties.
Note: The
Permissionsproperty is not a "magic button." It grants the necessary rights for the codeunit to execute, but it does not bypass the fundamental security model of the system. Always follow the principle of least privilege.
Not read yet
Best Practices Checklist for Developers
To maintain high-quality AL code, adhere to these industry-standard practices:
- Descriptive Naming: Name your codeunits clearly (e.g.,
InstallApp,UpgradeApp). - Modularization: Break down your upgrade logic into small, private procedures. This makes debugging much easier.
- Documentation: Comment your code. Explain why a certain migration is happening, not just how. This is invaluable for future developers who maintain your code.
- Version Control: Commit your installation and upgrade scripts to your source control system. Treat them with the same rigor as your core business logic.
- Performance: Avoid loops that iterate over thousands of records if possible. If you must iterate, use
SetAutoCalcFieldsto optimize the data retrieval. - Testing: Always write automated tests for your installation and upgrade logic. If you can test that your default data is inserted correctly in an automated test, you will save hours of manual verification.
Not read yet
Summary of Key Takeaways
- Lifecycle Management: Installation and Upgrade codeunits are the backbone of your extension's lifecycle. They ensure that your application can be deployed, configured, and updated without manual intervention or data loss.
- Trigger Specificity: Use
OnInstallAppPerCompanyandOnInstallAppPerDatabasecorrectly based on the scope of the data or configuration you are initializing. - Idempotency is Essential: Always write your upgrade code so that it can be safely re-run without causing duplication, data corruption, or errors. This is the hallmark of professional AL development.
- Data Preservation: Understand the platform's behavior regarding field deletion. If you need to migrate data, do it before the schema change is finalized in your code.
- Testing is Non-Negotiable: Never push an upgrade to production without testing it in a sandbox against a realistic dataset. Automated tests are the best way to ensure your migration logic is solid.
- Plan for Growth: As your application evolves, your upgrade code will become more complex. Keep it organized, modular, and well-documented to ensure long-term maintainability.
- Security and Permissions: Always ensure that your installation processes have the necessary permissions defined in the app manifest, while strictly adhering to the principle of least privilege.
By mastering these concepts, you transition from being a coder who writes features to an architect who builds robust, enterprise-ready solutions. The ability to manage the life of an extension is what separates a hobbyist project from a professional product that users can trust with their business-critical data. Always approach your installation and upgrade code with the same level of care and attention to detail as you would for your most complex business logic.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock MB-820 exam-style practice questions.
Practice for MB-820