Thursday, December 3, 2026

D365FO: Building the SysExtension reflection map five times faster

Recently, at one of my customer projects, users complained about the performance of the Create sales order form.

I recorded a trace and started investigating it using Trace Parser. Among other things, I discovered something interesting in the standard Microsoft code.

The Main Data Change functionality, through MainDataChangeImplementationFactory, triggered the initialization of the SysExtension reflection cache. Constructing the reflection map alone took approximately seven seconds.

The method responsible for most of this execution time was:

SysExtAppClassReflectionCacheBuilder::buildReflectionMapFromDictionary()

Considering how widely the SysExtension framework is used throughout D365FO, I decided to investigate whether this method could be optimized.

It turns out that it can.

The current implementation

The purpose of the method is to construct a map of interface names to sets of implementing class IDs.

The current implementation iterates through all classes in the runtime dictionary, constructs a SysDictClass object for each class and discovers its interface relationships.

The essential logic of the standard implementation can be illustrated as follows:

Dictionary dictionary = new Dictionary();
int classCount = dictionary.classCnt();

for (int counter = 1; counter <= classCount; counter++)
{
    ClassId classId = dictionary.classCnt2Id(counter);
    SysDictClass sysDictClass = new SysDictClass(classId);

    if (sysDictClass != null && !sysDictClass.isInterface())
    {
        int implementingCount = sysDictClass.implementsCnt();

        for (int implementingCounter = 1;
             implementingCounter <= implementingCount;
             implementingCounter++)
        {
            ClassId interfaceId =
                sysDictClass.implements(implementingCounter);

            SysExtAppClassReflectionData::addToMap(
                classId2Name(interfaceId),
                classId);
        }
    }
}

In the environment I investigated, there were more than 72,000 classes. Consequently, the algorithm constructs more than 72,000 SysDictClass objects, regardless of whether those classes implement any interfaces.

There are two opportunities for improvement here.

Optimization 1: Use DictClass instead of SysDictClass

The first optimization is surprisingly simple.

SysDictClass extends DictClass and has three instance member initializations that invoke the following methods:

  • parmStaticUseLegacyImplementedByAlgorithm()
  • parmStaticUseLegacyExtendedByAlgorithm()
  • parmStaticUseCachedMapsForLookupAlgorithms()

These settings are relevant to other reflection operations, but the algorithm shown above does not need the additional functionality provided by SysDictClass.

Across the entire class population, these initializations account for more than 218,000 additional method calls.

Why not simply use DictClass?

// Original implementation
SysDictClass sysDictClass = new SysDictClass(classId);

// Proposed implementation
DictClass dictClass = new DictClass(classId);

The rest of the algorithm remains unchanged.

I call the original algorithm V1 and this modified version V2.

In my benchmark, this small modification reduced the first-execution time by approximately 19% and the median warm execution time by approximately 49%.

Not bad for such a small change.

Optimization 2: Use the metadata API

Can we do substantially better?

Instead of constructing reflection objects for every class in the application, we can use the metadata APIs available in D365FO today.

The starting point is:

var classes =
    Microsoft.Dynamics.Ax.Xpp.MetadataSupport::GetAllClasses();

The returned AxClass metadata objects already contain information about their declared interfaces.

Therefore, when iterating through the metadata, we can immediately discard classes without interface declarations, as well as interface objects themselves:

var interfaces = classInfo.Implements;

if (interfaces == null)
{
    continue;
}

if (interfaces.Count == 0 || classInfo.IsInterface)
{
    continue;
}

Only the remaining candidates need further processing.

The optimized algorithm, which I call V4e, works as follows:

  1. Retrieve the class metadata.
  2. Select non-interface classes that declare interfaces.
  3. Resolve their runtime class IDs and validate their identities.
  4. Collect their declared interface names.
  5. Resolve interface names to their canonical runtime names, caching these resolutions locally during construction.
  6. Populate the reflection map using the same insertion rules as the original algorithm.

One important detail is that not every interface name found in the metadata resolves to an X++ interface ID. The optimized implementation preserves the original behavior for such relationships rather than introducing additional entries into the map.

It also preserves direct interface-declaration semantics. It does not recursively add inherited implementations.

The algorithm still performs runtime identity resolution where necessary, but it no longer needs to traverse the complete runtime dictionary and construct a reflection object for every class.

The complete implementation is available in the runnable class accompanying this article.

Performance comparison

To make the comparison reproducible, I created three independent runnable X++ classes.

Before executing each class, I restarted the AOS. Each class constructs its map four times: once after the restart and three subsequent times. Every construction uses a new map.

No artificial cache clearing or modification of standard Microsoft code is involved in the measurements.

