Showing posts with label best practice. Show all posts
Showing posts with label best practice. Show all posts

Friday, February 17, 2012

New AX 2012 intrinsic functions

Two new intrinsic functions were added in AX 2012. One to reference datasources of queries and another one to reference form controls:


Just want to remind the benefits of using intrinsic functions comparing to plain strings:

  • If the referenced object changes name the problem will be detected in compile time

  • The reference will be reflected as a cross-reference, making the dependencies more transparent

Tuesday, May 3, 2011

Surrogate keys in AX 2012

Data modeling enhancements were prioritized really high in AX 2012. I already mentioned one earlier – table inheritance, but there are a lot of other important features about data modeling.

One such feature is the support of surrogate keys. Surrogate keys recommended themselves as a very good solution for complex databases because of their beneficial properties, like immutability, robustness to redesign and performance. And now this best practice is coming to AX. It is the recommendation for AX 2012 to use surrogate keys for all new tables, unless there is a good reason not to do so.

Actually, previous versions of AX already have surrogates – RecIds. And it was possible to introduce surrogate key just by setting CreateRecIdIndex table property to Yes. But there is a problem with the inconvenience of working with surrogates in the UI. Imagine InventTable using surrogate key and all other tables that have relations to InventTable using its surrogate key as a foreign key. Then on any form where ItemId should be displayed (let’s say on the SalesTable) an extra join to InventTable will be needed to fetch the ItemId. And what if user can change the item? Then even more custom logic is needed to resolve the entered ItemId to the corresponding surrogate key value and write it to the SalesLine.

This inconvenience actually was a showstopper. But not anymore. AX 2012 got kernel support for surrogate key substitution. And not only in forms, but in Axd document services and even in the debugger.

Let me show an example of how it works:
UnitOfMeasure table uses surrogate key as a primary key. However, the user-friendly identifier of the UnitOfMeasure table records is the UnitOfMeasureSymbol field. This field is a part of the SymbolIdx index, which is specified as a replacement key on the UnitOfMeasure table.


This setup basically means that surrogate key values (RecIds) of the UnitOfMeasure table records will be automatically substituted in the UI with the replacement key values (UnitOfMeasureSymbols).
UnitOfMeasureConversion table has a relation to the UnitOfMeasue table through the surrogate key.


As you can see, on the UnitOfMeasureConversion form there are only UnitOfMeasureConversion datasources. And you can notice new ReferenceGroup control which is bound to the FromUnitOfMeasure field (which contains surrogate values).


And in the UI it will look just like UnitOfMeasureSymbol field is shown instead. And it can also be modified and that will be handled automatically, without a single line of code.


Actually ReferenceGroup control has much more interesting capabilities and thus deserves a separate post.

Monday, May 3, 2010

Overlay vs override

Microsoft is trying to achieve consistency among all the classes in AX to have the following condition met:
Each class has construct method which takes no parameters. This constructor should be the primary entry point for class construction, e.g. any other constructor should use construct() inside.
For the same reason, to avoid direct instantiation of the objects via new() method they are marked as protected. It is done in such way because it looks like overriding is much more maintainable than overlaying. It is better to create a sub-class in the outer layer that extends super-class in inner layer and overrides the required method + have construct() method overlaid to instantiate sub-class instead. Code upgrade in this case seems to be much cheaper comparing to the case when methods are overlaid directly on the super-class.

So my question basically is, if this statement is correct or not? Are you writing code in the described way? If no, why? What are the cases when overlaying is better that overriding?

Monday, April 5, 2010

Implicit casting from super-class to sub-class

X++ compiler allows casting from the super-class object to the sub-class. For example, UserConnection class extends Connection class. And you are allowed to write the following code:
UserConnection con = new Connection();
The only consequence of doing such thing is a run-time error thrown if a method that exists only on sub-class will be called for the instantiated object.
In the modern managed languages such implicit casting is not allowed and generates compilation error. So, it is best practice not to use it in AX too.

Thursday, March 18, 2010

Debug::assert

This method allows to check if some Boolean condition evaluates to true and if it doesn't - stop further execution and show stack trace. Debug::assert() should be used to validate some assumptions made in the code which should never happen if nothing is broken in the application. It means that wrong user input should not be asserted but rather validated by normal if statement and exception should be thrown if the input is wrong. However, if the code relies, for example, on query data source name, which can be broken only in development time - that is a good place to add assert to.

Example:
    Query query = new Query(querystr(Alertsetup));
    QueryBuildDataSource qbds;
    ;

    qbds = query.dataSourceName(identifierstr(EventRule));
    Debug::assert(qbds != null);

Wednesday, March 10, 2010

Define overwrites

It is a little bit weird how X++ compiler handles the case when macros with the same name are defined in the class declaration of a class and in the one of its methods. The expected behavior for me is to either not allow to do that or to have a macro from class declaration to be applicable everywhere except for the method where it is redefined. But in AX the value defined in the method will overwrite the value defined in the class declaration and will be the same in all methods.
Example:
class TestDefine
{
    #define.A(‘A’)
}

