Visual Studio – run as administrator

This is something that I generally forget whenever I create a new dev-box. Visual Studio needs to be running as Administrator otherwise you’ll get messages such as “Access to the path ‘K:\AosService\PackagesLocalDirectory\Bin\InstalledVersion.json’ is denied”:

Skærmbillede 2020-03-23 kl. 07.35.17.png

and “Visual Studio is not running as administrator. Finance and Operations (Dynamics 365) requires Visual Studio to be running as administrator. Please restart Visual Studio as administrator”:

Skærmbillede 2020-03-23 kl. 07.35.28.png

You can always right-click on your VS-shortcut and select “Run as administrator”, but if you’re even remotely like me, you’ll forget that approx 82% of the times.

So what you need to do is to modify the shortcut you’re using. In my case I modify the shortcut in my Taskbar. Right click on the shortcut for Visual Studio and instead of clicking “Run as administrator” you click Properties:

Skærmbillede 2020-03-23 kl. 09.27.35.png

In the properties window you click the Advanced button:

Skærmbillede 2020-03-23 kl. 09.29.37.png

In the window that opens up tick the “Run as administrator”:

Skærmbillede 2020-03-23 kl. 09.30.03.png

Click OK and OK and you’re done. Next time you use the shortcut it runs VS as administrator.

Debugging Commerce Runtime in the New Dynamics AX (AX7)


The New Dynamics AX has certainly shown us new ways of working and for the developer the learning curve has been pretty steep.

With everything being Visual Studio for the developers new work routines are implemented and that goes for debugging as well.

Now, the Visual Studio debugger is great. So we are not losing any ground. We do however have to think a bit different in order to nail those tricky troubleshooting situations. In this post I will show how to debug the Commerce Runtime part of the Retail Server.


Step 1 – Getting the IIS ready

Navigate to the Retail Server folder. One way to get there is to open the IIS Manager. Locate and select the RetailServer in the Sites list to the left and select Explore. In the web.config file change

<compilation debug="false" targetFramework="4.5" />


<compilation debug="true" targetFramework="4.5" />

When you save the file you cannot save it to its original position. Save it to your desktop or somewhere else neutral and then copy it to the original folder.

Restart the IIS


Step 2 – Set the breakpoint

Now start up Visual Studio and open the solution CommerceRuntime in the RetailSDK folder \RetailSDK\Code\CommerceRuntime.

In the solution explorer locate the Discount.cs file in Runtime.PricingEngine project and add a breakpoint. Just to keep it simple I have put it into the constructor:Breakpoint Discount constructor


Step 3 – Start the Modern POS

Now it is time to fire up the Modern POS. Just do a login and leave it there for a while.


Step 4 – Get the debugger ready

Go back to Visual Studio, go to the Debug menu and select Attach to process.

Change the code type from automatic to Managed (v4.6, v4.5, v4.0)


Mark Show processes from all users, select the w3wp.exe processes and click Attach.


I know that you probably only need to attach to one of them; but it is much easier just selecting them all.

Take a quick look at your breakpoints to make sure that they are active. If not you might be missing a reference in the commerceruntime file.

Breakpoint active Discount constructor

Step 5 – Back to the POS to get the debugger activated

What we need to do now is to get the POS to require an instance of the Discount object on the retail server. In this example I add a pair of sunglasses to the basket:

Add product to get the Discount object instantiated

That gets us into the debugger and we can do what we need to do in order to see how it works or start troubleshoot.

Debugger activated

I hope this helps you get a bit deeper into the retail server or other services related to the New Dynamics AX.




Locate duplicate values (or the opposite) in a table

The way X++ handles SQL statement often lacks a bit compared to what you can do in standard TSQL.

One of the areas is if you want to get a set of records from a table where a specific value in a field only occurs once in the table. You could traverse through the records and compare values as you go along. That could pull down performance significantly depending on the record count. Another way of doing it is to group by the field while counting the records in e.g. RecId. Then traversing this result set and look at the value in RecId could give you either the unique or not unique value depending on what you need.

A better way would be to let the SQL server do some of the work and consequently return as few records as possible. Here is a job that illustrates this and the group by version mentioned above.

AX 2012 queries support the HAVING clause. That can in some scenarios do the same and a bit more elegant than this.


static void DEMO_NoDuplicates(Args _args)
    CustGroup custGroup;
    CustGroup custGroup2;
    PaymTermId lastPaymTermId;

    info("TRAVERSE COUNT");

    while select count(recid) from custGroup
        group by PaymTermId
        if (custGroup.RecId == 1)
            while select custGroup2
                where custGroup2.PaymTermId == custGroup.PaymTermId

    info("USE JOIN");
    while select custGroup
        order by PaymTermId
        notexists join custGroup2
            where custGroup.RecId != custGroup2.RecId
               && custGroup.PaymTermId == custGroup2.PaymTermId