The benchmarks were performed in a D365FO development environment running:

  • Application version: 10.0.49 (10.0.2790.74)
  • Platform version: Update 73 (7.0.8199.48)

Here are the results:

Execution V1
SysDictClass
V2
DictClass
V4e
Metadata
First execution 7,057 ms 5,689 ms 2,008 ms
Warm 1 2,285 ms 1,175 ms 1,004 ms
Warm 2 2,546 ms 1,000 ms 446 ms
Warm 3 2,102 ms 1,438 ms 446 ms
Warm median 2,285 ms 1,175 ms 446 ms
D365FO SysExtension reflection map construction: first execution and warm performance comparison
Figure 1. Reflection map construction time. Lower is better.

Compared with the original algorithm, the metadata-based implementation is:

  • 3.51 times faster on the first execution after an AOS restart.
  • 5.12 times faster on subsequent executions, based on the warm median.

The first-execution time has been reduced by approximately five seconds.

These measurements cover reflection map construction, not the complete execution time of the sales order form.

But are the resulting maps identical?

Performance improvements are meaningless if they change the behavior of the framework.

After completing its four timed executions, each runnable class invokes the actual Microsoft implementation:

SysExtAppClassReflectionCacheBuilder::populateFromMetadata();

It then retrieves the resulting standard reflection map using:

SysExtAppClassReflectionData::getReflectionMapEnumerator();

Every constructed map is compared against this reference.

The comparison verifies the interface keys, every implementing class ID and the order of the packed implementation lists produced using the standard packing approach.

All twelve comparisons passed. Every map contained 1,505 interface keys, with no differences in their associated implementation lists, including their order.

PASS: all 4 V1 maps match the actual standard map,
including packed list order.

PASS: all 4 V2 maps match the actual standard map,
including packed list order.

PASS: all 4 V4e maps match the actual standard map,
including packed list order.

The runnable classes perform these checks automatically, so anyone can reproduce the experiment in their own development environment.

Why not implement the optimization myself?

Unfortunately, the method I would like to optimize is private and cannot be replaced through a supported extension mechanism.

Back in 2022, I wrote an article about bypassing the mandatory next call in Chain of Command.

There are ways one could attempt to work around the extensibility limitations here, but I have no intention of doing that. Introducing unsupported workarounds into a framework as fundamental as SysExtension would be the wrong solution.

This is something that should be fixed in the standard product.

Source code and reproduction

I have prepared three self-contained runnable classes:

View the source code on GitHub

Download all three runnable X++ classes (ZIP)

Add them to a development model, compile them and execute each class after an independent AOS restart. The Infolog displays the execution times and the result of the comparison against Microsoft's actual reflection map.

Run the experiment in an isolated development environment, as the final verification invokes the standard reflection-cache population routine.

A suggestion to the Microsoft development team

The SysExtension framework has been with us since the AX 2012 era. The way we can discover application metadata has evolved considerably since then.

The first proposed optimization is a very small change that already provides a measurable improvement.

The second demonstrates that a substantially faster approach is possible using existing metadata APIs.

Naturally, Microsoft would need to validate the metadata-based algorithm against its supported application and platform configurations before adopting it. However, the supplied runnable classes provide a straightforward starting point for that validation.

Given how extensively SysExtension is used throughout D365FO, I believe this optimization deserves attention.

And I would certainly prefer to see those five seconds spent on something more useful than constructing a reflection map.

Saturday, March 22, 2025

Fix build error at "using Microsoft.IdentityModel.Clients.ActiveDirectory" in D365FO update 10.0.43

If you used Azure Active Directory Authentication Library (ADAL) in your customization, and get a compilation error at "using Microsoft.IdentityModel.Clients.ActiveDirectory" statement in 10.0.43 update -- this is because ADAL is deprecated and MS have removed the reference from the AOT. 

You will need to migrate you code to Microsoft Authentication Library (MSAL).

In order to do that, you will need to add the Microsoft.Identity.Client.dll library to your bin-folder (can be found in other subfolders under K:\AosService\PackagesLocalDirectory), and add a corresponding reference to a VS project. The reference will then be created as an XML-file. Both the DLL and the XML files must be added to source control via "Add Items to Folder...", like this:

K:\AosService\PackagesLocalDirectory\<package name>\bin\Microsoft.Identity.Client.dll

K:\AosService\PackagesLocalDirectory\<package name>\<model name>\AxReference\Microsoft.Identity.Client.xml

Then, you will need to change the code.

Before:

using Microsoft.IdentityModel.Clients.ActiveDirectory;

