Tuesday, January 17, 2023

Import CSV file using x++ in D365FO

 In this post we can see how to import CSV file using x++. I have done by using RunBase batch. Because user will upload more data and he want to run in batch.

Dialog:


Using RunBase Batch

class TerminationBatch extends RunBaseBatch
{
    Filename        filename;
    dialog          dialog;

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

    client server static ClassDescription description()
    {
        return 'Upload CSV file';
    }

    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;
       
        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
            {

                Id    = conPeek(currentLine, 1);
                Date  = conPeek(currentLine, 2);
				// Remaining fields             
            }
        
            catch (Exception::Error)
            {
                Throw (Exception::Error);
            }
        }
        info('Success');
    }

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

}


Using Job.

        AsciiStreamIo                                   file;
        Array                                           fileLines;
        FileUploadTemporaryStorageResult                fileUpload;
        fileUpload = File::GetFileFromUser() as FileUploadTemporaryStorageResult;
        file = AsciiStreamIo::constructForRead(fileUpload.openResult());

        if (file)
        {
            if (file.status())
            {
                throw error("@SYS52680");
            }

            file.inFieldDelimiter(',');
            file.inRecordDelimiter('\r\n');
        }

        container record;
        while (!file.status())
        {
            record = file.read();
            if (conLen(record))
            {
                info(strFmt("%1 - %2",conPeek(record,1),conPeek(record,2)));
            }
        }

Keep Daxing!! 

Friday, January 13, 2023

Modified method is not triggering for Multi Select control in form Level in D365FO.

Hello everyone, I have received a requirement to add a multi-select control at the form level. However, after adding it, the Modified method is not triggering. 

I have added the control to the dialog form.

 

As per user selection I need to showcase those fields.


         To display specific fields based on user selection, I plan to write the code in the control's Modified event. However, the system is not triggering that method. To achieve this, I have followed the process below:


Lookup method in the form control.

public void lookup()
{
    MultiSelect multiSelectGrid = MultiSelect ::construct(Temp_Genders, Temp_Genders);

    Query query = new Query();
    QueryBuildDataSource queryBuildDataSource;
    queryBuildDataSource = query.addDataSource(tableNum(Temp));// My Table
    queryBuildDataSource.addSelectionField(fieldNum(Temp, Genders));

    multiSelectGrid.parmQuery(query);
    multiSelectGrid.parmCallingControl(this);
    multiSelectGrid.run();
}


  • For a multi-select lookup, the 'SysLookupMultiSelectGrid' class needs to be used. 
  • When the user selects values in the lookup, the 'SetSelected' method is triggered.
  •  To achieve this, I have created a new class, extending from 'SysLookupMultiSelectGrid,' and overridden the necessary methods.

class MultiSelect extends SysLookupMultiSelectGrid
{
    #Characters
    public void setSelected()
    {
        dictfield          dictField;
        Common             currentDSRecord;
        FormDataSource     formdatasource;
        container          con = this.selectedStr;
        callingControlId.text(SysOperationHelper::convertMultiSelectedValueString(selectedId));

        formdatasource = callingControlId.dataSourceObject();
      
        FormRun  FormRunLoc= formdatasource.formRun();

        // My custom code
        if (formHasMethod(FormRunLoc,  identifierStr(visibilityValidation)))
        {
            FormRunLoc.visibilityValidation(con);
        }

        if(formdatasource && callingControlStr.dataField())
        {
            dictfield = new dictfield(formdatasource.table(),callingControlStr.dataField());
            currentDSRecord = formdatasource.cursor();
            currentDSRecord.(dictfield.id()) = currentDSRecord.(dictfield.id()) 
                            + SysOperationHelper::convertMultiSelectedValueString(selectedStr);
            callingControlStr.update();
        }
        else
        {
            callingControlStr.text(SysOperationHelper::convertMultiSelectedValueString(selectedStr));
        }
    }

    public static MultiSelect construct(FormControl ctrlId, FormControl ctrlStr)
    {
        MultiSelect lookupMS = new MultiSelect ();

        lookupMS.parmCallingControlId(_ctrlId);
        lookupMS.parmCallingControlStr(_ctrlStr);

        return lookupMS;
    }
}


From the above code, I am triggering the form method. That code you can find below.

Public TestForm extend FormRun
{
    public void visibilityValidation()
    {
        boolean     isMale, isFemale, isOthers;

	isMale   = conFind(_con, 'Male');
	isFemale = conFind(_con, 'Female');
	isOthers = conFind(_con, 'Others');
		
	if (conFind(_con, 'Both'))
	{
	    isMale = true;
	    isFemale = true;
	}

	Temp_Male.visible(isMale);
	Temp_Female.visible(isFemale);
	Temp_Others.visible(isOthers);
    }
}

If you have used "SysLookupMultiSelectCtrl" class. You can follow the above process.


Thank you, Yasin, For your support. 

Keep Daxing!!