Thursday, July 26, 2012

Parm-methods generator script

It may be boring to manualy create parm-methods for each an every class member variable, although there is an editor script for that. By the way, there is a bug-o-feature in AX 2012 editor, which does not allow you to select anything but an EDT for the variable type.

This is a script that auto-generates parm-methods for a class, based on its class declaration:
static void createParmMethod(Args _args)
{
    #AOT
   
    ClassName className = classStr(MyClass);  // <---------------- Write your class name here
   
    TreeNode classDeclarationTreeNode;
    TreeNode classTreeNode;
    TreeNode parmMethodNode;
   
    Source classDeclaration;
   
    System.Text.RegularExpressions.MatchCollection mcVariables;
    System.Text.RegularExpressions.Match mVariable;
    int matchCount;
    int matchIdx;
   
    System.Text.RegularExpressions.GroupCollection gcVariableDeclaration;
    System.Text.RegularExpressions.Group gVariableDeclarationPart;
   
    str variableType;
    str variableName;
   
    str pattern = ' (?<VarType>[a-zA-Z0-9_]+)[ ]+(?<VarName>[a-zA-Z0-9_]+);';   
   
    Source parmMethodBody;
   
    classTreeNode = TreeNode::findNode(strFmt(@"%1\%2", #ClassesPath, className));
   
    classDeclarationTreeNode = TreeNode::findNode(
        strFmt(@"%1\%2\ClassDeclaration",
        #ClassesPath,
        className));
   
    classDeclaration = classDeclarationTreeNode.AOTgetSource();
   
    mcVariables = System.Text.RegularExpressions.Regex::Matches(
        classDeclaration,
        pattern,
        System.Text.RegularExpressions.RegexOptions::Singleline);

    matchCount = CLRInterop::getAnyTypeForObject(mcVariables.get_Count());   
   
    for (matchIdx = 0; matchIdx < matchCount; matchIdx++)
    {
        mVariable = mcVariables.get_Item(matchIdx);
        gcVariableDeclaration = mVariable.get_Groups();
       
        gVariableDeclarationPart = gcVariableDeclaration.get_Item('VarType');
        variableType = gVariableDeclarationPart.get_Value();
       
        gVariableDeclarationPart = gcVariableDeclaration.get_Item('VarName');
        variableName = gVariableDeclarationPart.get_Value();
       
        parmMethodBody = new xppSource().parmMethod(variableType, variableName);
       
        parmMethodNode = classTreeNode.AOTadd('method1');
        parmMethodNode.AOTsetSource(parmMethodBody);
        classTreeNode.AOTsave();
    }
   
    classTreeNode.AOTcompile();
}

2 comments:

  1. Very helpful snippet, thank you!

    Optionally, you can include multiple spaces, as is the case typically in our code to have multiple tabs between type and name.

    str pattern = ' (?[a-zA-Z0-9_]+)[\ ]+(?[a-zA-Z0-9_]+);';

    ReplyDelete