Sunday, May 23, 2010

Random and Sequence number Generation in AX

Ax provides us with two classes for this purpose. I am just giving an example on how to create random numbers and numbers in sequence by using them.

Random numbers:
static void RandomNumbers(Args _args)
{
RandomGenerate RandomRange = new RandomGenerate();
Random Random = new Random();
;
//This generates random numbers within the given range
info(int2Str(RandomRange.randomInt(20,100)));

//This generates random numbers
info(int2Str(Random.nextInt()));
}

Numbers generated can be repeated. So you should make some explicit validations if unique number is required.

Sequence numbers:

static void Sequence(Args _args)
{
Sequence Seq = new Sequence("Sequence",8,100,500,1);
// Displays the current value of the object
print Seq.currval();
while(1)
{
print Seq.nextval(10);
pause;
}
}
Sequence class takes the following parameters:
SequenceName ('Sequence') = It can be any string.
Identification No ('8') = Identification number for the sequence.
Initial Value ('100') = Initial value.
Maximum value ('500') = Maximum value.
Flag('1') = It indicates whether the cycle should repeat after maximum value.

The method “nextVal” takes the value to be incremented for next number as parameter.

Execute a string expression in X++

Sometimes we need to execute a string expression in X++. This may be the case when we need to take the full expression as input from the user and then to execute it. To do this we need to create a method which basically returns the string expression. Then pass this method runBuf() for execution as shown,

static void executeExpression(Args _args)
{
str expr = '2 * (16/8)';
str method = @'real calculate(){return ' + expr + ';}';
real result;
;
result = runBuf(method);
info (strfmt("Calculation result is %1", result));
}
This job will display an infolog of

Calculation result is 4