MSBA-353 · Lesson 6 of 12 · 20 min

Upgrade code and data migration

▶ Video coming soon A video version of this lesson is on the way.

The first version of the Tidewell integration stored one tracking number per shipment, in a text field that the extension added to the posted sales shipment. It worked until Dovrin pointed out that a grocery chain's order often leaves as four or five parcels, each with its own tracking number. Version 1.3 of the extension would therefore replace the single field with a CFR Shipment Parcel table holding one row per parcel. In CONFIG that was easy to change. But CONFIG already held six weeks of test shipments, PROD would soon hold real ones, and the rule in Business Central online is unforgiving: a new version of an extension must carry every customer's data forward, automatically, without anyone running a script by hand. This lesson is about how that works.

The MB-820 outline lists "Create installation and upgrade codeunits" among the codeunit skills and "Plan the update lifecycle for customizations of Business Central" under architecture. Both rest on understanding what happens when an extension is installed or replaced.

The extension lifecycle

An extension moves through four operations. Publish makes an app package known to the environment. Synchronize creates or alters the tables, fields and keys the app defines, so the database schema matches the app. Install makes a published, synchronized version active for the tenant, running install code if this is its first installation. Upgrade runs when a newer version replaces an installed one: the new version is published and synchronized, then its upgrade code runs, and then the old version is unpublished. If any step fails, the operation stops and the previous version stays in place.

A flowchart. Publish, then Synchronize schema. If the app has never been installed: Install, which runs the install codeunit. If an older version is installed: Upgrade, which runs OnCheckPreconditions, then OnUpgrade, then OnValidateUpgrade, per database and per company. A failure at any point returns to the previous version. Uninstall keeps data unless the user chooses to delete it.
Publish, synchronize, install or upgrade, and what happens on failure.

Uninstalling an extension removes its objects from use but keeps its data in the database by default, so reinstalling brings the data back. Data is removed only if an administrator chooses to delete the extension's data, for example with the option to delete data when uninstalling from Extension Management. Unpublishing removes the app package itself. Callum wrote that distinction on a sticky note, because "uninstall to fix it" is a common and mostly harmless instinct, while "uninstall and delete data" is not.

Schema changes and what is allowed

During development, Visual Studio Code's launch configuration has a schemaUpdateMode setting. Synchronize applies compatible changes and refuses destructive ones. Recreate drops and recreates the extension's tables, losing their data, which is acceptable only in a developer sandbox. ForceSync forces destructive changes through and is for development only. Production and the online upgrade process always use the safe path, so a new version must make only non-destructive schema changes against the version already installed.

Schema changes against an installed version.
ChangeAllowed in an upgrade?How to do it safely
Add a table or fieldYesJust add it
Make a text field longerYesIncrease the length
Delete a field or tableNot directlyMark ObsoleteState = Pending, then Removed in a later version
Rename a fieldYes (name only)The field ID keeps the data; API names should stay stable
Change a field's data typeNoAdd a new field, move the data in upgrade code, obsolete the old one
Make a text field shorterNoAdd a new field and move the data with truncation rules
Change a table's primary keyNoAdd a new table and move the data

The obsolete process is how fields and tables retire. In version N, the field gets ObsoleteState = Pending, an ObsoleteReason such as "Replaced by CFR Shipment Parcel table" and an ObsoleteTag with the version number. Code that still uses it produces compiler warnings, so callers have time to move. In a later version the state becomes Removed: the field disappears from the schema, but its data survives until the table itself is cleaned up. For a per-tenant extension the schedule can be short, a version or two; for a Marketplace app, other partners may depend on the field, so the AppSourceCop analyzer in lesson 10 enforces the obsolete process strictly.

Install codeunits

An install codeunit has Subtype = Install and two triggers. OnInstallAppPerDatabase runs once for the whole environment, for work such as registering a Copilot capability from lesson 4. OnInstallAppPerCompany runs once in each company, for work such as creating default setup records, number series or the CF-INTAKE permission set assignments. Install code runs only on first installation of the app, and again if the app is uninstalled and reinstalled. Code inside should check before inserting, because a reinstall finds the old data still there.

An install codeunit that creates a default setup record only if none exists.
codeunit 50080 "CFR Install"
{
    Subtype = Install;
    Access = Internal;

    trigger OnInstallAppPerCompany()
    var
        TidewellSetup: Record "CFR Tidewell Setup";
    begin
        if not TidewellSetup.Get() then begin
            TidewellSetup.Init();
            TidewellSetup."Max. Retries" := 3;
            TidewellSetup."Test Mode" := true;
            TidewellSetup.Insert();
        end;
    end;
}

Upgrade codeunits

An upgrade codeunit has Subtype = Upgrade and six triggers in three pairs, each pair with a per-database and a per-company version. OnCheckPreconditions runs first and can stop the upgrade with an error if the data is not in a state the new version can handle. OnUpgrade does the work. OnValidateUpgrade runs last and can check that the result is correct, failing the upgrade if not. Per-database triggers run once; per-company triggers run once in each company, in no guaranteed order. All of it runs in a single upgrade operation, so an error anywhere rolls the whole upgrade back.

Upgrade codeunits run on every upgrade of the app, not only the one they were written for. Version 1.3 upgrade code will run again when 1.4, 1.5 and 2.0 are installed. Code must therefore know whether its work has already been done. Two techniques exist. Comparing versions, through NavApp.GetCurrentModuleInfo and the module's DataVersion, works but becomes hard to follow as versions pile up. Upgrade tags are the recommended approach.

Upgrade tags

The Upgrade Tag codeunit in the System Application records named markers. Each upgrade step has a unique tag, usually built from the publisher, a short description and a date. The step checks HasUpgradeTag before running and calls SetUpgradeTag after succeeding. There is one more piece: when the app is installed fresh, there is no old data to move, so the tags must be marked as done without running the steps. The app does that by subscribing to the OnGetPerCompanyUpgradeTags and OnGetPerDatabaseUpgradeTags events and adding its tags; Business Central sets them on installation.

An upgrade step guarded by an upgrade tag, moving data with DataTransfer.
codeunit 50081 "CFR Upgrade"
{
    Subtype = Upgrade;
    Access = Internal;

    trigger OnUpgradePerCompany()
    begin
        MoveTrackingNumbersToParcels();
    end;

    local procedure MoveTrackingNumbersToParcels()
    var
        UpgradeTag: Codeunit "Upgrade Tag";
        ParcelTransfer: DataTransfer;
        ShipmentHeader: Record "Sales Shipment Header";
        Parcel: Record "CFR Shipment Parcel";
    begin
        if UpgradeTag.HasUpgradeTag(ParcelUpgradeTag()) then
            exit;

        ParcelTransfer.SetTables(Database::"Sales Shipment Header", Database::"CFR Shipment Parcel");
        ParcelTransfer.AddSourceFilter(ShipmentHeader.FieldNo("CFR Tracking No."), '<>%1', '');
        ParcelTransfer.AddFieldValue(ShipmentHeader.FieldNo("No."), Parcel.FieldNo("Shipment No."));
        ParcelTransfer.AddFieldValue(ShipmentHeader.FieldNo("CFR Tracking No."), Parcel.FieldNo("Tracking No."));
        ParcelTransfer.AddConstantValue(1, Parcel.FieldNo("Parcel No."));
        ParcelTransfer.CopyRows();

        UpgradeTag.SetUpgradeTag(ParcelUpgradeTag());
    end;

    local procedure ParcelUpgradeTag(): Code[250]
    begin
        exit('QUARRYSTONE-CFR-MoveTrackingToParcels-20261102');
    end;

    [EventSubscriber(ObjectType::Codeunit, Codeunit::"Upgrade Tag", 'OnGetPerCompanyUpgradeTags', '', false, false)]
    local procedure RegisterPerCompanyTags(var PerCompanyUpgradeTags: List of [Code[250]])
    begin
        PerCompanyUpgradeTags.Add(ParcelUpgradeTag());
    end;
}

