Code code to generate code in Dynamics AX
Good morning,
The following job will create a new static method on the SalesLine table at runtime. Use it as a tutorial for TreeNodes' AOTadd(), AOTsetSource(), AOTcompile() and AOTfindChild() methods.
Note that access to such code should be restricted through security keys, namely the 'SysDevelopment' key since this code definitely uses a dangerous API.
public static void createMethodTest(Args _args)
{
#AOT
#define.myNewStaticMethod('myNewStaticMethod')
#define.methods('methods')
TreeNode parentNode;
TreeNode methodNode;
MemberFunction subMethodNode;
SysDictTable sysDictTable = new SysDictTable(tablenum(SalesLine));
Source source = "public static void myNewStaticMethod()/n"
+ "{/n"
+ " ;/n"
+ " info(/"test/");/n"
+ "}/n";
;
if (hasSecuritykeyAccess(
securitykeynum(SysDevelopment), AccessType::Delete))
{
parentNode = TreeNode::findNode(#TablesPath+'//'+sysDictTable.name());
{
#AOT
#define.myNewStaticMethod('myNewStaticMethod')
#define.methods('methods')
TreeNode parentNode;
TreeNode methodNode;
MemberFunction subMethodNode;
SysDictTable sysDictTable = new SysDictTable(tablenum(SalesLine));
Source source = "public static void myNewStaticMethod()/n"
+ "{/n"
+ " ;/n"
+ " info(/"test/");/n"
+ "}/n";
;
if (hasSecuritykeyAccess(
securitykeynum(SysDevelopment), AccessType::Delete))
{
parentNode = TreeNode::findNode(#TablesPath+'//'+sysDictTable.name());
if (parentNode)
{
methodNode = parentNode.AOTfindChild(#methods);
{
methodNode = parentNode.AOTfindChild(#methods);
subMethodNode = methodNode.AOTfindChild(#myNewStaticMethod);
if (!subMethodNode)
{
subMethodNode = methodNode.AOTadd(#myNewStaticMethod);
}
subMethodNode.AOTsetSource(source, true); //true sets 'static'
if (!subMethodNode)
{
subMethodNode = methodNode.AOTadd(#myNewStaticMethod);
}
subMethodNode.AOTsetSource(source, true); //true sets 'static'
parentNode.AOTcompile();
}
}
}
}
}
}
Et voila! Right after execution, you will have a new static method in the AOT under Data dictionary/Tables/SalesLine/methods/:
public static void myNewStaticMethod()
{
;
info("test");
}
;
info("test");
}