Tuesday, January 17, 2023

Deserialize JSON file using Json Object In D365FO.

Deserialize JSON file using Json Object clss in D365FO.

Sample File :

{
    "Contract" : 
    {
	"CustomerId" : "123",
	"Name" 		 : "Test 123",
	"SalesOrders" : [
	{
	    "salesOrder" : "S123",
	    "SequenceNumber" : "S123456",
	    "SalesLines" : [
		{
		    "item"  : "Item123",
		    "qty"   : "1",
		    "price" : "33.01"
		},
		{
		    "item"  : "Item456",
		    "qty"   : "2",
		    "price" : "30.01"
		}
		]
	}
	],
	"Address" :
	{
	    "City" 	    : "Hyd",
	    "AddressLine"   : "KK"
	}
    }
}


Code :

if (jsonString)
{
	str  customerId, name;
	str  salesOrder;
	str  item, qty, price;

	Newtonsoft.Json.Linq.JObject  contractData    = Newtonsoft.Json.JsonConvert::DeserializeObject(jsonString);// main Json file
	Newtonsoft.Json.Linq.JObject  contractDataObj = contractData.GetValue('Contract');// 1st node

	customerId	= contractDataObj.GetValue('CustomerId') ? contractDataObj.GetValue('CustomerId').ToString() : '';//string value
	name		= contractDataObj.GetValue('Name') ? contractDataObj.GetValue('Name').ToString() : '';

	//Array
	Newtonsoft.Json.Linq.JArray  salesOrderArray = ComponentDataObj.GetValue('SalesOrders');
	
	for (int i = 0; i < salesOrderArray.Count; i++)
	{
		Newtonsoft.Json.Linq.JObject    salesOrderObj = salesOrderArray.get_item(i);//line by line

		salesOrder	   = salesOrderObj.GetValue('salesOrder') ? salesOrderObj.GetValue('salesOrder').ToString() : '';//string value
		SequenceNumber = salesOrderObj.GetValue('SequenceNumber') ? salesOrderObj.GetValue('SequenceNumber').ToString() : '';

		info (strFmt('salesOrder - %1,SequenceNumber -%2', salesOrder, SequenceNumber));

		// Array
		Newtonsoft.Json.Linq.JArray  salesLinesArray = assetInfoObj.GetValue('SalesLines');
		for (int j = 0; j < salesLinesArray.Count; j++)
		{
			Newtonsoft.Json.Linq.JObject    salesLinesObj = salesLinesArray.get_item(j);

			item = salesLinesObj.GetValue('item') ? salesLinesObj.GetValue('item').ToString() : '';
			qty = salesLinesObj.GetValue('qty') ? salesLinesObj.GetValue('qty').ToString() : '';
			price = salesLinesObj.GetValue('price') ? salesLinesObj.GetValue('price').ToString() : '';

			info (strFmt('item - %1',item));
		}	
	}		

		// Address - Node
		Newtonsoft.Json.Linq.JObject  addressObj = assetInfoObj.GetValue('Address');

		addressLine = addressObj.GetValue('AddressLine') ? addressObj.GetValue('AddressLine').ToString() : '';
		city        = addressObj.GetValue('City') ? addressObj.GetValue('City').ToString() : '';

		info (strFmt('City - %1,AddressLine -%2',city,addressLine));
}



Keep Daxing!!

How to terminate the worker using x++

 Today will see how to terminate the worker using x++ code. For this user will create the CSV file and he will upload the file while running the batch.


Dialog:



Code :


class TerminationBatch extends RunBaseBatch
{
    Filename        ItemFileName;
    Filename        filename;
    DialogField     dialogFilename;
    dialog          dialog;

    #define.CurrentVersion(1)
    #define.Version1(1)
    #localmacro.CurrentList
        fileName
    #endmacro

    client server static ClassDescription description()
    {
        return 'Terminate multiple workers';
    }

    protected boolean canRunInNewSession()
    {
        return false;
    }


