Friday, April 26, 2024

create DMF import data project dynamically and map using XML

internal final class DMFImport
{
    /// <summary>
    /// Class entry point. The system will call this method when a designated menu 
    /// is selected or when execution starts and this class is set as the startup class.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
        str fileExtWithoutDot;
        str contentType;
        str fileId;
        guid fileGuid = newGuid();
        DMFDefinitionGroup  definitionGroup;
        DMFDefinitionGroupEntity    definitionGroupEntityTable;
        
        //Creates DMF project
        str _defintionGroupName = "Test8";
        ttsbegin;
        definitionGroup.initValue();
        definitionGroup.DefinitionGroupName = _defintionGroupName;
        definitionGroup.OperationType = DMFOperationType::Import;
        definitionGroup.insert();
        ttscommit;
        
        fileExtWithoutDot = DMFDataSource::getFormatFileExtension('XML-Element');
        contentType     = strFmt('application/%1', fileExtWithoutDot);

        DMFEntity DMFEntity;// = DMFEntity::find("Customer groups");
        select firstonly dmfEntity
            order by dmfEntity.EntityName asc
                where dmfEntity.targetEntity == "CUSTCUSTOMERGROUPENTITY";;

       // str _entityName = "CUSTCUSTOMERGROUPENTITY";
        str _entityName = DMFEntity.EntityName;
        
        str _fileName = "Test8";

        fileId = guid2str(fileGuid);
        str _fileBase64 = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48RG9jdW1lbnQ+PENVU1RDVVNUT01FUkdST1VQRU5USVRZPjxDTEVBUklOR1BFUklPRFBBWU1FTlRURVJNTkFNRT48L0NMRUFSSU5HUEVSSU9EUEFZTUVOVFRFUk1OQU1FPjxDVVNUT01FUkFDQ09VTlROVU1CRVJTRVFVRU5DRT48L0NVU1RPTUVSQUNDT1VOVE5VTUJFUlNFUVVFTkNFPjxDVVNUT01FUkdST1VQSUQ+RXhEZWJCUnVwdDwvQ1VTVE9NRVJHUk9VUElEPjxERUZBVUxURElNRU5TSU9ORElTUExBWVZBTFVFPjwvREVGQVVMVERJTUVOU0lPTkRJU1BMQVlWQUxVRT48REVTQ1JJUFRJT04+QWNjb3VudHMgcmVjZWl2YWJsZSBleHRlcm5hbCAtIGJhZCBkZWJ0PC9ERVNDUklQVElPTj48SVNTQUxFU1RBWElOQ0xVREVESU5QUklDRT5ObzwvSVNTQUxFU1RBWElOQ0xVREVESU5QUklDRT48UEFZTUVOVFRFUk1JRD48L1BBWU1FTlRURVJNSUQ+PFRBWEdST1VQSUQ+PC9UQVhHUk9VUElEPjxXUklURU9GRlJFQVNPTj48L1dSSVRFT0ZGUkVBU09OPjwvQ1VTVENVU1RPTUVSR1JPVVBFTlRJVFk+PC9Eb2N1bWVudD4=";
       
        //Creates a file from Base64
        System.Byte[] reportBytes = System.Convert::FromBase64String(_fileBase64);
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(reportBytes);

        FileUploadTemporaryStorageStrategy fileUploadStrategy = new FileUploadTemporaryStorageStrategy();
        FileUploadTemporaryStorageResult fileUploadResult = fileUploadStrategy.uploadFile(memoryStream, _fileName,contentType);

        //Adds the entity and file to the DMF Project
        ttsbegin;
        definitionGroupEntityTable.initValue();
        definitionGroupEntityTable.DefinitionGroup = _defintionGroupName;
        definitionGroupEntityTable.Entity = _entityName;
        definitionGroupEntityTable.Source = 'XML-Element';
        definitionGroupEntityTable.SampleFilePath = fileUploadResult.getFileId();
        definitionGroupEntityTable.EntityXMLName = DMFEntity.TargetEntity;

        definitionGroupEntityTable.RunInsertLogic = NoYes::Yes;
        definitionGroupEntityTable.RunValidateWrite = NoYes::Yes;
        DIS_DMFImport::GenerateAndValidateMapping(definitionGroupEntityTable);
        definitionGroupEntityTable.insert();
        ttscommit;

        DMFExecutionId  executionId = DMFUtil::setupNewExecution(_defintionGroupName);
        DMFDefinitionGroupExecution execution = DMFDefinitionGroupExecution::find(_defintionGroupName, definitionGroupEntityTable.Entity,executionId, true);

        //execution.DataProjectId = journalId;
        execution.FilePath = fileId;
        execution.update();