DataTransfer for speed

The obvious way to move data is a loop: find each shipment header, insert a parcel record, modify the header. For a few hundred records that is fine. For hundreds of thousands, row-by-row code can take hours and hold the upgrade window hostage. The DataTransfer data type moves data in bulk with a single set-based SQL statement. SetTables names the source and destination; AddFieldValue maps fields; AddConstantValue sets a fixed value; AddSourceFilter limits rows; AddJoin links tables when the destination already has rows. CopyFields updates existing destination rows, and CopyRows inserts new ones. DataTransfer is meant for upgrade code, and it skips table triggers and validation, so the developer must be sure the moved data is valid.

Worked problem

Planning the parcel upgrade

CONFIG has 1,240 posted shipments, 1,105 of them with a tracking number. Version 1.3 adds the parcel table and marks the old field Pending. What must the upgrade do, and what should validation check?

Show solution
  1. Preconditions: none needed; any text value is a valid tracking number.
  2. Upgrade per company: if the tag is not set, copy every shipment with a non-empty tracking number into the parcel table as parcel 1, then set the tag.
  3. Validate per company: count parcels with parcel number 1 and compare with the count of shipments that have a tracking number; raise an error if they differ.
  4. After the upgrade: the expected result is 1,105 parcel records. The old field remains, marked Pending, so nothing is lost if the team needs to check.
  5. In version 1.5, after the next major update has passed, set the old field to Removed.

Answer: Move the data with an upgrade-tag-guarded DataTransfer, check the counts in OnValidateUpgrade, and retire the old field in two steps.

Testing upgrades

Upgrade code runs once per environment and cannot be retried at leisure in production, so it must be tested before release. Noor's routine had three parts. An upgrade test in the test app creates data the old way, runs the upgrade procedure and asserts the result. A container rehearsal installs version 1.2 with sample data, then upgrades to 1.3, which AL-Go can automate by testing against the previous release. And a sandbox rehearsal copies CONFIG to a sandbox and installs the new version there first, giving real data volumes and timings. Only then does the version go to CONFIG, and later to PROD.

Microsoft's updates and your extensions

Business Central online receives a major update twice a year, in April and October, and minor updates monthly. Each update recompiles and upgrades extensions against the new base application, so partner code must stay compatible. Microsoft publishes breaking changes and obsolete objects ahead of time, and the admin center lets administrators choose an update window and schedule the update date within the allowed period. Corbel & Finch's UPDATE-TEST environment exists for this: when a new major version is available as a preview, a sandbox on the preview runs the extension and its tests before the production update date. Partner apps that fail to compile against the new version block the environment's update and generate notifications to the partner and administrator, so watching those notifications is part of the support job in lesson 11.

Migrating data into an extension

Upgrade code moves data that is already in Business Central. Data migration brings data in from outside. For the standard tables, MSBA-150 covered configuration packages, the data migration tools and the migration plan for customers, vendors, items and open documents. Extension tables follow the same tools: configuration packages work with any table, including tables added by extensions, as long as the extension is installed first. Corbel & Finch had twelve months of green coffee intake records in a spreadsheet, which matter for quality trends with importers. Callum created a configuration package for the CFR Green Intake Check table, mapped the spreadsheet columns, validated the data in CONFIG, fixed eleven rows with lot numbers that did not match any lot, and saved the package for the cutover run in late December.

Different data, different tools.
DataToolWhen
Standard master data and open documentsConfiguration packages and migration plan (MSBA-150)December cutover
Green coffee intake historyConfiguration package for the extension tableDecember cutover, after the extension is installed in PROD
Tidewell setupInstall code creates defaults; Callum enters account and keyAfter go-live
Tracking numbers in CONFIGUpgrade code (DataTransfer)Each time the extension version changes

Larger migrations from other systems, such as from Business Central on-premises or Dynamics GP, use Microsoft's cloud migration tools, which replicate data into an online environment and run upgrade steps; partners with extensions that held data on-premises need matching extensions online. Corbel & Finch did not need that path, because its old system was a desktop accounting package, but Noor mentioned it because the exam outline's "differentiate Business Central online and on-premises features" often appears in migration questions.

