How to remove the duplicate objects in AOT Using X++

Scenario : Nags came across a requirement for duplicating the production instance.He followed the following steps
1. Setup a new instance and Copied the var.aod files from production instance and restored the DB with production DB.
2. After that he kept the application for compilation. When the compilation ends , he tries to synchronize the Data dictionary. But he was getting error during synchronization because some objects were duplicated in layers. e.g System will show two ItemId fields at table level.
Use the following code to delete the identical copy.
static void FindAndDeleteIdenticalObjects(Args _args)
{
    SysTreeNode comparable1, comparable2;
    TreeNode curLevelTreeNode, upperLevelTreeNode;
    UtilIdElements utilElements, joinUtilElements;
    ;
    while select UtilElements
    where UtilElements.utilLevel == UtilEntryLevel::var &&
    (
        UtilElements.recordType == UtilElementType::Form ||
        Utilelements.recordType == UtilElementType::Report ||
        Utilelements.recordType == UtilElementType::Table ||
        Utilelements.recordType == UtilElementType::Class ||
        Utilelements.recordType == UtilElementType::Enum ||
        Utilelements.recordType == UtilElementType::ExtendedType
    )
    {
        //Should use join if for a normal table, but not applicable for UtilElements
        //Performance hit if use exists join
        select firstonly recid from joinUtilElements
        where joinUtilElements.utilLevel != UtilElements.utilLevel &&
        joinUtilElements.name == UtilElements.name &&
        joinUtilElements.recordType == UtilElements.recordType;
        if (joinUtilElements.RecId)
        {
            //Thanks for Jim Shepherd here
            curLevelTreeNode = SysTreeNode::findNodeInLayer(UtilElements.recordType, UtilElements.name, UtilElements.parentId, UtilElements.utilLevel);
            upperLevelTreeNode = SysTreeNode::getLayeredNode(curLevelTreenode, 1);
            comparable1 = SysTreeNode::newTreeNode(curLevelTreeNode);
            comparable2 = SysTreeNode::newTreeNode(upperLevelTreeNode);
            if (SysCompare::silentCompare(comparable1, comparable2))
            {
                info(strFmt("Element name: %1, Element type: %2", UtilElements.name, enum2str(UtilElements.recordType)));
                //Remove the node
                curLevelTreeNode.AOTdelete();
            }
        }
    }
}

1 comment: