Manipulating Data and Managing Files
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 10 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Manipulating Data and Managing Files in AL
Introduction: The Core of Business Logic
In the world of Microsoft Dynamics 365 Business Central, the AL (Application Language) environment serves as the backbone for custom business logic. While the platform provides a rich set of standard tables and pages, the real power of development lies in your ability to manipulate data—creating, modifying, and deleting records—and managing the files that your users interact with daily. Whether you are building an integration that imports bank statements or creating a custom routine to update pricing based on external market data, understanding how to handle data and files efficiently is a foundational skill for every AL developer.
Data manipulation is not just about writing code that works; it is about writing code that is performant, scalable, and safe. Business Central is a multi-tenant cloud environment where poorly written code can lead to locking issues, performance degradation, and data corruption. By mastering the AL data model, including how to use Record variables, filters, and file streams, you ensure that your extensions provide value without imposing unnecessary burdens on the system. This lesson will guide you through the intricacies of data management, from basic record operations to advanced file handling techniques.
Not read yet
Understanding the Data Model in AL
At the heart of AL is the Record data type. A Record variable acts as a pointer to a table in the database. When you declare a record variable, you are not creating a copy of the data, but rather creating a reference that allows you to traverse, query, and modify rows within that table. Understanding this distinction is vital because it explains why operations on records are inherently database-driven.
When you manipulate data in AL, you are essentially translating business requirements into SQL-like operations. Every time you call Modify, Insert, or Delete, the AL engine translates that into a transaction that must be committed to the database. This process involves locking strategies and validation logic that you, as the developer, must respect to maintain the integrity of the Business Central data model.
Working with Record Variables
To interact with a table, you first declare a variable of type Record followed by the table name. Once declared, you can use methods to locate specific data. The most common methods are Get, Find, and Next.
- Get: This method is used when you know the primary key values of the record you want to retrieve. It is highly efficient because it performs a direct lookup.
- Find/FindFirst/FindLast: These methods are used to navigate through a recordset.
FindFirstis generally faster thanFindSetif you only need the first record, whereasFindSetis optimized for iterating through a collection of records. - Next: This method iterates to the subsequent record in the current filter context. It is almost always used in conjunction with a
repeat-untilloop to process multiple records.
Callout: The Importance of Filters A common mistake beginners make is attempting to process large datasets without applying filters. In AL, filtering is not just a way to narrow down results; it is a critical performance mechanism. By using
SetRangeandSetFilter, you instruct the database engine to perform the heavy lifting, ensuring that only the necessary rows are returned to the application tier. Always filter your data before initiating a loop to avoid unnecessary server load.
Practical Example: Updating Customer Records
Let's look at a scenario where you need to update a field on all customers belonging to a specific country. This code demonstrates the standard pattern for iterating through records:
procedure UpdateCustomerRegion(CountryCode: Code[10])
var
Customer: Record Customer;
begin
Customer.SetRange("Country/Region Code", CountryCode);
if Customer.FindSet() then
repeat
Customer."Salesperson Code" := 'REGION-A';
Customer.Modify(true); // 'true' triggers the OnModify trigger
until Customer.Next() = 0;
end;
In this example, Modify(true) is significant. By passing true, you ensure that the OnModify trigger of the Customer table is executed. This is crucial if there are standard validation rules—such as checking if a customer is blocked or if specific fields are mandatory—that must run before the change is saved.
Not read yet
Advanced Data Manipulation Strategies
As your integration requirements grow, you will move beyond simple loops. You will need to handle complex transactions, perform bulk updates, and manage data validation. Professional AL development requires a deep understanding of the transaction model.
Handling Transactions and Performance
Business Central operates on a transactional basis. When you initiate a process, you want to ensure that it either completes entirely or fails entirely (atomicity). However, long-running transactions can hold locks on tables, preventing other users from working. To prevent this, developers often use the Commit function, but this should be used with extreme caution.
- Avoid unnecessary commits: Committing inside a loop is a major performance anti-pattern. It creates excessive overhead and can lead to inconsistent data states if the process fails midway.
- Keep transactions short: Perform as much data calculation as possible before opening a transaction. Once you start modifying records, do it quickly and close the process.
- Use Bulk Operations: Whenever possible, use
ModifyAllorDeleteAllinstead of iterating through records. These methods perform the operations in a single database round-trip, which is significantly faster.
The Power of ModifyAll and DeleteAll
If you need to update a non-validated field across a large set of records, ModifyAll is your best friend. It does not run the OnModify trigger, which makes it incredibly fast, but also risky if you rely on logic inside that trigger.
procedure BulkUpdateCreditLimit(NewLimit: Decimal)
var
Customer: Record Customer;
begin
Customer.SetRange(Blocked, Customer.Blocked::" ");
if not Customer.IsEmpty then
Customer.ModifyAll("Credit Limit (LCY)", NewLimit, false);
end;
Note: Always verify whether you need to trigger standard validation logic before choosing between
ModifyandModifyAll. If your change affects fields that have dependent calculations or complex business rules, useModify(true)within a loop. If you are performing a mass update that is strictly data-driven,ModifyAllis the industry standard for performance.
Not read yet
Managing Files in Business Central
File management in a cloud-based environment like Business Central is vastly different from managing files on a local machine. You do not have direct access to the server's file system. Instead, you work with InStream and OutStream objects. These streams allow you to read from and write to files stored in memory, on Azure Blob Storage, or provided by the user via the browser.
The Concept of Streams
Think of a stream as a pipe. An InStream is a pipe that carries data into your AL code (e.g., from a file upload or a web service response), while an OutStream is a pipe that carries data out of your code (e.g., to a file download or an external API).
Reading a File from the User
When a user uploads a file, you use the UploadIntoStream function. This displays a dialog in the browser, allowing the user to select a file from their computer, which is then streamed into your AL code.
procedure ImportFile()
var
InStream: InStream;
FileName: Text;
begin
if UploadIntoStream('Select File', '', 'All Files (*.*)|*.*', FileName, InStream) then
// Now you can use the InStream to read the file content
// Example: XMLPort.Import(Xmlport::"My Import", InStream);
end;
Writing a File for the User
Conversely, if you need to generate a report or an export file for the user, you create a memory stream and use DownloadFromStream.
procedure ExportFile()
var
OutStream: OutStream;
TempBlob: Codeunit "Temp Blob";
begin
TempBlob.CreateOutStream(OutStream);
// Write data to the OutStream...
// Example: OutStream.WriteText('Hello World');
// Download the result
FileManagement.BLOBExport(TempBlob, 'Export.txt', true);
end;
Best Practices for File Handling
- Use TempBlob: The
Temp Blobcodeunit is the standard way to handle binary data in AL. It abstracts the complexity of working with streams and provides built-in methods for exporting and importing data. - Validate File Types: When using
UploadIntoStream, always filter for the expected file types (e.g.,.csv,.xml). This prevents users from accidentally uploading files that your logic cannot process. - Handle Large Files: If you are processing very large files, do not try to read the entire file into a text variable. Process the file line-by-line or use an XMLPort to stream the data directly into the database.
- Error Handling: Always wrap your file operations in
try-catchlogic (usingTryFunction) if the file format is unpredictable. This prevents the entire session from crashing if a user uploads a corrupted file.
Not read yet
Comparison: Record Operations vs. File Streams
| Feature | Record Operations |
File Streams |
|---|---|---|
| Purpose | CRUD operations on DB records | Reading/Writing external data |
| Performance | Depends on filtering and indices | Depends on buffer size and IO |
| Context | Server-side (Database) | Memory-based (Transient) |
| Common Use | Business logic, ledger updates | Integrations, Exports, Imports |
Warning: The "Hidden" Performance Trap A common pitfall is performing a
GetorFindinside a loop that is already iterating through a recordset. This is known as the "N+1" problem. If you have 100 records and you perform aGetfor a related record in each iteration, you are executing 101 database queries. Always useJoinqueries or pre-fetch related data into a temporary table to keep the query count to a minimum.
Common Pitfalls and How to Avoid Them
1. Forgetting to Validate Data
AL is a strongly typed language, but it cannot prevent business-logic errors. For example, setting a Posting Date to a date in a closed fiscal year is technically valid in AL, but it violates business rules. Always use the standard table triggers (OnInsert, OnModify, OnDelete) by passing true to the methods, or manually call the validation functions if you are performing bulk operations.
2. Ignoring Table Locks
When you modify a heavily used table like Sales Header or G/L Entry, you risk locking the table for other users. If your logic takes several seconds to process, the system might become unresponsive for everyone else.
- Solution: Perform your logic on a background session using a
Job QueueorTask Schedulerif the process is time-consuming.
3. Hardcoding Values
Hardcoding IDs, table names, or folder paths is a recipe for disaster in multi-tenant environments.
- Solution: Use
Setuptables to store configuration values. If you need to store file paths, store them in a way that is relative to the current environment, or better yet, use cloud storage providers like Azure Blob Storage via theAzure Blob Storagemodule.
4. Over-relying on FindSet(true)
FindSet(true) tells the system you intend to modify the records you are iterating over. This sets a lock on the records as they are read. If you are only reading data to display it or perform a calculation, do not use true in FindSet. Only use it when you are absolutely certain that a Modify operation will follow.
Not read yet
Step-by-Step: Creating a Data Import Routine
To solidify these concepts, let's walk through the creation of a simple CSV import routine for a custom table.
Step 1: Define the Data Structure Create a table with the fields you intend to import. Ensure you have a clear primary key.
Step 2: Create the Import Codeunit
Create a codeunit that uses UploadIntoStream to grab the file.
codeunit 50100 "Data Importer"
{
procedure ImportCSV()
var
InStream: InStream;
FileName: Text;
begin
if UploadIntoStream('Select CSV', '', 'CSV Files (*.csv)|*.csv', FileName, InStream) then
ProcessStream(InStream);
end;
local procedure ProcessStream(var InStream: InStream)
var
Line: Text;
MyRecord: Record "My Import Table";
begin
// Use a stream reader to read line by line
while not InStream.EOS() do begin
InStream.ReadText(Line);
// Parse the CSV line (simplified)
ParseLine(Line, MyRecord);
MyRecord.Insert();
end;
end;
}
Step 3: Add Validation
Inside ParseLine, add checks to ensure the data is valid before calling Insert. If the data is bad, write to a log or throw an error to stop the process.
Step 4: Optimize
If the CSV is large, consider using an XmlPort or the Data Exchange Framework provided by Business Central, as these are built for high-performance data transformation.
Not read yet
Best Practices for Professional AL Development
As you progress in your AL journey, adopt these industry standards:
- Modularize your code: Don't write 500 lines of code in a single trigger. Break your logic into small, reusable
procedureswithin codeunits. This makes testing and debugging significantly easier. - Document your logic: Use XML comments (
///) for your procedures. This allows other developers (and your future self) to understand the purpose, parameters, and return values of your code without reading the entire implementation. - Use
TryFunctionfor risky operations: When dealing with external files or web services, the risk of failure is high. Wrap these calls in aTryFunctionto handle exceptions gracefully. - Adopt naming conventions: Use clear, descriptive names for your variables. Instead of
Rec1orTemp, useCustomerRecorTempCustomerList. This improves code readability immensely. - Testing: Always write test codeunits for your data manipulation routines. Automating tests ensures that future changes to the system don't break your existing integration logic.
Callout: The "Record-Level" vs. "Set-Level" Mindset Beginners often struggle to decide whether to iterate (Record-level) or perform bulk updates (Set-level). A good heuristic: If the operation requires running code inside a table trigger (like calculating tax, updating ledger entries, or triggering workflows), use a loop. If the operation is a simple value change (like updating a status flag or a non-validated date), use
ModifyAll.
Not read yet
Handling Multi-Language and Localization
One of the unique challenges in Business Central is that your code might run in different countries with different localizations. When manipulating data, keep in mind that fields like Address or Post Code might have different lengths or validation rules depending on the country.
Always use the Format function carefully when converting data to strings for file exports, as the user's locale settings can change how dates and decimals are represented. For example, the date 12/01/2023 could mean December 1st in the US or January 12th in Europe. When generating files for external systems, always use ISO formats (e.g., YYYY-MM-DD) to ensure consistency regardless of the user's regional settings.
Security Considerations
When managing files and data, security is paramount. Since you are handling sensitive business information, ensure that:
- Access Control: Use
Permissionsproperties on your objects to limit who can run your data manipulation routines. - Input Sanitization: Never trust the data coming from an external file. Always validate that strings contain expected characters and numbers are within expected ranges.
- Data Privacy: If you are importing personal data (PII), ensure that you comply with GDPR or other local privacy regulations. Consider using the
Data Privacyfeatures built into Business Central to manage the classification of your fields.
Not read yet
Key Takeaways
- Master the
Recordvariable: It is your primary tool for data manipulation. Understand the difference betweenGet,FindFirst, andFindSet. - Filter before you iterate: Always apply filters using
SetRangeorSetFilterto optimize performance and prevent unnecessary database load. - Understand the Transaction Model: Know when to use
Modify(true)to trigger business logic and whenModifyAllis the better choice for performance. - Embrace Streams: For all file handling, use
InStreamandOutStreamobjects. They are the only reliable way to handle data in the cloud environment. - Prioritize Performance: Avoid the "N+1" problem by pre-fetching data and minimizing the number of database round-trips.
- Safety First: Always validate input data, handle errors with
TryFunction, and respect the system’s transactional integrity. - Documentation and Testing: Treat your AL code like a professional product; document your procedures and write automated tests to ensure long-term stability.
By internalizing these concepts, you move from being a developer who writes "code that works" to an engineer who builds "systems that perform." Data and file management are the core functions of any ERP extension; getting them right is the difference between a system that serves the business and one that becomes a bottleneck.
Not read yet
Common Questions (FAQ)
Q: Why does my code work in the development environment but fail in production? A: This is usually due to differences in data volume or user permissions. Always test with a dataset that mirrors production volume and ensure your user account has the necessary permissions to access all tables involved in your routine.
Q: Can I use Commit to save my progress in a long loop?
A: While possible, it is generally discouraged. If you absolutely must commit frequently, ensure that you are handling the possibility of a partial failure, where some records are updated and others are not, by implementing a robust logging or error-tracking mechanism.
Q: What is the best way to handle large XML or JSON files?
A: For large files, avoid loading the entire content into a text variable. Use the XMLPort object for XML files, which is designed to stream data directly into the database, or the JsonToken and JsonReader objects for efficient JSON parsing.
Q: How do I know if a field has validation logic?
A: Open the table definition in the AL editor, look for the OnValidate trigger on the specific field. If there is code there, you must use Modify(true) or explicitly call Validate(Field, Value) in your code.
Q: Is there a way to see the SQL queries my AL code generates? A: While you cannot see the raw SQL, you can use the "Database Monitor" or "Performance Profiler" tools in the Business Central administration center to analyze how your code interacts with the database. These tools are invaluable for identifying slow-running queries.
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