Versioning the extension

Every app.json carries a four-part version: major, minor, build and revision. Upgrade logic, AL-Go releases and Microsoft's rules all depend on it. Noor's convention for CF Roastery was to raise the minor version for each release with schema or behavior changes, to let the pipeline set build and revision numbers, and to raise the major version only for large redesigns. A new version must be higher than the installed one to upgrade; installing a lower version over a higher one is not possible, so "rolling back" in production means publishing a new, higher version with the old behavior, not reinstalling an older file.

That rule shapes how the team thinks about mistakes. If version 1.3 has a bug, the fix is 1.3 with a higher build number or 1.4, carried through the pipeline with a test. Because uninstalling keeps data and reinstalling the same version does not run upgrade code again, the few cases where an uninstall helps are limited to removing an extension the customer no longer wants.

A cutover checklist for extension data

Go-live adds a one-time sequence on top of normal releases. Callum and Noor agreed the order for the December cutover in PROD: install the released CF Roastery version through the pipeline; let its install code create default setup; enter the Tidewell account and key and keep test mode on; import the intake check history with the configuration package; run a validation report that counts imported rows against the spreadsheet; switch test mode off only after a live rate quote succeeds. Each step has an owner and a check, and the checklist lives in the same repository as the code, so it changes when the code does.

Extension steps in the go-live cutover.
StepOwnerCheck
Deploy release to PRODNoorExtension Management shows the expected version
Default setup createdInstall codeSetup page opens with defaults
Tidewell account and key enteredCallumTest connection succeeds
Intake history importedCallumRow count matches the source spreadsheet
Test mode offCallumOne live rate quote returned

Common mistakes

  • MistakeDeleting a field from a table in a new version.

    InsteadMark it ObsoleteState = Pending, then Removed in a later version.

  • MistakeWriting upgrade code that assumes it runs only once.

    InsteadGuard each step with an upgrade tag and register tags for new installs.

  • MistakeLooping over hundreds of thousands of rows in upgrade code.

    InsteadUse DataTransfer for bulk moves, after checking the data is valid.

  • MistakeUsing ForceSync or Recreate outside a developer sandbox.

    InsteadUse Synchronize and design non-destructive schema changes.

  • MistakeUninstalling with data deletion to fix a problem.

    InsteadUninstall without deleting data, or better, fix forward with a new version.

Summary and key terms

  • Extensions are published, synchronized, then installed or upgraded; failures leave the previous version in place.
  • Upgrades allow only non-destructive schema changes; fields retire through ObsoleteState Pending and Removed.
  • Install codeunits have per-database and per-company triggers that run on first installation.
  • Upgrade codeunits run preconditions, upgrade and validation triggers on every upgrade.
  • Upgrade tags record completed steps and are registered so fresh installs skip them.
  • DataTransfer moves data in bulk during upgrade; configuration packages migrate outside data into extension tables.
Install codeunit
A codeunit with Subtype = Install whose triggers run when an app is first installed.
Upgrade codeunit
A codeunit with Subtype = Upgrade whose triggers run when a newer version replaces an installed one.
Upgrade tag
A named marker recording that an upgrade step has run.
DataTransfer
A data type that copies data between tables in bulk during upgrade or install.
ObsoleteState
A property that marks a field or object as Pending or Removed.
Schema synchronization
Applying an app's table definitions to the database.
Data version
The version of the app whose data is currently in the database.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why are upgrade tags registered in OnGetPerCompanyUpgradeTags?

    Show answer

    So that a fresh installation marks the steps as done and never runs them against data that does not need moving.

  2. What does OnValidateUpgradePerCompany add to the parcel upgrade?

    Show answer

    A check that the number of parcels matches the number of shipments with tracking numbers, failing the upgrade if not.

  3. Can a configuration package load data into an extension's table?

    Show answer

    Yes, once the extension is installed in that environment.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz