Thursday, August 10, 2023

DataEntity import Dynamic field mapping X++

using JSONTOXMLConvert;
Public class CommonDataEntityImportService
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name = "Entities"></param>
    /// <returns></returns>
    public CommonDataEntityImportResponseContract importData(Newtonsoft.Json.Linq.JObject    Entities)
    {
        // Define XML Document and its nodes
        XmlDocument     doc;
        XmlNodeList     xmlMainNodeList;
        XmlNodeList     xmlChildNodeList;
        XmlElement      nodeRoot;
        XmlElement      nodeParent;
        XMLParseError   xmlError;
        // Define temporary variables
        int i, j;
        str response;
        Set setResponsetext = new Set(Types::String);

        try
        {
            //passsing and converting JSOn to XML
            
            str xml = Utilities::ConvertToXML(Entities);

            doc = new XmlDocument();
            doc.loadXml(xml);

            // Verify XML Document Structure
            xmlError  = doc.parseError();
            if(xmlError && xmlError.errorCode() != 0)
            {
                throw error(strFmt("XML Error: %1", xmlError.reason()));
            }

            // Get the root element and its child nodes
            nodeRoot = doc.firstChild();
            xmlMainNodeList = nodeRoot.childNodes();

            //looping through all the Parent nodes
            for (i=0; i < xmlMainNodeList.length(); i++)
            {
                Common          common;
                SysDictTable    dictTable;
                SysDictField    dictField;
                str             responseText =  strMin();

                nodeParent          = xmlMainNodeList.item(i);
                xmlChildNodeList    = nodeParent.childNodes();
                str parentNodeName  = nodeParent.name();

                XmlElement  lineNumber;
                XmlElement  orderNumber;
                XmlElement  dataAreadid;

                switch (parentNodeName)
                {
                    case 'PurchaseOrderHeader':
                        dictTable           = new SysDictTable(tableName2Id(tableStr(PurchPurchaseOrderHeaderEntity)));
                        common              = dictTable.makeRecord();
                        orderNumber         = nodeParent.selectSingleNode(fieldStr(PurchPurchaseOrderHeaderEntity, PurchaseOrderNumber));
                        dataAreadid         = nodeParent.selectSingleNode(fieldStr(PurchPurchaseOrderHeaderEntity, DataAreaId));
                        responseText        = strFmt("Purchase order %1", orderNumber.text());

                        select forupdate common
                            where common.(fieldName2id(common.TableId, 'PurchaseOrderNumber')) == orderNumber.text() &&
                             common.(fieldName2id(common.TableId, 'DataAreaId')) == dataAreadid.text();

                        break;
                    case 'PurchaseOrderLinesV2':
                        dictTable           = new SysDictTable(tableName2Id(tableStr(PurchPurchaseOrderLineV2Entity)));
                        common              = dictTable.makeRecord();
                        lineNumber          = nodeParent.selectSingleNode(fieldStr(PurchPurchaseOrderLineV2Entity, LineNumber));
                        orderNumber         = nodeParent.selectSingleNode(fieldStr(PurchPurchaseOrderLineV2Entity, PurchaseOrderNumber));
                        dataAreadid         = nodeParent.selectSingleNode(fieldStr(PurchPurchaseOrderLineV2Entity, DataAreaId));
                        responseText        = strFmt("Purchase order %1", orderNumber.text());
                       
                        select forupdate common
                        where common.(fieldName2id(common.TableId, 'PurchaseOrderNumber')) == orderNumber.text() &&
                            common.(fieldName2id(common.TableId, 'LineNumber')) == str2Int64(lineNumber.text()) &&
                            common.(fieldName2id(common.TableId, 'DataAreaId')) == dataAreadid.text();

                        break;
                }
                
                //looping through all the child nodes
                for (j=0; j < xmlChildNodeList.length(); j++)
                {
                    XmlElement nodeChild = xmlChildNodeList.item(j);

                    str value  = nodeChild.text();

                    dictField = dictTable.fieldObject(fieldName2Id(dictTable.id(), nodeChild.name()));
        
                    if(dictField)
                    {
                        switch (dictField.baseType())
                        {
                            case Types::Int64 :
                                common.(fieldName2Id(common.TableId, nodeChild.name())) = str2Int64(value);
                                break;
                            case Types::Integer :
                                common.(fieldName2Id(common.TableId, nodeChild.name())) = str2Int(value);
                                break;
                            case Types::Date :
                                common.(fieldName2Id(common.TableId, nodeChild.name())) = str2Date(value,321);
                                break;
                            case Types::Real :
                                common.(fieldName2Id(common.TableId, nodeChild.name())) = str2Num(value);
                                break;
                            default :
                                common.(fieldName2Id(common.TableId, nodeChild.name())) = value;
                                break;
                        }
                    }
                
                }
                ttsbegin;
                if (common.RecId)
                {
                    common.update();
                    response = orderNumber.text();
                }
                else
                {
                    common.insert();
                    response = orderNumber.text();
                }
                ttscommit;

            }

            return this.formatResponseToJSON(response);
            
        }
        catch(Exception::CLRError)
        {
            throw Error("CLRError : DLL Error");
        }
        catch(Exception::Error)
        {
            throw Error("unknown Error");
        }
        catch(Exception::DuplicateKeyException)
        {
            throw Error("DuplicateKeyException: Record already exists");
        }
    }

    /// <summary>
    /// generate JSON response
    /// </summary>
    /// <param name = "_set"></param>
    /// <returns></returns>
    public HFGCommonDataEntityImportResponseContract formatResponseToJSON(PurchId _poNum)
    {
        HFGCommonDataEntityImportResponseContract responseContract = new HFGCommonDataEntityImportResponseContract();
        responseContract.parmResponse(_poNum);

        return responseContract;
    }

}

