Basic calculator using runbuf() in Dynamics AX

Good evening,
If you ever need to build a mathematical calculator in Dynamics AX, you might consider using runbuf() as basis for the code. The only critical considerations are to make sure that an attacker cannot use the calculator to execute code other than mathematical functions.
Here’s a quick example of what the calc() code for the calculator might look like (in a job):
public static void calcExample(Args _args)
{
    real ret;
    str formula = "(30+20)*(2)"; //user might type this into a textbox on a form
    ;
    ret = runbuf(
        strfmt(
            "real calc()\n"
            +"{\n"
            +"    ;\n"
            +"    return %1;\n"
            +"}\n", formula));

    info(SysQuery::value(ret));
}

An added advantage of using runbuf() this way, is that it gives the user the ability to use mathematical functions defined in AX like abs() acos(), asin(), atan(), etc.
This entry was posted in Dynamics Ax 4.0x. Bookmark the permalink.