Exercise: Complete a resilient AL import service
In this exercise, you build a service that imports item review data from a CSV file, updates existing items, and records the outcome of every row. Use object IDs 70900–70999 in a Business Central online sandbox.
Define the import contract
The import accepts three columns in this order:
| Column | AL value | Rule |
|---|---|---|
ItemNo |
Code[20] |
Must identify an existing, unblocked item. |
ReviewPriority |
Enum | Must be Low, Normal, or High. |
NextReviewDate |
Date |
Must use YYYY-MM-DD format and can't be before the work date. |
Create a UTF-8 file named item-reviews.csv. Replace the item numbers with numbers that exist in your sandbox.
ItemNo,ReviewPriority,NextReviewDate
1000,High,2026-11-15
1001,Normal,2026-12-01
BADITEM,Low,2026-12-15
The import classifies malformed values as Rejected. It classifies missing or blocked target items as Failed. It classifies applied updates as Imported. An unexpected database error stops the operation and rolls back the transaction.
Add item review fields
Create ItemReviewEnums.Enum.al with enums for review priority and import status.
enum 70900 "Item Review Priority"
{
Extensible = true;
value(0; Low)
{
Caption = 'Low';
}
value(1; Normal)
{
Caption = 'Normal';
}
value(2; High)
{
Caption = 'High';
}
}
enum 70901 "Item Review Import Status"
{
Extensible = false;
value(0; Imported)
{
Caption = 'Imported';
}
value(1; Rejected)
{
Caption = 'Rejected';
}
value(2; Failed)
{
Caption = 'Failed';
}
}
Create ItemReviewFields.TableExt.al. The date trigger keeps the rule on the table so every caller gets the same validation.
tableextension 70900 "Item Review Fields" extends Item
{
fields
{
field(70900; "Item Review Priority"; Enum "Item Review Priority")
{
Caption = 'Item Review Priority';
DataClassification = CustomerContent;
}
field(70901; "Next Review Date"; Date)
{
Caption = 'Next Review Date';
DataClassification = CustomerContent;
trigger OnValidate()
begin
if ("Next Review Date" <> 0D) and ("Next Review Date" < WorkDate()) then
Error(ReviewDateErr, WorkDate());
end;
}
}
var
ReviewDateErr: Label 'The next review date must be on or after the work date, %1.';
}
Store row-level results
Create ItemReviewImportResult.Table.al. A batch identifier groups all rows from one upload, while the line number preserves the source location.
table 70900 "Item Review Import Result"
{
Caption = 'Item Review Import Result';
DataClassification = CustomerContent;
DrillDownPageId = "Item Review Import Results";
fields
{
field(1; "Batch ID"; Guid)
{
Caption = 'Batch ID';
DataClassification = SystemMetadata;
}
field(2; "Line No."; Integer)
{
Caption = 'Line No.';
DataClassification = SystemMetadata;
}
field(3; "Source Name"; Text[250])
{
Caption = 'Source Name';
DataClassification = CustomerContent;
}
field(4; "Item No."; Code[20])
{
Caption = 'Item No.';
TableRelation = Item."No.";
DataClassification = CustomerContent;
}
field(5; Status; Enum "Item Review Import Status")
{
Caption = 'Status';
DataClassification = CustomerContent;
}
field(6; Message; Text[250])
{
Caption = 'Message';
DataClassification = CustomerContent;
}
}
keys
{
key(PK; "Batch ID", "Line No.")
{
Clustered = true;
}
}
}
Create ItemReviewImportResults.Page.al as a read-only view of the import evidence.
page 70900 "Item Review Import Results"
{
PageType = List;
SourceTable = "Item Review Import Result";
Caption = 'Item Review Import Results';
ApplicationArea = All;
UsageCategory = History;
Editable = false;
InsertAllowed = false;
DeleteAllowed = false;
layout
{
area(Content)
{
repeater(Results)
{
field("Batch ID"; Rec."Batch ID")
{
ApplicationArea = All;
ToolTip = 'Specifies the identifier shared by rows from one import.';
}
field("Line No."; Rec."Line No.")
{
ApplicationArea = All;
ToolTip = 'Specifies the source line that produced the result.';
}
field("Source Name"; Rec."Source Name")
{
ApplicationArea = All;
ToolTip = 'Specifies the uploaded file name.';
}
field("Item No."; Rec."Item No.")
{
ApplicationArea = All;
ToolTip = 'Specifies the item number read from the source row.';
}
field(Status; Rec.Status)
{
ApplicationArea = All;
ToolTip = 'Specifies whether the row was imported, rejected, or failed.';
}
field(Message; Rec.Message)
{
ApplicationArea = All;
ToolTip = 'Specifies the outcome or error for the row.';
}
}
}
}
}
Implement the internal import service
Create ItemReviewImportImpl.Codeunit.al. The codeunit is internal because callers shouldn't depend on its CSV buffer or validation helpers.
codeunit 70900 "Item Review Import Impl."
{
Access = Internal;
procedure ImportRows(SourceName: Text; SourceStream: InStream; var ImportedCount: Integer; var RejectedCount: Integer; var FailedCount: Integer): Guid
var
TempCSVBuffer: Record "CSV Buffer" temporary;
BatchId: Guid;
LineNo: Integer;
begin
ImportedCount := 0;
RejectedCount := 0;
FailedCount := 0;
BatchId := CreateGuid();
TempCSVBuffer.LoadDataFromStream(SourceStream, ',');
ValidateHeader(TempCSVBuffer);
for LineNo := 2 to TempCSVBuffer.GetNumberOfLines() do
ImportRow(
BatchId,
SourceName,
LineNo,
TempCSVBuffer.GetValue(LineNo, 1),
TempCSVBuffer.GetValue(LineNo, 2),
TempCSVBuffer.GetValue(LineNo, 3),
ImportedCount,
RejectedCount,
FailedCount);
exit(BatchId);
end;
local procedure ValidateHeader(var TempCSVBuffer: Record "CSV Buffer" temporary)
var
HeaderError: ErrorInfo;
begin
if (TempCSVBuffer.GetNumberOfLines() > 0) and
(UpperCase(TempCSVBuffer.GetValue(1, 1)) = 'ITEMNO') and
(UpperCase(TempCSVBuffer.GetValue(1, 2)) = 'REVIEWPRIORITY') and
(UpperCase(TempCSVBuffer.GetValue(1, 3)) = 'NEXTREVIEWDATE')
then
exit;
HeaderError.Title(InvalidHeaderTitleLbl);
HeaderError.Message(InvalidHeaderMessageLbl);
HeaderError.DetailedMessage(InvalidHeaderDetailLbl);
Error(HeaderError);
end;
local procedure ImportRow(BatchId: Guid; SourceName: Text; LineNo: Integer; ItemNoText: Text; PriorityText: Text; ReviewDateText: Text; var ImportedCount: Integer; var RejectedCount: Integer; var FailedCount: Integer)
var
ItemNo: Code[20];
ReviewPriority: Enum "Item Review Priority";
ReviewDate: Date;
begin
ClearLastError();
if not TryParseRow(LineNo, ItemNoText, PriorityText, ReviewDateText, ItemNo, ReviewPriority, ReviewDate) then begin
RejectedCount += 1;
InsertResult(BatchId, SourceName, LineNo, ItemNo, "Item Review Import Status"::Rejected, GetLastErrorText());
exit;
end;
ClearLastError();
if not TryValidateTarget(ItemNo, ReviewDate) then begin
FailedCount += 1;
InsertResult(BatchId, SourceName, LineNo, ItemNo, "Item Review Import Status"::Failed, GetLastErrorText());
exit;
end;
ApplyItemUpdate(ItemNo, ReviewPriority, ReviewDate);
ImportedCount += 1;
InsertResult(BatchId, SourceName, LineNo, ItemNo, "Item Review Import Status"::Imported, ImportedMessageLbl);
end;
[TryFunction]
local procedure TryParseRow(LineNo: Integer; ItemNoText: Text; PriorityText: Text; ReviewDateText: Text; var ItemNo: Code[20]; var ReviewPriority: Enum "Item Review Priority"; var ReviewDate: Date)
begin
ItemNo := CopyStr(ItemNoText.Trim(), 1, MaxStrLen(ItemNo));
if ItemNo = '' then
Error(MissingItemNoErr, LineNo);
case UpperCase(PriorityText.Trim()) of
'LOW':
ReviewPriority := ReviewPriority::Low;
'NORMAL':
ReviewPriority := ReviewPriority::Normal;
'HIGH':
ReviewPriority := ReviewPriority::High;
else
Error(InvalidPriorityErr, LineNo, PriorityText);
end;
if not Evaluate(ReviewDate, ReviewDateText.Trim(), 9) then
Error(InvalidDateErr, LineNo, ReviewDateText);
end;
[TryFunction]
local procedure TryValidateTarget(ItemNo: Code[20]; ReviewDate: Date)
var
Item: Record Item;
begin
Item.Get(ItemNo);
Item.TestField(Blocked, false);
if ReviewDate < WorkDate() then
Error(PastDateErr, ItemNo, ReviewDate, WorkDate());
end;
local procedure ApplyItemUpdate(ItemNo: Code[20]; ReviewPriority: Enum "Item Review Priority"; ReviewDate: Date)
var
Item: Record Item;
begin
Item.Get(ItemNo);
Item.Validate("Item Review Priority", ReviewPriority);
Item.Validate("Next Review Date", ReviewDate);
Item.Modify(true);
end;
local procedure InsertResult(BatchId: Guid; SourceName: Text; LineNo: Integer; ItemNo: Code[20]; ImportStatus: Enum "Item Review Import Status"; ResultMessage: Text)
var
ImportResult: Record "Item Review Import Result";
begin
ImportResult.Init();
ImportResult."Batch ID" := BatchId;
ImportResult."Line No." := LineNo;
ImportResult."Source Name" := CopyStr(SourceName, 1, MaxStrLen(ImportResult."Source Name"));
ImportResult."Item No." := ItemNo;
ImportResult.Status := ImportStatus;
ImportResult.Message := CopyStr(ResultMessage, 1, MaxStrLen(ImportResult.Message));
ImportResult.Insert();
end;
var
InvalidHeaderTitleLbl: Label 'The import file has an invalid header.';
InvalidHeaderMessageLbl: Label 'The file must contain the ItemNo, ReviewPriority, and NextReviewDate columns in that order.';
InvalidHeaderDetailLbl: Label 'Use a comma-delimited UTF-8 file. The header names are case-insensitive.';
MissingItemNoErr: Label 'Line %1 doesn't contain an item number.';
InvalidPriorityErr: Label 'Line %1 contains the unsupported review priority %2.';
InvalidDateErr: Label 'Line %1 contains the invalid review date %2. Use YYYY-MM-DD format.';
PastDateErr: Label 'Item %1 has review date %2, which is before the work date, %3.';
ImportedMessageLbl: Label 'The item review fields were updated.';
}
TryParseRow and TryValidateTarget don't write to the database. ApplyItemUpdate runs only after both calls succeed. The field Validate calls preserve table behavior, and Modify(true) runs the table modification trigger.
Expose a stable entry point
Create ItemReviewImport.Codeunit.al. This public façade is the supported contract for the page action and possible dependent extensions.
codeunit 70901 "Item Review Import"
{
Access = Public;
procedure ImportItemReviews(SourceName: Text; SourceStream: InStream; var ImportedCount: Integer; var RejectedCount: Integer; var FailedCount: Integer): Guid
var
ImportImpl: Codeunit "Item Review Import Impl.";
begin
exit(ImportImpl.ImportRows(SourceName, SourceStream, ImportedCount, RejectedCount, FailedCount));
end;
}
Create ItemReviewImportAction.PageExt.al to show the review fields and add a browser-safe upload action to the Items page.
pageextension 70900 "Item Review Import Action" extends "Item List"
{
layout
{
addlast(Control1)
{
field("Item Review Priority"; Rec."Item Review Priority")
{
ApplicationArea = All;
ToolTip = 'Specifies the priority assigned to the next item review.';
}
field("Next Review Date"; Rec."Next Review Date")
{
ApplicationArea = All;
ToolTip = 'Specifies when the item is next scheduled for review.';
}
}
}
actions
{
addlast(Processing)
{
action(ImportItemReviews)
{
ApplicationArea = All;
Caption = 'Import item reviews';
Image = Import;
ToolTip = 'Upload a CSV file that assigns item review priorities and dates.';
trigger OnAction()
var
ImportResult: Record "Item Review Import Result";
ImportService: Codeunit "Item Review Import";
SourceStream: InStream;
FileName: Text;
BatchId: Guid;
ImportedCount: Integer;
RejectedCount: Integer;
FailedCount: Integer;
begin
if not UploadIntoStream(SelectFileLbl, '', CsvFilterLbl, FileName, SourceStream) then
exit;
BatchId := ImportService.ImportItemReviews(FileName, SourceStream, ImportedCount, RejectedCount, FailedCount);
Message(ImportCompleteMsg, ImportedCount, RejectedCount, FailedCount);
ImportResult.SetRange("Batch ID", BatchId);
Page.Run(Page::"Item Review Import Results", ImportResult);
end;
}
}
}
var
SelectFileLbl: Label 'Select an item review file';
CsvFilterLbl: Label 'CSV files (*.csv)|*.csv';
ImportCompleteMsg: Label 'Imported: %1. Rejected: %2. Failed: %3.';
}
The page action owns the user interaction. The public codeunit owns the supported procedure contract. The internal codeunit owns parsing and update details.
Test successful and unsuccessful rows
Publish the extension to a sandbox, and then follow these steps:
- Open the Items page, and confirm that the review fields appear.
- Select Import item reviews, and upload the sample CSV file.
- Confirm that existing, unblocked items receive the expected priority and date.
- Confirm that an unknown item creates a Failed result without changing an item.
- Change a priority to an unsupported value, import again, and confirm that the row is Rejected.
- Change the header name, import again, and confirm that
ErrorInforeports the file-level contract failure. - Set a date before the work date, import again, and confirm that validation prevents the update.
Review the counters and the filtered Item Review Import Results page after each completed import. Set breakpoints in TryParseRow, TryValidateTarget, and ApplyItemUpdate to observe the boundary between recoverable validation and database writes.