Tuesday, August 28, 2018

Class extension/ Method extension in D365FO/AX 7.0

This article describes the new class extension model in X++.
Because over-layering is a very intrusive feature, we recommend that you not use it. The alternative to over-layering is extension. Extension lets you extend existing artifacts in a new model. Extensions are easier to maintain, but the amount of extension that can be done during customization is limited. There are rich ways to extend the metadata. For example, you can add new fields to a table. This article describes how X++ code can be extended, so that you can add methods and state to artifacts that are defined in other models without recompiling those models. A similar code extension mechanism already exists for X++ and is modeled after the corresponding feature in C#. Under this mechanism, a class can be designated as an extension class through a naming convention and by hosting public static methods. In the existing feature, the type of the first argument that is passed to the extension method is the type to extend. What this article describes is the next step in that direction, which offers a more capable and natural extension story. In objected-oriented programming, the term extend has a well-defined meaning. If we say, "class B extends class A," we mean that B inherits from A, and the usual object-oriented rules are implied. In fact, this term is even used in the X++ syntax that is used in class declarations to express this relationship. At the same time, we use the term extension to talk about metadata that has contributions from several models. To avoid overloading the term extend, we will instead use the term class augmentation to designate the relationship between a class A in a base model and a class B in a model that depends on it, where B provides additional functionality to class A in the context of that model. Nevertheless, we will also continue to use the term extension class, because it's prevalent.

The effective class concept

It's useful to have a term for a class that consists of the public members of the augmented artifact and all the public members of all the class extensions that augment that artifact. This class is called the effective class in a given model. The following illustration shows an artifact, MyArtifact, that is defined in a base model, MyModel, and two dependent models that have extension classes for MyArtifact. Artifact MyArtifact that is defined in base model MyModel, and two dependent models that have extension classes for MyArtifact In this example, the effective class is the class in the extension models that contains all the original methods and all the public artifacts from the extension classes. The effective class isn't the same in every model, because it includes only the class extensions that are defined in a given model. The following illustration shows the effective class of MyArtifact in the MyExtensionModel model. Effective class of MyArtifact in MyExtensionModel We will describe class extensions by using a class that is named MyClass in a model that is named MyModel.
class MyClass
{
    public int mycState;
    public str mycMethod(int arg)
    {
        // ...
    }
}
We can add new methods and state to MyClass by introducing an extension class in the extension model (MyExtensionModel) that builds on top of (that is, has a dependency on) MyModel.

Extension class declarations

Extension classes are classes that are adorned with the ExtensionOf attribute and that also have a name that has the _Extensionsuffix. (This restriction on the naming might be removed later.) The name of the extension class is otherwise unimportant. The class augments the artifact that is specified in the ExtensionOf attribute, as shown in the following example.
[ExtensionOf(classStr(MyClass))]
final class MyClass_Extension
{
    private void new()
    {
    }
}
Because the classes are instantiated by the runtime system, it's not meaningful to derive from the extension class. Therefore, the extension class must be marked as final. The classStr compile-time function must be used and has two purposes:
  • It produces a compilation error if the MyClass class doesn't exist.
  • The compile-time function that is used tells the compiler what kind of artifact is augmented. Artifact names by themselves don't uniquely identify a given artifact to augment. For example, forms can have the same names as tables, classes, and enums.
Any number of extension classes can augment a given artifact in a particular model. Extension classes are never referenced directly by the programmer, only by the runtime system.

Extension class inheritance

Any class that inherits from an augmented class also inherits the effective class. In other words, the classes that inherit from a class that has extensions inherit the methods that are defined in the extension classes.

Constructors

X++ supports both instance constructors and static constructors.

Instance constructors

The instance constructor is the method that is named new. The instance constructor that is defined in an extension class can't have parameters. Instances of the extension classes are created, and the runtime system calls their constructors as required by the usage scenario. These constructors are never explicitly called by your code. Constructors are useful for initializing the state of the extension objects. It's guaranteed that the constructor that is provided in an extension class will be called one time before any instance method or the instance state on the extension class is accessed. However, if no such references are made, the constructor isn't called.

Static constructors

Static constructors are the parameter-less static methods that are named typenew. Static constructors can be defined on extension classes. It's guaranteed that the runtime system will call the constructor before the first reference to the extension type. You can't assume any particular order of invocation for static construction among a set of extensions.

Methods

The public methods that are defined in extension classes provide additional functionality to the augmented class in the context of the model where the extension class is defined. Only public methods are exposed in this way. You can define private methods to help implement the public methods, but those private methods aren't part of the effective class. Because extension classes are final, methods can't be marked as protected.

Instance methods

The following example defines an extension method that is named ExtensionMethod and that augments MyClass.
[ExtensionOf(classStr(MyClass))]
final class MyClass_Extension
{
    private void new()
    {
    }
    public int ExtensionMethod(int arg)
    {
    }
}
The public instance method (ExtensionMethod) is defined in the extension class. Therefore, it's available just as if it were defined in MyClass in the context of the model where the extension class is defined. The following example shows how to call the method in the model.
MyClass c = new MyClass();
print c.ExtensionMethod(32);
Note that the instance method that is defined in the extension class is used as an instance method on the augmented artifact. An extension method can access public members only from the artifact that it augments (Access to protected methods and members is also supported if you are on platform update 9 or newer). This behavior is by design. No artifact should be able to interact directly with state and methods that are explicitly hidden through the private, or internal keywords. Otherwise, direct interaction with explicitly hidden state and methods could cause malfunction by invalidating key implementation assumptions in those artifacts. Methods and statements in the method body can use the this keyword. In this context, the type of this is the effective class of the augmented artifact.

Static methods

Methods that are defined as public and static in the extension class are available as static methods on the artifact that is augmented.
[ExtensionOf(classStr(MyClass))]
final class MyClass_Extension
{
    private void new()
    {
    }
    public int method1(int arg)
    {
    }
    public static real CelsiusToFahrenheit(real celsius)
    {
        return (celsius * 9.0 / 5.0) + 32.0;
    }
}
The following example shows how to call the method in the model.
var temp = MyClass::CelsiusToFahrenheit(20.0);
A static method can access the public static methods and state in the effective class of the augmented artifact. As an interesting side effect, static extension methods on the Global class become available in the language as functions, which are available without any prefix.

State

In addition to providing static and instance methods to an artifact, you can add instance state and static state.

Instance state

Instance state, which is state that pertains to a particular instance of an artifact, can be specified on extension classes. The following example defines a state that is named state.
[ExtensionOf(classStr(MyClass))]
final class MyClass_Extension
{
    public int state;
    private void new()
    {
    }
}
The following example shows how to use state in your code.
MyClass c = new MyClass();
c.state = 12;

Static state

Static state applies to the type instead of an instance of the type. The following example shows a static extension state.
[ExtensionOf(classStr(MyClass))]
final class MyClass_Extension
{
    public int state;
    public static int staticState;
    static void TypeNew()
    {
        staticState = 77;
    }
}

Chain of Command / CoC in D365FO/ AX 7.0

Class extension via method wrapping and Chain of Command (CoC)

The functionality for class extension, or class augmentation, has been improved in Microsoft Dynamics 365 for Finance and Operations. You can now wrap logic around methods that are defined in the base class that you're augmenting. You can extend the logic of public and protected methods without having to use event handlers. When you wrap a method, you can also access public and protected methods, and variables of the base class. In this way, you can start transactions and easily manage state variables that are associated with your class.
For example, a model contains the following code.
class BusinessLogic1
{
    str DoSomething(int arg) {
    …
    }
}
You can now augment the functionality of the DoSomething method inside an extension class by reusing the same method name. An extension class must belong to a package that references the model where the augmented class is defined.
[ExtensionOf(ClassStr(BusinessLogic1))]
final class BusinessLogic1_Extension
{
    str DoSomething(int arg) {
        // Part 1
        var s = next DoSomething(arg + 4);
        // Part 2
        return s;
    }
}
In this example, the wrapper around DoSomething and the required use of the next keyword create a Chain of Command (CoC) for the method. CoC is a design pattern where a request is handled by a series of receivers. The pattern supports loose coupling of the sender and the receivers.
We now run the following code.
BusinessLogic1 c = new BusinessLogic1();
info(c.DoSomething(33));
When this code is run, the system finds any method that wraps the DoSomething method. The system randomly runs one of these methods, such as the DoSomething method of the BusinessLogic1_Extension class. When the call to the next DoSomething method occurs, the system randomly picks another method in the CoC. If no more wrapped methods exist, the system calls the original implementation.

