Saturday, December 26, 2020

Dynamics 365 F&O Import data from CSV

In this example We will be importing name and id from a csv file in a table.


class TTC_AY_ImportFile

{

    public static void main(Args _args)

    {

        AsciiStreamIo                       file;

        FileUploadTemporaryStorageResult    fileUpload;

        TTC_WorkerTable                     workerTable;

        Counter                             counter = 0;

        str                                 Name;

        #OCCRetryCount


        try

        {

            fileUpload  = File::GetFileFromUser() as FileUploadTemporaryStorageResult;

            file        = AsciiStreamIo::constructForRead(fileUpload.openResult());

            if (file)

            {

                if (file.status())

                {

                    throw error("Unknown problem while importing file");

                }

                file.inFieldDelimiter(';'); //separator

                file.inRecordDelimiter('\r\n');

            }


            //Read a CSV File

            container rec;

            ttsbegin;

            while (!file.status())

            {

                counter++;

                rec = file.read();

                if (conLen(rec))

                {

                    Name = conPeek(rec, 2);

                    workerTable = TTC_WorkerTable::find(Name);

                    

                    if(!workerTable.RecId)

                    {

                        workerTable.clear();

                        workerTable.Id    = conPeek(rec, 1);

                        workerTable.Name  = Name;

                        workerTable.insert();

                    }

                }

            }

            ttscommit;

            info("Operation complete.");

        }

        catch (Exception::Deadlock)

        {

            retry;

        }

        catch (Exception::UpdateConflict)

        {

            if (appl.ttsLevel() == 0)

            {

                if (xSession::currentRetryCount() >= #RetryNum)

                {

                    throw Exception::UpdateConflictNotRecovered;

                }

                else

                {

                    retry;

                }

            }

            else

            {

                throw Exception::UpdateConflict;

            }

        }

    }

}