Wednesday 25 February 2015

Sort container and Array for Dynamics AX

Just a quick snippet for sorting container and Array object.

//Method to sort container
static container sortContainer(container _con)
{
    anytype     temp1;
    anytype     temp2;
    int         i;
    int         j;
    container   sortedCon;
    ;

    sortedCon = _con;

    // Sort the container
    for (i = 1; i <= conlen(sortedCon); i++)
    {
        for (j = i + 1; j <= conlen(sortedCon); j++)
        {
            temp1 = conpeek(sortedCon, j);
            temp2 = conpeek(sortedCon, i);

            if (temp1 < temp2)
            {
                sortedCon = condel(sortedCon, j, 1);
                sortedCon = conins(sortedCon, j, temp2);
                sortedCon = condel(sortedCon, i, 1);
                sortedCon = conins(sortedCon, i, temp1);
            }
        }
    }

    return sortedCon;
}

//Method to sort Array
static Array sortArray(Array _array)
{
    int         i;
    int         arrayCount = _array.lastIndex();
    container   con, sortedCon;

    //Switch from Array to container
    for(i = 1; i <= arrayCount; i++)
    {
        con = conIns(con, i, _array.value(i));
    }
    
    //Sort the container
    sortedCon = sortContainer(con);
    
    //Switch from container to Array
    for(i = 1; i <= conLen(sortedCon); i++)
    {
        _array.value(i, conPeek(sortedCon, i));
    }
    
    return _array;
}

Thursday 12 February 2015

Copy table buffer between two table with similar structure

Just a quick snippet for those who need it.
The standard buf2Buf() method works if the field Id is identical, but in case the field name is same but have different Id, the code snippet below does the job. It is modified from the buf2Buf() to cater to two tables with similar structure and field name but different field Id.

static void buf2BufByName(
    Common  _from,
    Common  _to
    )
{
    DictTable   dictTableFrom   = new DictTable(_from.TableId);
    DictTable   dictTableTo     = new DictTable(_to.TableId);
    DictField   dictFieldFrom;
    FieldId     fieldIdFrom     = dictTableFrom.fieldNext(0);
    FieldId     fieldIdTo
    ;

    while (fieldIdFrom && ! isSysId(fieldIdFrom))
    {
        dictFieldFrom   = new DictField(_from.TableId, fieldIdFrom);

        if(dictFieldFrom)
        {
            fieldIdTo = dictTableTo.fieldName2Id(dictFieldFrom.name());

            if(fieldIdTo)
                _to.(fieldIdTo) = _from.(fieldIdFrom);
        }

        fieldIdFrom = dictTableFrom.fieldNext(fieldIdFrom);
    }
}