Supported versions

Important
The functionality that is described in this topic (CoC and access to protected methods and variables) is available in Platform update 9. However, the class that is being augmented must also be compiled on Platform update 9 or later. As of August 2017, all current releases of the applications for Finance and Operations have been compiled on Platform update 8 or earlier. Therefore, to wrap a method that is defined in a base package (such as Application Suite), you must recompile that base package on Platform update 9 or later. As an example: If you create your own extension model that is augmenting a class that exists in the Application Suite model, and if you are using CoC or accessing protected methods/variables, you will need to build both Application Suite and your extension model. You will also need to create a deployable package that includes both models in order to deploy this functionality on a runtime environment. This is a temporary situation until the next release of the Microsoft Dynamics 365 for Finance and Operations application.

Capabilities

The following sections give more details about the capabilities of method wrapping and CoC.

Wrapping public and protected methods

Protected or public methods of classes, tables, or forms can be wrapped by using an extension class that augments that class, table, or form. The wrapper method must have the same signature as the base method.
  • When you augment form classes, only root-level methods can be wrapped. You can't wrap methods that are defined in nested classes.
  • Only methods that are defined in regular classes can be wrapped. Methods that are defined in extension classes can't be wrapped by augmenting the extension classes.

What about default parameters?

Methods that have default parameters can be wrapped by extension classes. However, the method signature in the wrapper method must not include the default value of the parameter.
For example, the following simple class has a method that has a default parameter.
class Person 
{
    Public void salute( str message = "Hi"){ }
}
In this case, the wrapper method must resemble the following example.
[ExtensionOf(classtr(Person))]
final class aPerson_Extension
{
    Public void salute( str message ){ }
}
In the aPerson_Extension extension class, notice that the salute method doesn't include the default value of the message parameter.

Wrapping instance and static methods

