AX Developer Tips for Newbies: Part 2

By Laura Lake | January 13, 2016

Ax developer tips for newbies: part 2

In a previous post I compiled a collection of tips gleaned from teaching AX developers in my training classes. The selections included in AX Developer Tips: Part 2 are  dedicated to X++ coding tips.

Read more on AX Developer Tips for Newbies: Part I here. 

 

Select statements

A. It is highly recommended to use a field list in your Select statements if you do not need access to all fields in the table. Just remember, only the fields in the list will contain values. If you try using another field later in your code, you will get unexpected results.

CustTable   custTable;
    
    select accountNum from custTable where custTable.AccountNum == 'US-001';
    
    
    if (custTable.Blocked) //this will always be false because the field is null
    {
    }

B.  Similarly, the exists/notexists join returns no data at all. In the following statement, the custInvoiceJour record buffer will contain no data.

CustTable   custTable;
    CustInvoiceJour custInvoiceJour;
    CustTrans       custTrans;
    
    select custTable
        exists join custInvoiceJour
            where custInvoiceJour.OrderAccount == custTable.AccountNum;

 

For this reason, it is not possible to join another table using custInvoiceJour. This won’t work. The custTrans buffer will be empty.

CustTable   custTable;
    CustInvoiceJour custInvoiceJour;
    CustTrans       custTrans;
    
    select custTable
        exists join custInvoiceJour
            join custTrans 
                    where custInvoiceJour.OrderAccount == custTable.AccountNum
                        && custTrans.Invoice == custInvoiceJour.InvoiceId
                        && custTrans.AccountNum == custInvoiceJour.InvoiceAccount
                        && custTrans.transDate == custInvoiceJour.InvoiceDate    
                        && custTrans.Voucher == custInvoiceJour.LedgerVoucher;

 

Where Clause and Indexes

When issuing select statements against tables in X++ code, align the where clauses in the X++ select statements to the fields that are contained within an existing index. If this is not possible, then consider adding an index to the table that matches the where clause. Where statements that do not align with indexes can cause table scans which lead to significant performance problems when the tables have a large number of records in them. This is especially true when selecting records from transactional tables.

Avoid statements like the following where the LedgerJournalTrans table does not have an index that contains the AcknowledgementDate in it.

LedgerJournalTrans ledgerJournalTrans;
 
    
    while select ledgerJournalTrans where ledgerJournalTrans.AcknowledgementDate== today()
    {
        print ledgerJournalTrans.AmountMST;
    }

 

 

FirstOnly

In select statements use the keyword firstonly to retrieve the first record found in the database table when verifying that a condition is true or false. For example when verifying if a given sales order contain any sales lines, firstonly can be used because once the first sales line is found the condition is true. Also use firstonly when the developer knows that only one record will be found in the table. By using the keyword the search through the database is completed as soon as the first record is identified.

 

Replace this code:

static CustTable find(CustAccount _custAccount, boolean _forUpdate = false)
{
   CustTable custTable;
   ;
   if (_custAccount)
   {
     custTable.selectForUpdate(_forUpdate);
     select custTable
        where custTable.AccountNum == _custAccount;
  }
  return custTable;
}

With:

static CustTable find(CustAccount _custAccount, boolean _forUpdate = false)
{
   CustTable custTable;
   ;
   if (_custAccount)
   {
      custTable.selectForUpdate(_forUpdate);
      select firstonly custTable
         where custTable.AccountNum == _custAccount;
   }
   return custTable;
}

 

Transactions and Locking

A.  When there are ttsbegin and ttscommit statements nested within other ttsbegin and ttscommit statements, locks held on records in the table are not released until the outer ttscommit is reached, so keep the number of lines of code between the ttsbegin and ttscommit as small as possible. Additionally since the locks are not released until the ttscommit is reached avoid any tts statements that wrap dialogs requiring user intervention.

B. In the following code locks are initiated in both of the update statements. Those locks are not released until the final/outer ttscommit statement is reached:

CustTable ct;            
    SalesTable st;
 
    ttsbegin;
    while select forupdate Blocked from ct where ct.AccountNum == '1101'
    {
 
         ct.Blocked = CustVendorBlocked::All;  
         ct.update(); //lock obtained here
         //do something                
         ttsbegin;
         while select forupdate st where st.SalesId == "SO-101246"
         {
                st.CustAccount = "1101"; 
                st.update(); //lock obtained here
         }
         ttscommit; //locks are not released here
 
         print ct.Blocked;
     }
     ttscommit; // both locks are released here
 

 

Table Methods

Before writing a lot of code to access or update base tables in AX, take a look at the methods on the table you are interested in. Most tables in AX have built-in methods you can use to perform basic tasks like finding and initializing records.