        //DMFQuickImportExport::doPGImport(_defintionGroupName, executionId);
    }

    /// <summary>
    /// Generates mapping for a definition group entity.
    /// </summary>
    /// <param name = "definitionGroupEntity">The definition group entity to generate mapping for.</param>
    public static void GenerateAndValidateMapping(DMFDefinitionGroupEntity definitionGroupEntity)
    {
        // Generate the mapping
        DMFXmlGeneration::generateMappingV2(definitionGroupEntity, '', true, true, false);

        // Validate generated mapping
        DMFQuickImportExport::validateXML(definitionGroupEntity.Source,
                definitionGroupEntity.SampleFilePath,
                definitionGroupEntity.Entity,
                definitionGroupEntity);
    }

}

Tuesday, April 23, 2024

Sysoperation framework with Aot query

public class UpdatePriceFormulaIdOnItemsService__Custom extends SysOperationServiceBase
{
    #OCCRetrycount
    public void processOperation(UpdatePriceFormulaIdOnItemsContract__Custom _contract)
    {
        Query               orderQuery;

        orderQuery      = _contract.getQuery();
        container       compCon = str2con(_contract.parmCompany(), SysAppUtilities__Custom::semiColon);
        QueryRun    queryRun = new QueryRun(orderQuery);
        while (queryRun.Next())
        {
            InventTable inventTable = queryRun.get(tableNum(InventTable));
            try
            {
                PriceFormulaId__Custom  priceFormulaIdMaster = this.getPriceFormulaId(inventTable);

                //DSSE
                if (inventTable &&
                    inventTable.PriceFormulaIdMaster__Custom != priceFormulaIdMaster)
                {
                    ttsbegin;
                    inventTable.selectForUpdate(true);
                    inventTable.PriceFormulaIdMaster__Custom = priceFormulaIdMaster;
                    inventTable.PriceFormulaId__Custom = priceFormulaIdMaster;
                    inventTable.doUpdate();
                    ttscommit;
                }

                for (int i=1; i<=conLen(compCon); i++)
                {
                    DataAreaId  company = conPeek(compCon, i);
                    changecompany(company)
                    {
                        InventTable inventTableSales = InventTable::find(inventTable.ItemId);
                        PriceFormulaId__Custom  priceFormulaId = this.getPriceFormulaId(inventTableSales);

                        if (inventTableSales &&
                            inventTableSales.PriceFormulaId__Custom != priceFormulaId)
                        {
                            ttsbegin;
                            inventTableSales.selectForUpdate(true);
                            inventTableSales.PriceFormulaIdMaster__Custom = priceFormulaIdMaster;
                            inventTableSales.PriceFormulaId__Custom = priceFormulaId;
                            inventTableSales.doUpdate();
                            ttscommit;
                        }
                    }
                }

                info(strfmt("@_CustomtITServices:SucessUpdateItem", inventTable.ItemId));
            }
            catch (Exception::Deadlock)
            {
                retry;
            }
            catch (Exception::UpdateConflict)
            {
                if (appl.ttsLevel() == 0)
                {
                    if (xSession::currentRetryCount() >= #RetryNum)
                    {
                        warning(strFmt("@_CustomtITServices:FaliedUpdateItem", inventTable.ItemId));
                        continue;
                    }
                    else
                    {
                        retry;
                    }
                }
                else
                {
                    warning(strFmt("@_CustomtITServices:FaliedUpdateItem", inventTable.ItemId));
                    continue;
                }
            }
            catch (Exception::Error)
            {
                warning(strFmt("@_CustomtITServices:FaliedUpdateItem", inventTable.ItemId));
                continue;
            }
        }
    }

    public PriceFormulaId__Custom getPriceFormulaId(InventTable _inventTable)
    {
        DimensionValue      brandDim;
        EcoResCategoryId    ecoResCategoryId;
        container           catCon  = conNull();

        if (_inventTable)
        {
            brandDim            = _CustomtITServicesUtility__Custom::getDimension_CustomplayValue(_inventTable.DefaultDimension, SysAppUtilities__Custom::dimensionAttributeNameBrand);
            catCon              = _CustomtITServicesUtility__Custom::getProdCategories(_inventTable.ItemId);
        }

        ItemPriceFormula__Custom    itemPriceFormula;
        
        if (_inventTable.ItemId)
        {
            itemPriceFormula    = ItemPriceFormula__Custom::findByItem(_inventTable.ItemId);
        }
           
        if (!itemPriceFormula && catCon != conNull() && brandDim)
        {
            for (int i=1; i<=conLen(catCon); i++)
            {
                ecoResCategoryId    = EcoResCategory::find(conPeek(catCon, i)).RecId;
                itemPriceFormula    = ItemPriceFormula__Custom::findByCategoryBrand(ecoResCategoryId, brandDim);
                if (itemPriceFormula)
                {
                    break;
                }
            }
        }

        if (!itemPriceFormula && brandDim)
        {
            itemPriceFormula    = ItemPriceFormula__Custom::findByBrand(brandDim);
        }
        
        if (!itemPriceFormula && catCon != conNull())
        {
            for (int i=1; i<=conLen(catCon); i++)
            {
                ecoResCategoryId    = conPeek(catCon, i);
                itemPriceFormula    = ItemPriceFormula__Custom::findByCategory(ecoResCategoryId);
                if (itemPriceFormula)
                {
                    break;
                }
            }
        }

        return itemPriceFormula.PriceFormulaId;
    }

}
=====================
public class UpdatePriceFormulaIdOnItemsController__Custom extends SysOperationServiceController
{
    // <summary>
    /// Creates a new instance of <c>UpdateEndOfLifeOnItemsController__Custom</c> class.
    /// </summary>
    /// <param name = "_args">A controller arguments.</param>
    /// <returns>A instance of <c>SysOperationController</c> class.</returns>
    public static UpdatePriceFormulaIdOnItemsController__Custom construct(Args _args)
    {
        UpdatePriceFormulaIdOnItemsController__Custom controller = new UpdatePriceFormulaIdOnItemsController__Custom();
        controller.parmArgs(_args);

        return controller;
    }