Instance and static methods can be wrapped by extension classes. If a static method is the target that will be wrapped, the method in the extension must be qualified by using the static keyword.
For example, we have the following A class.
class A 
{
    public static void aStaticMethod( int parameter1)
    {
    // …
    }
}
In this case, the wrapper method must resemble the following example.
[ExtensionOf(classstr(A)]
final class An_Extension
{
    public static void aStaticMethod( int parameter1)
    {
        Next aStaticMethod( 10 );
    }
}
Important
The ability to wrap static methods doesn't apply to forms. In X++, a form class isn't a new class, and can't be instantiated or referenced as a normal class. Static methods in forms don't have any semantics.

Wrapper methods must always call next

Wrapper methods in an extension class must always call next, so that the next method in the chain and, finally, the original implementation are always called. This restriction helps guarantee that every method in the chain contributes to the result.
In the current implementation of this restriction, the call to next must be in the first-level statements in the method body.
Here are some important rules:
  • Calls to next can't be done conditionally inside an if statement.
  • Calls to next can't be done in while, do-while, or for loop statements.
  • A next statement can't be preceded by a return statement.
  • Because logical expressions are optimized, calls to next can't occur in logical expressions. At runtime, the execution of the complete expression isn't guaranteed.
Note
The author of the original implementation of a method can explicitly allow wrapper methods to skip calling next. If the method you are wrapping is tagged with the [Replaceable] attribute, an extension class can wrap this method without calling the nextkeyword. Replaceable methods are methods that implement logic that can safely be "replaced" by custom implementation. This functionality is available with the release of Platform Update 11.

Wrapping a base method in an extension of a derived class

The following example shows how to wrap a base method in an extension of a derived class. For this example, the following class hierarchy is used.
class A
{
    public void salute(str message)
    {
        Info(message);
    }
}

class B extends A { }
class C extends A { }
Therefore, there is one base class, A. Two classes, B and C, are derived from A. We will augment or create an extension class of one of the derived classes (in this case, B), as shown here.
[Extensionof(classstr(B))]
final class aB_Extension
{
    public void salute(str message)
    {
        next salute( message );
        Info("B extension");
    }
}
Although the aB_Extension class is an extension of B, and B doesn't have a method definition for the salute method, you can wrap the salute method that is defined in the base class, A. Therefore, only instances of the B class will include the wrapping of the salutemethod. Instances of the A and C classes will never call the wrapper method that is defined in the extension of the B class.
This behavior becomes clearer if we implement a method that uses these three classes.
class ProgramTest 
{
    Public static void Main( Args _args)
    {
        var a = new A( );
        var b = new B( );
        var c = new C( );

        a.salute("Hi");
        b.salute("Hi");
        c.salute("Hi");
    }
}
For calls to a.salute(“Hi”) and c.salute(“Hi”), the Infolog shows only the message “Hi.” However, when b.salute(“Hi”) is called, the Infolog shows “Hi” followed by “B extension.”
By using this mechanism, you can wrap the original method only for specific derived classes.

Accessing protected members from extension classes

As of Platform update 9, you can access protected members from extension classes. These protected members include fields and methods. Note that this support isn't specific to wrapping methods but applies all the methods in the class extension. Therefore, class extensions are more powerful than they were before.

The Hookable attribute

If a method is explicitly marked as [Hookable(false)], the method can't be wrapped in an extension class. In the following example, anyMethod can't be wrapped in a class that augments anyClass1.
class anyClass1 
{
    [HookableAttribute(false)]
    public void anyMethod() {…}
}

Final methods and the Wrappable attribute

Public and protected methods that are marked as final can't be wrapped in extension classes. You can override this restriction by using the Wrappable attribute and setting the attribute parameter to true ([Wrappable(true)]). Similarly, to override the default capability for (non-final) public or protected methods, you can mark those methods as non-wrappable ([Wrappable(false)]).
In the following example, the doSomething method is explicitly marked as non-wrappable, even though it's a public method. The doSomethingElse method is explicitly marked as wrappable, even though it's a final method.
class anyClass2 
{
    [Wrappable(false)]
    public void  doSomething(str message) { …}

    [Wrappable(true)]
    final public void  doSomethingElse(str message){ …}
}

Restrictions on wrapper methods

The following sections describe restrictions on the use of CoC and method wrapping.

Kernel methods can't be wrapped

Kernel classes aren't X++ classes. Instead, they are classes that are defined in the kernel of the Microsoft Dynamics 365 Unified Operations platform. Even though extension classes are supported for kernel classes, method wrapping isn't supported for methods of kernel classes. In other words, if you want to wrap a method, the base method must be an X++ method.

X++ classes that are compiled by using Platform update 8 or earlier

The method wrapping feature requires specific functionality that is emitted by an X++ compiler that is part of Platform update 9 or later. Methods that are compiled by using earlier versions don't have the infrastructure to support this feature.

Nested class methods (forms) can't be wrapped

The concept of nested classes in X++ applies to forms for overriding data source methods and form control methods. Methods in nested classes can't be wrapped in class extensions.

Tooling

For the features that are described in this topic, the Microsoft Visual Studio X++ editor doesn't yet offer complete support for cross-references and Microsoft IntelliSense. We plan to make complete support available in Microsoft Dynamics 365 for Finance and Operations, Enterprise edition platform update 10.

Please check my other posts: https://rahulmsdax.blogspot.com/2018/12/coc-chain-of-command-or-method-wrapping.html
https://rahulmsdax.blogspot.com/2019/04/extensioncoc-class-for-dp-classes-in.html

What is the primary purpose of using a Solution in Microsoft Power Platform & ALM?

As organizations embrace low-code development with Microsoft Power Platform , it becomes essential to manage and govern apps, flows, and dat...