...

            ClientCredential clientCrendential = new ClientCredential(clientId, clientSecret);

            AuthenticationContext authContext = new AuthenticationContext(authority);

            AuthenticationResult authResult = authContext.AcquireToken(resource, clientCrendential);

            accessToken = authResult.AccessToken;

...

After:

using Microsoft.Identity.@Client;

...

            ConfidentialClientApplicationBuilder clientApplicationbuilder = ConfidentialClientApplicationBuilder::Create(clientId);

            IConfidentialClientApplication app = clientApplicationbuilder

                .WithClientSecret(clientSecret)

                .WithAuthority(authority)

                .Build();

            System.Collections.Generic.List<System.String> scopes = new System.Collections.Generic.List<System.String>();

            scopes.Add(resource + '/.default');

            System.Collections.IEnumerable enumerable = scopes;

            AcquireTokenForClientParameterBuilder parameterBuilder = app.AcquireTokenForClient(enumerable);

            var task = parameterBuilder.ExecuteAsync();

            task.Wait();

            AuthenticationResult authResult = task.Result;

            accessToken = authResult.AccessToken;

...


Wednesday, December 7, 2022

D365FO: Bypassing "next" in CoC

DISCLAIMER: Use this trick at your own risk. Do not do this, unless you absolutely have to. 

Some time ago I had to figure out why one of the custom services was slow. It took like 30+ seconds to return a dozen of trade agreements for a customer.

It turned out the SysExtension framework tried to collect data about classes through reflection, and it did that multiple times in the same session. 

The issue may be reproduced with this runnable class. Here, we instantiate instances of 4 different classes. The class constructors use SysExtension framework for figuring out which class type to build.


If running the class the first time, the output would look something like this:

SalesLineType::construct: 13610 ms
SalesSummaryFields::construct: 1968 ms
SalesQuantity::construct: 2078 ms
TradeModuleType::newFromModule: 3406 ms

After System administration -> Setup -> Refresh elements, the time would drop to:

SalesLineType::construct: 1735 ms
SalesSummaryFields::construct: 1781 ms
SalesQuantity::construct: 1641 ms
TradeModuleType::newFromModule: 1656 ms

But still, almost 2 seconds for every single class instance is too much. 

The following change can fix this issue by skipping metadata collection, if it is already done:


This code does the following: if the reflection is already collected (reflectionDataEnumerator.moveNext() returns "true"), we throw an exception of a type, that will most likely never be thrown from the "next populateFromMetadata();" itself. Then, we catch the exception, but that also means the "next" statement is skipped and the reflection cache data is not built from scratch again. 

After this change, the runnable class output looks like this:

SalesLineType::construct: 1657 ms
SalesSummaryFields::construct: 218 ms
SalesQuantity::construct: 125 ms
TradeModuleType::newFromModule: 157 ms

It is important, that this "skip" is only done when there is no transaction scope around, otherwise it would abort the transaction, therefore the check for ttsLevel. So, this trick will basically improve performance of certain "read" scenarios, but in order to improve performance for "write" scenarios, MS has to provide a fix.

Thursday, October 29, 2020

Marking via X++

X++ code for marking in D365FO (it is somewhat different from that in AX 2012):

    InventTransId         issueInventTransId   = 'x';
    InventTransId         receiptInventTransId = 'y';
 
    InventTransOriginId receiptInventTransOriginId = 
        InventTransOrigin::findByInventTransId(receiptInventTransId).RecId;
    InventTrans         receiptInventTrans         = 
        InventTrans::findByInventTransOrigin(receiptInventTransOriginId);
 
    InventTransOriginId issueInventTransOriginId = 
        InventTransOrigin::findByInventTransId(issueInventTransId).RecId;
    InventTrans         issueInventTrans       = 
        InventTrans::findByInventTransOrigin(issueInventTransOriginId);
 
    collection = TmpInventTransMark::markingCollection(
        InventTransOrigin::find(receiptInventTransOriginId),
        receiptInventTrans.inventDim(),
        receiptInventTrans.Qty);
 
    collection.insertCollectionToTmpTable(tmpInventTransMark);
 
    select firstonly tmpInventTransMark
        where tmpInventTransMark.InventTransOrigin == issueInventTrans.InventTransOrigin
           && tmpInventTransMark.InventDimId       == issueInventTrans.InventDimId;
 
    if (tmpInventTransMark.RecId != 0)
    {
        Qty qtyToMark = issueInventTrans.Qty;
 
        tmpInventTransMark.QtyMarkNow =  qtyToMark;
        tmpInventTransMark.QtyRemain  -= tmpInventTransMark.QtyMarkNow;
 
        mapUpdated = new Map(Types::Int64, Types::Record);
        mapUpdated.insert(tmpInventTransMark.RecId, tmpInventTransMark);
 
        TmpInventTransMark::updateTmpMark(
                receiptInventTransOriginId,
                receiptInventTrans.inventDim(),
                -qtyToMark,
                mapUpdated.pack());
    }

