Wednesday, 26 November 2025

Import excel file data in batch processing

 





















Contract class

[

    DataContract,

    SysOperationContractProcessing(classStr(ModelsUIBuilder))

]

public class ModelsContract

{

    container storageResult;

 

    /// <summary>

    /// Parameter method which holds values of the packed variables from <c>FileUploadTemporaryStorageResult</c> class

    /// </summary>

    /// <param name = "_storageResult">Packed instance of <c>FileUploadTemporaryStorageResult</c> class</param>

    /// <returns>Container with packed values</returns>

    [DataMemberAttribute('StorageResult')]

    public container parmStorageResult(container _storageResult = storageResult)

    {

        storageResult = _storageResult;

        return storageResult;

    }

 

}

UI Builder class

/// <summary>

/// UI Builder class for models

/// </summary>

class ModelsUIBuilder  extends SysOperationUIBuilder

{

    #File

    #define.CommandButton("CommandButton")

    #define.FileUpload("FileUpload")

 

    private str availableTypes = #xlsx;

    private const str OkButtonName = #CommandButton;

    private const str FileUploadName = #FileUpload;

 

    ModelsContract        contract;

    public void postBuild()

    {

        DialogGroup                     dialogGroup;

        FormBuildControl                formBuildControl;

        FileUploadBuild                 dialogFileUpload;

 

        super();

 

        contract = this.dataContractObject();

 

        dialogGroup = dialog.addGroup("@RET1964");

        formBuildControl = dialog.formBuildDesign().control(dialogGroup.name());

 

        dialogFileUpload = formBuildControl.addControlEx(classstr(FileUpload), FileUploadName);

        dialogFileUpload.style(FileUploadStyle::MinimalWithFilename);

        dialogFileUpload.baseFileUploadStrategyClassName(classstr(FileUploadTemporaryStorageStrategy));

        dialogFileUpload.fileTypesAccepted(availableTypes);

        dialogFileUpload.fileNameLabel("@SYS308842");

    }

 

    /// <summary>

    /// Subscribes events to the dialog form

    /// </summary>

    /// <param name = "_formRun">The instance of the dialog form</param>

    private void dialogEventsSubscribe(FormRun _formRun)

    {

        FileUpload fileUpload = _formRun.control(_formRun.controlId(FileUploadName));

        fileUpload.notifyUploadCompleted += eventhandler(this.uploadCompleted);

        fileUpload.notifyUploadAttemptStarted += eventhandler(this.uploadStarted);

        _formRun.onClosing += eventhandler(this.dialogClosing);

    }

 

    /// <summary>

    /// Executes logic for unsubscribing the registered events on the form

    /// </summary>

    /// <param name = "sender">Formrun object</param>

    /// <param name = "e">Form event args</param>

    [SuppressBPWarningAttribute('BPParameterNotUsed', 'This is event parameter not required to use')]

    private void dialogClosing(xFormRun sender, FormEventArgs e)

    {

        this.dialogEventsUnsubscribe(sender as FormRun);

    }

 

    /// <summary>

    /// Unsubscribes events from the dialog form

    /// </summary>

    /// <param name = "_formRun">The instance of the dialog form</param>

    private void dialogEventsUnsubscribe(FormRun _formRun)

    {

        FileUpload fileUpload = _formRun.control(_formRun.controlId(FileUploadName));

        fileUpload.notifyUploadCompleted -= eventhandler(this.uploadCompleted);

        fileUpload.notifyUploadAttemptStarted -= eventhandler(this.uploadStarted);

        _formRun.onClosing -= eventhandler(this.dialogClosing);

    }

 

    /// <summary>

    /// Executes additional logic once the upload of the file is completed

    /// </summary>

    protected void uploadCompleted()

    {

        var formRun = this.dialog().dialogForm().formRun();

        FileUpload fileUpload = formRun.control(formRun.controlId(FileUploadName));

        FileUploadTemporaryStorageResult uploadResult = fileUpload.getFileUploadResult();

 

        if (uploadResult != null && uploadResult.getUploadStatus())

        {

            contract.parmStorageResult(uploadResult.pack());

        }

 

        this.setDialogOkButtonEnabled(formRun, true);

    }

 

    /// <summary>

    /// Additional logic which is executed once the upload of the file has started

    /// </summary>

    private void uploadStarted()

    {

        var formRun = this.dialog().dialogForm().formRun();

        this.setDialogOkButtonEnabled(formRun, false);

    }

 

    /// <summary>

    /// Enables/Disables the OK button of the dialog

    /// </summary>

    /// <param name = "_formRun">The instance of the dialog form</param>

    /// <param name = "_isEnabled">Should the OK button be enabled?</param>

    protected void setDialogOkButtonEnabled(FormRun _formRun, boolean _isEnabled)