Using “Create document service” wizard results in a method xMLMapUnitId does not exist

And that is – in AX 2012 – absolutely correctly observed by the compiler. The method was present in earlier versions of AX but went missing in AX 2012 and was replaced by the method xmlMapUnitOfMeasureSymbol.

So if you use the wizard on for example on a query using ProdTable you might end up with an error telling you that this.mapPolicy().xMLMapUnitId() does not exist. Replace it with this.mapPolicy().xmlMapUnitOfMeasureSymbol() and you are good to go. It will also tell you that this.axUnitId() is incorrect which also is true. The correct method name is axUnitOfMeasureSymbol().

Once you know it … 🙂

How to delete a label file in AX 2012

If you end up with an obsolete label file in AX 2012 and want to delete it you cannot just right click and select delete from the popup menu.

To get rid of the label file you can do the following:

  1. Create a new model. In this example named DeleteMe
  2. Move your label file to the DeleteMe model
  3. Use AXUTILs delete function to delete DeleteMe
  4. Restart the AOS

You have successfully removed the label file from your installation.

Manipulating data while ignoring a TTSABORT

OK, the subject of this post will probably be categorised as dangerous and by some as borderline stupid. The content should NOT be considered used in everyday work since it very easily could give you massive inconsistency in data and a broken system. There! I said it and I do not want to be the one saying I told you so afterwards. This blog post is only for information and not a recommendation.

So what is all the fuzz about? Well, sometimes it could be nice allowing some data to be inserted, updated or deleted although a TTSABORT command or an error is thrown. That could be relevant in regards of a log being updated no matter what the result of a job is or the likes.

The mechanism is known from the batch queue that has its status updated no matter how the job finishes.


The trick is using the UnitOfWork and UserConnection framework within the TTS-scope. This allows you to create a connection to the database that is not a part of the TTS but is running its own show.

And this is where it gets dangerous/stupid in some scenarios. Imagine a inventory transactions customisation manipulating data in some circumstances within the TTS and some without. The result could be data almost impossible to recover to a consistent state again.


In this example we want to update the Tax Group Id on the Customer groups and log the changes to a table no matter what happens.

I have created a table – DEMO_Log – with CustGroup as the only field. We would like this table to receive a new record not depending on success nor failure in the update of the CustGroup table.

Next step is to create a class doing the work. In this case it is called DemoIgnoreTTSAbort and it has a run method like this:

private void run()
    info("BEFORE UPDATING");



It starts by showing the current records in a resume like this

private void showInfo()
    CustGroup custGroup;
    DEMO_Log log;

    select count(RecId) from custGroup
        where custGroup.TaxGroupId;

    select count(RecId) from log;

    info(strFmt("Customer groups with Tax group id: %1", custGroup.RecId));
    info(strFmt("Log records: %1", log.RecId));

The idea is to give us a count of customer groups with Tax group ids and the count of records in our log table.

Then we – inside a TTS scope – uses the updateCustGroup method to try updating the groups like this:

private void updateCustGroup()
    CustGroup custGroup;

    while select forUpdate custGroup
        where ! custGroup.TaxGroupId
        custGroup.TaxGroupId = 'TX';

Each CustGroup record with no TaxGroupId content is updated with ‘TX’ and a log is inserted using the method insertInLog that goes like this:

private void insertInLog(CustGroupId _custGroupId)
    DEMO_Log log;
    Log.CustGroup = _custGroupId;

I think that one is pretty self explaining…

The TTS scope is then ended with an TTSABORT so no records within the scope is updated/inserted.

We then pull the showInfo once more to se if anything has happened. And nothing has. No surprise.


The next part is a new TTS scope and a method (updateCustGruop2) which is almost identical to updateCustGroup is used:

private void updateCustGroup2()
    CustGroup custGroup;
    while select forUpdate custGroup
        where ! custGroup.TaxGroupId
        custGroup.TaxGroupId = 'TX';



The only difference between updateCustGroup and updateCustGroup2 is that it calls insertInLog2 instead of insertInLog after updating each record.

This method is the key to all this and it looks like this:

private void insertInLog2(CustGroupId _custGroupId)
    DEMO_Log log;
    UnitofWork unitOfWork;
    UserConnection userConnection;

    userConnection = new UserConnection();
    unitOfWork = new UnitofWork();

    log.CustGroup = _custGroupId;