    /// <summary>
    /// Instantiate controller.
    /// </summary>
    protected void new()
    {
        super(classStr(UpdatePriceFormulaIdOnItemsService__Custom), methodStr(UpdatePriceFormulaIdOnItemsService__Custom, processOperation));

        this.parmDialogCaption("@_CustomtITServices:UpdatePriceFormulaIdItem");
    }

    /// <summary>
    /// Runs the class with the specified arguments.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
        UpdatePriceFormulaIdOnItemsController__Custom controller = UpdatePriceFormulaIdOnItemsController__Custom::newFromArgs(_args);
        controller.parmExecutionMode(SysOperationExecutionMode::Synchronous);
        controller.startOperation();
    }

    /// <summary>
    /// Instantiate and initialize controller class.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    /// <returns>
    /// returns controller class.
    /// </returns>
    public static UpdatePriceFormulaIdOnItemsController__Custom newFromArgs(Args _args)
    {
        UpdatePriceFormulaIdOnItemsController__Custom controller = UpdatePriceFormulaIdOnItemsController__Custom::construct(_args);
        return controller;
    }

}
==================
[DataContractAttribute, SysOperationContractProcessingAttribute(ClassStr(UpdatePriceFormulaIdOnItemsUIbuilder__Custom))]
public class UpdatePriceFormulaIdOnItemsContract__Custom
{
    str     packedQuery;
    Str                     company;
    /// <summary>
    ///    Initialize query
    /// </summary>
    public void initQuery()
    {
        Query   newQuery;
        newQuery = new Query(queryStr(InventTable));
        this.setQuery(newQuery);
    }

    /// <summary>
    ///     Get/Set the packed query
    /// </summary>
    /// <param name = "_packedQuery">query</param>
    /// <returns>string</returns>
    [
    DataMemberAttribute,
    AifQueryTypeAttribute('_packedQuery', queryStr(InventTable))
    ]
    public str parmPackedQuery(str _packedQuery = packedQuery)
    {
        packedQuery = _packedQuery;

        return packedQuery;
    }

    /// <summary>
    ///     Get the query
    /// </summary>
    /// <returns>Query</returns>
    public Query getQuery()
    {
        return
        new Query(SysOperationHelper::base64Decode(packedQuery));
    }

    /// <summary>
    ///     Set the query
    /// </summary>
    /// <param name = "_query">query</param>
    public void setQuery(Query _query)
    {
        packedQuery = SysOperationHelper::base64Encode(_query.pack());
    }

    // <summary>
    /// Gets or sets the value of the datacontract parameter company.
    /// </summary>
    /// <param name="_company">
    /// The new value of the datacontract parameter company; optional.
    /// </param>
    /// <returns>
    ///  The current value of datacontract parameter company
    /// </returns>
    [
        DataMemberAttribute,
        SysOperationLabelAttribute(literalStr("@_CustomtITServices:Company")),
        SysOperation_CustomplayOrderAttribute("1")
    ]
    public Str parmCompany(Str _company = company)
    {
        company = _company;
        return company;
    }

}

Table browser URL in D365FO

Critical Thinking icon icon by Icons8