public void method1()
{
    ;
    info(#A);
}

public void method2()
{
    #define.A(‘B’)
    ;
    info(#A);
}

If method1 or method2 will be called the ‘B’ will be received in the infolog and not ‘A’.

The next question will be what if define is overwritten in several methods. The answer is that the result is undetermined. It depends on X++ compiler internal flow and cannot be predicted. So, just avoid such constructions and even better avoid defines at all.

Thursday, March 4, 2010

Global::queryValue method

This method translates anything into the correct query range value, so you don't have to care about how UTCDateTime value should be converted into a string or which symbols require slash before them. It is the best practice to always use this method when query range is assigned a value, even if the value is string.

Note, that queryValue('') will return the following string '""' (two double quotes) which will give empty string range value. If you want to clear the range you'll have to assign it's value with empty string directly.

Tuesday, February 23, 2010

Caching edit methods

There was a great improvement done to the form datasource caching in AX 2009 - it is possible now to cache not only display methods but edit methods too. The caching of the edit methods can be performed in the same way as caching of display methods - by using FormDataSource.cacheAddMethod() method.
Despite that great improvement a lot of forms in AX 2009 haven't consumed it. So if you are looking for a solution to speed up existing AX 2009 form, edit methods that are not cached is a good place to look at.

Wednesday, February 17, 2010

Temporary table residing tier

Temporary table resides on the tier where the first insert happened into it. Since temporary table data generation usually requires quite a lot of database transactions it makes sense to instantiate it on the server. However, if a temporary table is displayed on a form it makes sense to instantiate it on the client to avoid chattiness during displaying of the form. But anyway with such approach there will be a lot of client-server calls either during data generation or during displaying. To avoid that the following approach can be used:
  1. Create a temporary table instance on the server and fill it with data.
  2. Place all records from the table to a container and pass it to the client.
  3. Create a new temporary table instance on the client and fill it with data from the container.
  4. Use the client temporary table instance to display on a form.

Tuesday, February 16, 2010

Priority of Boolean operations

In X++ Boolean && and || operations have the same priority. That is not the case in other languages where && has higher priority than ||. So adding additional parenthesis to make sure that code works as expected is a good idea.
Example: (true || false && false) will be evaluated to false in X++, but in C# it will be evaluated to true.

Monday, February 15, 2010

Messages mentioning table or field

It is the best practice to use both table or field UI name and system name in error messages. For example, the standard “The record already exists” message looks like:
Cannot create a record in Inventory model groups (InventModelGroup). Inventory model group: Std, Standard. The record already exists.
So both UI name (Inventory model groups) and system name (InventModelGroup) appear in the message.
To retrieve those names tablepname() and tablestr() functions can be used correspondingly. For the fields there are similar functions: fieldpname() and fieldstr().

Thursday, February 4, 2010

FormDataSource.object method

There is a nice way to change a property for all controls on a form that are bound to the same field, for example, hide\unhide or enable\disable. FormDataSource has method object() which accepts field number as parameter and returns an object of type FormDataObject which has several properties to change controls' behavior, like visible(), enabled(), allowEdit() and others.
Example:
inventBatch_ds.object(fieldnum(InventBatch, ItemId)).visible(false);
This way to change controls' properties is more preferable than working with individual controls, since it's possible that user will add new controls for the same field using user setup.

Tuesday, February 2, 2010

FormButtonManager

In AX 2009 a new nice framework was introduced to simplify form buttons enabling\disabling. This framework is primarily used for list pages, however it can be used for regular forms too. Usage of this framework is quite simple. A new class should be created for a form which implements ButtonStateProvider interface. This class will contain methods which define buttons enable\disable rules. After that form buttons should be mapped to the rules using FormButtonManager class. That's pretty much it. The only thing left is to call FormButtonManager.refresh() method on selection changed event to get buttons enabled or disabled according to specified rules.
For more details you can look at SMAAgreementTableListPage and SMAAgreementTableButtonStateProvider class.

Friday, January 29, 2010

FormDataSource.markChanged method

In AX 2009 a new method was added to the FormDataSource – markChanged() which is dedicated specifically to handle selection change event. Before that active() method was commonly used for this purpose, however it is not precise and there are cases when selection is changed but active() method is not triggered. It is the most important to use markChanged() instead of active() when multiple records selection needs to be handled.

Thursday, January 28, 2010

PageActivated metod

Overriding of tabChanged method on the form Tab control leads to locking of user setup for this tab and all it child controls.

The best practice is to override pageActivated method on the TabPage control which in most cases allows to achieve the same behavior as tabChanged method but does not lock user setup.

Monday, January 25, 2010

Client server method keywords

There is a difference between declaring a static method with both client and server keywords and without any:
public static client server void method1()
{
}

and
public static void method2()
{
}

If a method is declared without these keywords the tier to execute the method will be determined based on RunOn property of the class. So if a class has RunOn property equals to "Client", then method2() will always be called on the client tier but method1() will be called on the tier where it was called from.
Considering that it is a best practice to explicitly mark methods with both client and server keywords if it is designed to be executed on both tiers.

Thursday, January 21, 2010

Global::isRunningOnServer

This method allows to determine if the code is being executed on server (or client). It can be useful if there is a class which is explicitly designed to be executed on "called from" tier but which has a method that performs a lot of database calls. Execution of the "heavy" method on the object which resides on the client can result in a large numer of RPC calls which seriously reduces performance. To avoid that, object on the client can be serialized, instantiated on the server, deserialized and then execution of the desired method can be performed. To determine whether object is on the client (or server) just call Global::isRunningOnServer() method.

Wednesday, January 20, 2010

Intrinsic functions for Maps and Views

It appears that the same intrinsic functions that work for tables can be used on AOT Maps and Views. Among them tableStr, fieldStr, tableMethodStr, etc.
So, if a map or a view is needed to be referenced via reflection, those functions should be used.

Friday, January 15, 2010

Global::formHasMethod

This method determines if a form has the specified method. It is a best practice to call this method before executing the desired method on the form itself.

For example:
Object formRunObject;

if (formHasMethod(formRun, identifierstr(refreshForm)))
{
    formRunObject = formRun;
    formRunObject.refreshForm();
}