Compared to insertInLog it starts by adding to new variables – unitOfWork and userConnection which gives us an extra connection to the database not included in the TTS scope. First is a basic instantiation followed by the insert of the DEMO_Log record like in the insertInLog method. The next statement is where we tell unitOfWork to insert the log record(s) upon the call of the saveChanges method. There is a deleteOnSaveChanges and updateOnSaveChanges if you want something else than inserts.

Finally we call the saveChanges using the above declared userConnection.

Ending the run method with another call of the showInfo reveals that although we abort our TTS scope and the customer groups remain unchanged the log is fully updated:

Message (05:09:54 am)
Customer groups with Tax group id: 0
Log records: 0
Customer groups with Tax group id: 0
Log records: 0
Customer groups with Tax group id: 0
Log records: 7

Once again: Remember that this is only to be used with extreme caution …

Joins, indexes and an example of when they don’t match…

We experienced some data locks that gave a customer some performance issues. Going through the motions we found this statement (scrambled) being the problem:

update_recordSet adjustment
    setting Voucher = voucher
    where ! adjustment.voucher
        join trans
            where trans.Status == Status::Open
               && trans.DateTime < perDateTime
               && trans.RecId == adjustment.Trans;

The table Adjustment is connected to the table Trans through a relation like this: Adjustment.Trans = Trans.RecId. And Adjustment has – among others – an unclustered index like this: Trans, Voucher and a couple of other fields.

So you might think that the SQL server was capable of utilising this index since both Trans and Voucher are in play in the attempt to limit the records involved.

Looking at it from the SQL server it ends up like this:

AND ((T1.VOUCHER = @P5)))
AND (((T2.STATUS = @P8)

Now, when executing this ended up giving an index scan resulting in heavy locking of data. The reason for this – and the reason why the index could not be used – is that the SQL server sees this as two statements selecting adjustment records with the Voucher field as only range and the trans records with the specified ranges except the relation range and then returns the intersection of these two result sets.

Adding an index with Voucher as first field solves the problem and the data locking stops.

Prefixing a strings with @’s – multi lines and escape characters

This post just shows a couple of ways to use the feature of putting a @ in front of a text string and what the result is.

The first example shows how to use it when referring to eg. a file with backslashes.

Example 2 shows how to split a text line into two or more lines for easier reading.


static void coupleOfStringTricks(Args _args)
    str text1;
    // Example 1
    // ---------

    // Using a backslash in the text messes up the result
    text1 = "c:\temp\someFile.txt";

    // An option is to use double backslash
    text1 = "c:\\temp\\someFile.txt";

    // Or use the @ as prefix to the string
    text1 = @"c:\temp\someFile.txt";

    // Example 2
    // ---------

    // Allowing to extend a text string over multiple lines
    text1 = @"This text is toooooooooooooooooooo loooooooooooooooong
    to keep in one line for easy reading";

Using HAVING in a query

With AX 2012 we now have the option of using HAVING in a query. This allows us to limit a result set based on aggregated fields.

The advantage is that we let the SQL server do some filtering and receive less records compared to the old-school version were we had to receive all records and then use an IF or the likes to filter away the records that did not match the criterias.

In this simple example we want to get all sales ids on orders having lines with a line amount total of 100000 and beyond.


static void SimpleQueryWithHavingExample(Args _args)
    Query query;
    QueryRun queryRun;
    QueryBuildDataSource qBDS_SalesTable;
    QueryBuildDataSource qBDS_SalesLine;
    SalesTable salesTable;
    SalesLine salesLine;
    // Init query
    query = new Query();
    // Add datasources and use standard relations
    qBDS_SalesTable = query.addDataSource(tableNum(SalesTable));
    qBDS_SalesLine = qBDS_SalesTable.addDataSource(tableNum(SalesLine));
    // Add a group by on SalesTable
    qBDS_SalesTable.addGroupByField(fieldNum(SalesTable, SalesId));

    // Add aggregation on LineAmount
    qBDS_SalesLine.addSelectionField(fieldNum(SalesLine, LineAmount), SelectionField::Sum);
    // Add the having filter
    query.addHavingFilter(qBDS_SalesLine, fieldStr(SalesLine, LineAmount), AggregateFunction::Sum).value(SysQuery::range(100000, ''));
    // Create and run the queryRun object
    queryRun = new QueryRun(query);

    while (
        salesTable = queryRun.get(tablenum(SalesTable));
        salesLine = queryRun.get(tableNum(salesLine));
        info(strFmt("%1 %2", salesTable.SalesId, salesLine.LineAmount));


I am sure that this will come in handy. 🙂