    {

        FormControl okButtonControl = _formRun.control(_formRun.controlId(OkButtonName));

        if (okButtonControl)

        {

            okButtonControl.enabled(_isEnabled);

        }

    }

 

    /// <summary>

    /// Override of the <c>postRun</c> method in order to add events subscriptions

    /// </summary>

    public void postRun()

    {

        super();

 

        FormRun formRun = this.dialog().dialogForm().formRun();

        this.dialogEventsSubscribe(formRun);

 

        this.setDialogOkButtonEnabled(formRun, false);

    }

 

}


Controller class

/// <summary>

/// Controller class to the models

/// </summary>

public class ModelsController extends SysOperationServiceController

{

     /// <summary>

    /// Creates new instance of <c>ModelsController</c>

    /// </summary>

    /// <param name = "_mode">Execution mode</param>

    protected void new(SysOperationExecutionMode _mode = SysOperationExecutionMode::Synchronous)

    {

        super();

 

        this.parmClassName(classStr(ModelsService));

        this.parmMethodName(methodStr(ModelsService, processOperation));

        this.parmDialogCaption("Models");

        this.parmExecutionMode(_mode);

    }

 

    /// <summary>

    /// Constructor for the class and creates a new instance of the class

    /// </summary>

    /// <param name = "_mode">Execution mode</param>

    /// <returns>An instance of ModelsController class</returns>

    public static ModelsController construct(SysOperationExecutionMode _mode = SysOperationExecutionMode::Synchronous)

    {

        ModelsController controller = new  ModelsController(_mode);

 

        return controller;

    }

 

    /// <summary>

    /// Sets the caption of the job

    /// </summary>

    /// <returns>Caption of the job</returns>

    public ClassDescription caption()

    {

        return "Models";

    }

 

    /// <summary>

    /// Method which is run while calling the corresponding menu item

    /// </summary>

    /// <param name = "args">Arguments passed from the menu item</param>

    public static void main(Args args)

    {

        ModelsController controller = ModelsController::construct(SysOperationExecutionMode::Synchronous);

 

        controller.startOperation();

    }

 

}


Service class

using System.IO;

using OfficeOpenXml;

using OfficeOpenXml.ExcelPackage;

using OfficeOpenXml.ExcelRange;

 

/// <summary>

/// Service class to models

/// </summary>

public class ModelsService extends SysOperationServiceBase

{

    

    public void processOperation(odelsContract _contract)

    {

        System.IO.Stream                    stream;

       

        if (_contract.parmStorageResult() != conNull())

        {

            FileUploadTemporaryStorageResult fileUploadResult = new FileUploadTemporaryStorageResult();

            fileUploadResult.unpack(_contract.parmStorageResult());

 

            if (fileUploadResult != null && fileUploadResult.getUploadStatus())

            {

                stream = fileUploadResult.openResult();

 

                // If not in batch, call code to show progress bar

                if(!this.isExecutingInBatch())

                {

                    SysOperationSandbox::callStaticMethod(classNum(ModelsService),

                                                        staticMethodStr(ModelsService,processExcelData),

                                                        [stream], "Importing models", "OperationCompleted");

                }

                else

                {

                    ModelsService::processExcelData([stream]);

                }

               

            }

        }

 

        info("@SYS9265");

    }

 

   

    public static void processExcelData(container conStream)

    {

       

        str                                 make, model, modelDesc;

        LineNumber                          lineNum;

        int                                 numOfModelsDeleted;

        int                                 numOfModelsSkipped;

        boolean                             isValid;

        System.IO.Stream                    stream;

 

        [stream] = conStream;

 

        using (ExcelPackage package = new ExcelPackage(stream))

        {

            int rowCount, i;

 

            package.Load(stream);

            ExcelWorksheet worksheet = package.get_Workbook().get_Worksheets().get_Item(1);

            OfficeOpenXml.ExcelRange range = worksheet.Cells;

            rowCount = (worksheet.Dimension.End.Row + 1) - (worksheet.Dimension.Start.Row);

            lineNum = 0;

 

            if(rowCount == 0)

            {

                throw error("File uploaded doesn't have any data");

            }

            else if (rowCount == 1)

            {

                throw error("File uploaded either doesn't have a header record or no data records.");

            }

 

            setPrefix("Importing models");

 

            for (i = 2; i <= rowCount; i++)

            {

                try

                {

                    make        = '';

                    model       = '';

                    modelDesc   = '';

                    isValid     = true;

 

                    make        = range.get_Item(i, 1).Text;

                    model       = range.get_Item(i, 2).Text;

                    modelDesc   = range.get_Item(i, 3).Text;

 

                    if (make && model && modelDesc)

                    {

                        ---Business logic

                    }

                   

                }

                catch (Exception::Error)

                {

                    error("@RET433");

                }

            }

            info(strFmt("Number of records processed %1", rowCount-1));   

        }

    }

 

}

No comments:

Post a Comment