Examples:

Find method – find a record by the primary key

static CustTable find(CustAccount   _custAccount,
                      boolean       _forUpdate = false)
{
    CustTable custTable;

    if (_custAccount)
    {
        if (_forUpdate)
        {
            custTable.selectForUpdate(_forUpdate);
        }

        select firstonly custTable
            index hint AccountIdx
            where custTable.AccountNum == _custAccount;
    }

    return custTable;
}

 

InitFrom methods -Initialize fields in the table from another table

public void initFromPostingProfile(CustPostingProfile _custPostingProfile)
{
    CustLedger          custLedger;
    CustPostingProfile  custPostingProfile = _custPostingProfile;

    if (! custPostingProfile)
    {
        custPostingProfile = CustParameters::find().PostingProfile;
    }

    custLedger = CustLedger::find(custPostingProfile);

    if (! custLedger)
    {
        throw error(strFmt("@SYS27773",custPostingProfile));
    }

    this.Settlement             = custLedger.Settlement;
    this.Interest               = custLedger.Interest;
    this.CollectionLetter       = custLedger.CollectionLetter;
    this.PostingProfileClose    = custLedger.PostingProfileClose;
    this.PostingProfile         = custLedger.PostingProfile;
}

 

 

Cross-reference

Before anything else, do yourself a favor and update the AOT cross-reference in your development environment. The cross-reference system allows you to see the relationships between objects. It is most useful for finding where EDT’s, fields or methods are used in AX. When you are learning, it is an invaluable tool for quickly finding code examples in the base product and also ensures that you adhere to standard coding practices.

Yes, the update takes a long time to run. Try running it from a Job instead of from the Tools menu. Here is a sample job. Start it up at the end of your work day and it will be finished by the next morning.

static void CrossRefUpdate(Args _args)
{

    xRefUpdateIL rbbTask = new xRefUpdateIL();;
    
    rbbTask.setFullTree(true);
    rbbTask.setSelective(false);
    rbbTask.setUpdateTableRelation(true);
    rbbTask.run();

}

 

Once the job is complete, you will have the Used By option as below:

AX Dev Tips

 

We can find out how the ChooseLines method is used and from where:

Choose Line Method in AX

 

Best Practices Compiler

Set the Compiler to Level 4 when you are writing new code. AX will point out Best Practice deviations at compile time.

Best Practice Compiler

 

Under Tools, Options, Development Tab, select Best Practices. Here you can set the checks that you want to perform.

Best Practices in Dynamics AX

 

 

Related Posts

Recommended Reading:

Manage U.S. Use Tax on Purchase Orders in Dynamics 365 Finance and Operations

  Managing sales tax requirements on your business purchase can be complicated, but Dynamics 365 Finance and Operations can help […]

Read the Article
5.19.22 Dynamics CRM

How to Write a Great Support Ticket in the Stoneridge Support Portal

Submitting a support ticket through the Stoneridge Support Portal is a quick and effective way to get assistance for any […]

Read the Article

Managing Your Business Through Uncertain Times Using Dynamics 365 Finance and Operations

  Dynamics 365 Finance and Operations (F&O) can help you make informed decisions on how to move your business forward. […]

Read the Article
5.13.22 Power Platform

Using Power BI Object Level Security

  The following article will demonstrate how to use Power BI Object Level Security to disable column data based on […]

Read the Article
5.12.22 Dynamics CRM

How to Use the Stoneridge Support Portal

Stoneridge Software’s support portal is an intuitive and useful function that makes it easy for you to access resources to […]

Read the Article
5.6.22 Dynamics GP

Dynamics GP Transaction Removal: Purchase Orders

  Are you having performance issues with Purchase Orders?  Do you find that there are old Purchase Orders on your […]

Read the Article
5.5.22 Dynamics GP

The Real Story about the Long-Term Future of Dynamics GP Support

I’ve seen a number of people put forward comment that Dynamics GP is going away and you have to get […]

Read the Article

New Features in Dynamics 365 Business Central 2022 Wave 1 Release – Financial Enhancements

The Dynamics 365 Businses Central 2022 Wave 1 Release has a lot of new and exciting features to help your […]

Read the Article
4.29.22 Dynamics GP

Dynamics GP Transaction Removals: Bank Reconciliation

  This is part 2 of a 3 part series on Dynamics GP Transaction Removals. These quick tips will hopefully […]

Read the Article

Start the Conversation

It’s our mission to help clients win. We’d love to talk to you about the right business solutions to help you achieve your goals.

Subscribe To Our Blog

Sign up to get periodic updates on the latest posts.

Thank you for subscribing!

X