Wednesday, March 27, 2019

Common mistake, when creating Purchase Orders from X++

I would like to warn my fellow Axapta/AX/D365FO bloggers, that blind copy-pasting from each other seems innocent, but it fact may result in spreading bugs.

E.g., the following piece of code is very popular in "How to create Purchase Order from X++" posts.

numberSeq = NumberSeq::newGetNumFromCode(purchParameters::numRefPurchaseOrderId().NumberSequence,true);

Purchtable.PurchId = numberSeq.num();

The problem is numRefPurchaseOrderId returns the number sequence for purchase order confirmation number. For purchase order number, numRefPurchId should have been used. Using the wrong number sequence may result in duplicate key issues.

Thursday, December 6, 2018

Controlling grid line colors

Can see some folks have found the DisplayOptionInitialize event, still they are in doubt on how to control the displayOption settings based on the selected line.


Here is the solution:


X++:
 [FormDataSourceEventHandler(formDataSourceStr(Form1, SalesTable), FormDataSourceEventType::DisplayOptionInitialize)]
    public static void SalesTable_OnDisplayOptionInitialize(FormDataSource sender, FormDataSourceEventArgs e)
    {
        FormDataSourceDisplayOptionInitializeEventArgs args = e as FormDataSourceDisplayOptionInitializeEventArgs;
        RecId currentRecId = args.record().RecId;
        int rgbValue = 255 - (20 * (currentRecId mod 2));
        args.displayOption().backColor(WinAPI::RGB2int(rgbValue, rgbValue, rgbValue));
    }



Tuesday, November 6, 2018

Create LedgerDimension from main account and financial dimensions

The following code will (hopefully) keep generating valid LedgerDimension values, even after account structures or advanced rule structures are modified.

In the example below, there is an account structure with MainAccount-BusinessUnit-Department segments and an advanced rule with Project segment.

class TestLedgerDim
{        
    public static DimensionDynamicAccount generateLedgerDimension(
        MainAccountNum _mainAccountId,
        str _departmentId,
        str _businessUnit,
        str _projectId)
    {
        DimensionAttributeValueSetStorage dimensionAttributeValueSetStorage 
            = new DimensionAttributeValueSetStorage();

        void addDimensionAttributeValue(
            DimensionAttribute _dimensionAttribute, 
            str _dimValueStr)
        {
            DimensionAttributeValue dimensionAttributeValue;

            if (_dimValueStr != '')
            {
                dimensionAttributeValue = 
                    DimensionAttributeValue::findByDimensionAttributeAndValueNoError(
                        _dimensionAttribute,
                        _dimValueStr);
            }

            if (dimensionAttributeValue.RecId != 0)
            {
                dimensionAttributeValueSetStorage.addItem(dimensionAttributeValue);
            }
        }

        DimensionAttribute dimensionAttribute;

        while select dimensionAttribute
            where dimensionAttribute.ViewName == tableStr(DimAttributeOMDepartment)
               || dimensionAttribute.ViewName == tableStr(DimAttributeOMBusinessUnit)
               || dimensionAttribute.ViewName == tableStr(DimAttributeProjTable)
        {
            switch (dimensionAttribute.ViewName)
            {
                case tableStr(DimAttributeOMDepartment):
                    addDimensionAttributeValue(dimensionAttribute, _departmentId);
                    break;

                case tableStr(DimAttributeOMBusinessUnit):
                    addDimensionAttributeValue(dimensionAttribute, _businessUnit);
                    break;

                case tableStr(DimAttributeProjTable):
                    addDimensionAttributeValue(dimensionAttribute, _projectId);
                    break;
            }            
        }

        RecId defaultDimensionRecId = dimensionAttributeValueSetStorage.save();

        return LedgerDimensionFacade::serviceCreateLedgerDimension(
            LedgerDefaultAccountHelper::getDefaultAccountFromMainAccountRecId(
                MainAccount::findByMainAccountId(_mainAccountId).RecId),
            defaultDimensionRecId);
    }

    /// <summary>
    /// Runs the class with the specified arguments.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {   
        // Prints 110110-001-022-000002
        info(
            DimensionAttributeValueCombination::find(
                TestLedgerDim::generateLedgerDimension(
                    '110110', 
                    '022', 
                    '001', 
                    '000002')).DisplayValue);
    }

}