    public Object dialog()
    {
        DialogGroup         dialogGroup;
        FormBuildControl    formBuildControl;
        FileUploadBuild     dialogFileUpload;
       // Set              enumSet = new Set(Types::Enum);
                
        dialog              = super();
        dialogGroup         = dialog.addGroup('File picker');
        formBuildControl    = dialog.formBuildDesign().control(dialogGroup.name());
        
        dialogFileUpload = formBuildControl.addControlEx(classstr(FileUpload), filename);
        dialogFileUpload.style(FileUploadStyle::MinimalWithFilename);
        dialogFileUpload.baseFileUploadStrategyClassName(classstr(FileUploadTemporaryStorageStrategy));
        dialogFileUpload.fileTypesAccepted('.csv');
        dialogFileUpload.fileNameLabel('Select worker data file');
    
        return dialog;
    }

    static void main(Args _args)
    {
        TerminationBatch objClass = new TerminationBatch();

        if (objClass.prompt())
        {
            objClass.runOperation();
        }
    }

    public void run()
    {
        #File
        container                           currentLine;
        CommaTextStreamIo                   localStream;
        str                                 textFile;
        FromTime                            timeConsumedStartTime;
        ToTime                              timeConsumedEndTime;
        int                                 timeConsumedInMin;
        HcmPersonnelNumberId                hcmPersonnelNumberId;
        HcmWorker                           hcmWorker;
        boolean                             ret = true;
        HcmReasonCodeRecId                  reasonCodeRecId;
        HcmReasonCodeId                     reasonCodeId;
        TransDate                           lastDate, terminationDate;
        TimeOfDay                           toTime;
        HcmEmploymentLastWorkedDateTime     localLastDayWorked;
        HcmEmploymentTransitionDateTime     localTerminationDate;
        HcmEmploymentLastWorkedDateTime     localRetirementDate;
        int i;
       
        FileUpload fileUploadControl = this.getFormControl(dialog, filename);
        
        FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult();

        if (fileUploadResult != null && fileUploadResult.getUploadStatus())
        {
            textFile = fileUploadResult.getDownloadUrl();
        }
        
        localStream = CommaTextStreamIo::constructForRead(File::UseFileFromURL(textFile));
       
          
        if (localStream.status() != IO_Status::Ok)
        {
            throw error(strfmt('Is not possible to open the file. Error %1',enum2str(localStream.status())));
        }
    
        localStream.inFieldDelimiter(',');
        while (localStream.status() ==  IO_Status::Ok)
        {
            currentLine = localStream.read();

            if (!currentLine)
            {
                break;
            }
            try
            {
                timeConsumedStartTime = timeNow();
               // timeConsumedStartTime = DateTimeUtil::getUserPreferredTimeZone();


                hcmPersonnelNumberId    = conPeek(currentLine, 1);
                lastDate                = conPeek(currentLine, 2);
                terminationDate         = conPeek(currentLine, 3);
                reasonCodeId            = conPeek(currentLine, 4);

                toTime      = str2time('23:59:59');
                localLastDayWorked      = DateTimeUtil::newDateTime(lastDate, toTime);
                localTerminationDate    = DateTimeUtil::newDateTime(terminationDate, toTime);

                hcmWorker       = HcmWorker::findByPersonnelNumber(hcmPersonnelNumberId);
                reasonCodeRecId = HcmReasonCode::findByReasonCode(reasonCodeId).RecId;

                ret = HcmWorkerTransition::newTerminateHcmWorker(hcmWorker.RecId,
                                                                    localTerminationDate,
                                                                    localRetirementDate,
                                                                    reasonCodeRecId,
                                                                    localLastDayWorked,
                                                                    false);

                if (ret)
                {
                    i++;
                }

                timeConsumedEndTime = timeNow();
               // timeConsumedEndTime = DateTimeUtil::getUserPreferredTimeZone();

                timeConsumedInMin = str2int(Global::timeConsumed(timeConsumedStartTime, timeConsumedEndTime));

            }
        
            catch (Exception::Error)
            {
                Throw (Exception::Error);
            }
        }
        info(strFmt('Successfully terminated workers: %1', i));
        info(strFmt('It took %1 minutes to update the records', timeConsumedInMin / 60));
    }


    protected FormControl getFormControl(DialogRunbase dialog, str controlName)
    {
        return dialog.formRun().control(_dialog.formRun().controlId( controlName));
    }

}



Keep Daxing!!