Monday, March 8, 2010

Simple x++ Calculator

May be you know the AX GUI calculator of the FormRealControl. If not, I will explain in a short way: If you enter a proper calculation expression in a real field (picture a) and commit the input expression will be calculated and the result set to the field (picture b).

picture a:

picture b:

So I found this functionality can also be used trough x++. The result was a static method which can evaluate an expression to be calculated.

That's the code behind:
/// ;
/// Calculates a simple math task
/// ;
/// ;
/// A simple mathematic expression. 
/// +-/* operators and brackets can be used
/// 
/// 
/// The calculated result. If the expression
/// does not match the expected format, 
/// zero is returned.
/// ;
/// ;
/// Uses functionality from 
/// FormRealControl, 
/// therefore client execution 
/// is required.
/// ;
static client real calcExpression(str _expression)
{
    SysFormRun formRun;
    Args args = new Args();
    FormBuildControl buildCtrl;
    FormRealControl realCtrl;
    
    ;
    args.name(formstr(Dialog));
    formRun = classFactory.formRunClass(args);
    
    buildCtrl = formRun.form().design()
        .addControl(FormControlType::Real, 
        classstr(FormRealControl));
    formRun.init();
    realCtrl = formRun.design()
        .control(buildCtrl.id());
    realCtrl.pasteText(_expression);
    return realCtrl.realValue();
}
And that's how we use it:
info(strfmt('%1', 
    MyClass::calcExpression('5+(5*2)')));

Keep in mind, this function inherits all limits which the FormRealControl calculation feature owns.

2 comments:

  1. You can also use the function runBuf() which supports full X++ syntax.

    http://msdn.microsoft.com/en-us/library/aa656300.aspx

    /Bjørn

    ReplyDelete
  2. Of course the runBuf function can evaluate a calculation too, but say the user can define the calculation expression in a text field; we won't give them access to the entire X++ functionality, won't we?

    What I mean is, you don't need any validation of the expression when use the RealFormControl's feature.

    ReplyDelete