Skip to main content

AX 2012: Reading files from directory through X++

Following code can be used to read files from the specified path. With this example, I am reading a CSV files from a directory.

Class declaration

class readFilesFromDirectory extends RunBase

{
    FilePath            filePath;
    Filename            filename;
    CommaTextIo         fileIO;
    Set                 fileSet;
    CommaIo             commaIo;
    str                 currentFile;
    container           lineCon;
    #File
    #AviFiles
}

main method

Public static void main(Args _args)

{
    readFilesFromDirectory  readFiles = readFilesFromDirectory::construct();
    readFiles.readFilesFromDirtecory();
}

Construct


Public static readFilesFromDirectory construct()

{
    return new readFilesFromDirectory();
}

readFileFromDirectory method


private void readFilesFromDirtecory()

{
    SetEnumerator           sE;
    int                     row = 1;
    filePath = @"C:\Temp\FilesToRead";
    this.getFiles();
    sE = fileSet.getEnumerator();
    while (sE.moveNext()) // loop through all files
    {
        filename = sE.current();
        this.openFile();
        while(this.readLine()) // loop through all lines from current file
        {
            this.processRow(row, lineCon);
            row++;
        }
    }
}

getFiles method


private void getFiles()
{
    System.String[]                 files;
    System.Collections.IEnumerator  enumerator;
    str file;
    try
    {
        fileSet = new Set(Types::Container);
        files = System.IO.Directory::GetFiles(filePath, '*.csv');
        enumerator = files.GetEnumerator();
        while (enumerator.MoveNext())
        {
            file = enumerator.get_Current();
            fileSet.add([file]);
        }
    }
    catch (Exception::Internal)
    {
        this.processCLRErrorException();
    }
    catch (Exception::CLRError)
    {
        this.processCLRErrorException();
    }
}

openFile method


private void openFile()

{
    FileIOPermission fileIOPermission;
    fileIOPermission = new FileIOPermission(filename, #io_read);
    fileIOPermission.assert();
    commaIo = new CommaIo(filename, #io_read);
    if (commaIo && commaIo.status() == IO_Status::Ok)
    {
        commaIo.inRecordDelimiter(#delimiterCRLF);
    }
    else
    {
        throw error(strFmt("Error when opening file %1", filename));
    }
}

readLine method

private boolean readLine()

{
    boolean readLine;
    if (commaIo && commaIo.status() == IO_Status::Ok)
    {
        lineCon = commaIo.read();
        readLine = lineCon != conNull();
    }
    else
    {
        lineCon = conNull();
        readLine = false;
    }
    return readLine;
}

processRow method

private void processRow(int _rowIdx, container  _row)

{
    //conpeek(_row, 1);
    //conpeek(_row, 2);
    //conpeek(_row, 3);
    //conpeek(_row, 4);
    //conpeek(_row, 5);
    //conpeek(_row, 6);
    //conpeek(_row, 7);
    //conpeek(_row, 8);
    //conpeek(_row, 9);
    //conpeek(_row, 10);
}

processCLRErrorException method
private void processCLRErrorException(
    boolean _throw = true
    )
{
    str strError;
    CLRObject exc;
    CLRObject innerExc;
    CLRObject clrExcMessage;
    exc = CLRInterop::getLastException();
    if (exc)
    {
        clrExcMessage = exc.get_Message();
        innerExc = exc.get_InnerException();
        while (innerExc != null)
        {
            clrExcMessage = innerExc.get_Message();
            innerExc = innerExc.get_InnerException();
        }
        strError = CLRInterop::getAnyTypeForObject(clrExcMessage);
        error(strError);
        if (_throw)
        {
            throw error("Update has been cancelled");
        }
    }
}


Comments

Popular posts from this blog

The Dual Write implementation - Part 1 - Understand and Setup

What is Dual-write? Tightly couples – complete at one transaction level Near real time Bi-directional Master data and business documents – Customer records you are creating and modifying and at this document we are talking about sales orders or quotes and invoice. Master data could be reference data e.g. customer groups and tax information Why Dual-write and why not Data Integrator? Data Integrator is Manual or Scheduled One directional Now, Let's deep dive and understand what is required for Dual-write setup and from where to start. First thing first, check you have access to https://make.powerapps.com/ Choose right environment of CDS (CE) Make sure you have access to the environment too, click on gear icon and Admin Center  Look for required environment and Open it, you must have access as going forward you are going to configure dual write steps in the environment user the same user you are logged in now. Now, go back to power platform admin center and...

D365FO: Entity cannot be deleted while dependent Entities for a processing group exist. Delete dependent Entities for a processing group and try again.

Scenario: There are times when you want to delete an entity from target entity list and when you do so, you face an error message which does not tell you where exactly the entity has been used.  "Entity cannot be deleted while dependent Entities for the processing group exist. Delete dependent Entities for a processing group and try again. " Solution: Browse the environment by appending this part  /?mi=SysTableBrowser&TableName=DMFDefinitionGroupEntity&cmp=USMF   at the end.  For example; if the environment URL is  https://daxture.sandbox.operations.dynamics.com then the complete URL will be https://daxture.sandbox.operations.dynamics.com/?mi=SysTableBrowser&TableName=DMFDefinitionGroupEntity&cmp=USMF Filter for Entity and it will give you the DefinitionGroup where the entity has been added or used in data management import/export projects. Get the DefinitionGroup name and search in the export/import projects under data management and either del...

Dual-write connection set error: An item with the same key has already been added

If you happen to see this error message then you have duplicate records in cdm_company entity in CDS environment. Check for cdm_companycode field this is normally not allowed but have a look and delete the ones with duplicates.