==============

response contarct
[DataContractAttribute]
class CommonDataEntityImportResponseContract
{
    PurchId  response;
    
    [DataMemberAttribute('PurchaseOrderNumber')]
    public PurchId parmResponse(PurchId _response = response)
    {
        response = _response;
        return response;
    }

}
========
JSON payload
{
    "Entities": {
        "PurchaseOrders": [
            {
                "PurchaseOrderHeader": [
                    {
                        "DataAreaId": "100",                        
                        "PurchaseOrderNumber": "6100001105",
                        "OrderVendorAccountNumber": "60000016",
                        "RequestedDeliveryDate": "2023-06-09",
                        "VendorOrderReference": "SO000609C",
                        "ReceivingWarehouseId": "DC01"
                    }
                ],
                "PurchaseOrderLinesV2": [
                    {
                        "DataAreaId": "100",   
                        "LineNumber": 6.00,                     
                        "ItemNumber": "44573054",
                        "ProductConfigurationId": "44573054C001",
                        "OrderedPurchaseQuantity": 1,
                        "RequestedDeliveryDate": "2023-06-09",
                        "ReceivingWarehouseId": "DC01",
                        "PurchasePrice": 4,
                        "PurchaseOrderNumber": "6100001105"
                    }
                ]
            }
        ]
    }
}

======
JSON to XML convesrion using C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Xml.Linq;

namespace JSONTOXMLConvert
{
    public class Utilities
    {
        public static string ConvertToXML(Newtonsoft.Json.Linq.JObject myJObject)
        {
            string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);
            //if an empty string is passed, return empty string without conversion
            if (string.IsNullOrEmpty(json))
                return string.Empty;
            //if invalid json is passed, throw error.
            ValidateJSON(json);
            //Convert Json to XML
            XDocument xmlDoc = JsonConvert.DeserializeXNode(json);
            return xmlDoc.ToString();
        }
        public static void ValidateJSON(string json)
        {
            try
            {
                var jsonObject = JObject.Parse(json);
            }
            catch (Exception ex)
            {
                throw new InvalidCastException("Provided json is not valid.", ex);
            }
        }
    }
}

No comments:

Post a Comment

Table browser URL in D365FO

Critical Thinking icon icon by Icons8