Friday, 5 November 2010

AX - Import flat file job

I use this quite often. When I want a quick job to import a text file.

static void ImportFileWithDialog(Args _args)
{
    AsciiIO     asciiIO;
    Filename    filename;
    NoYesId     skipFirstLine;
    Container   line;
    Dialog      dialog;
    DialogField dialogFileName, dialogSkipFirstLine;
    ;

    dialog                  = new Dialog("Import file");
    dialogFileName          = dialog.addField(typeid(Filenameopen), "File name");
    dialogSkipFirstLine     = dialog.addField(typeid(NoYesId), "Skip first line");
    dialog.run();

    if (dialog.run())
    {
        filename      = dialogFileName.value();
        skipFirstLine = dialogSkipFirstLine.value();
    }

    asciiIO = new AsciiIO(filename, 'R');

    if (!asciiIO || asciiIO.status() != IO_Status::Ok )
    {
        throw error (strfmt("@SYS19312",filename));
    }


    ttsbegin;
    asciiIO.inRecordDelimiter('\r\n');
    asciiIO.inFieldDelimiter(',');

    if (skipFirstLine)
        line = asciiIO.read();

    while (asciiIO.status() == IO_status::Ok)
    {
        line = asciiIO.read();

        if (line)
        {
            info(conpeek(line,1));
            info(conpeek(line,2));
        }
    }
    ttscommit;
}

1 comment:

Venkat Chaitanya said...

IN AX 2012 REPLACE THE FOLLOWING LINES TO MAKE USE OF THE CODE

// dialogFileName = dialog.addField(typeid(Filenameopen), "File name");
// dialogSkipFirstLine = dialog.addField(typeid(NoYesId), "Skip first line");

WITH

dialogFileName = dialog.addField(extendedTypeStr(Filenameopen), "File name");
dialogSkipFirstLine = dialog.addField(extendedTypeStr(NoYesId), "Skip first line");