AX 2012: Creating parm methods automatically

It is often a tedious task to create parm methods for a class having many data members. Use the following AOT job to create parm methods automatically instantaneously! All you need to do is to declare data members in the class declaration. Make sure the data type and variable is separated by a single space character. Then replace the name of your class in the job script and finally run job! You can download the xpo file below:

static void createParmMethod(Args _args)
{
    #AOT

    ClassName className = classStr(MyClass);

    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 = ' (?[a-zA-Z0-9_]+) (?[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();
}

Download the XPO:


Read the full post here by Sasha Nazarov.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s