X++ code to import multiple files from a folder in AX 2012 R3
Create a Runbase class :
class RBReadFileFromDirectory extends RunBaseBatch
{
Filename ItemFileName;
Filename filename;
DialogField dialogFilename;
SalesOrderTmp salesOrderTmp;
FilePath filePath;
CommaTextIo fileIO;
Set fileSet;
CommaIo commaIo;
str currentFile;
container lineCon;
#File
#AviFiles
#define.CurrentVersion(1)
#define.Version1(1)
#localmacro.CurrentList
fileName
#endmacro
}
public Object dialog()
{
DialogRunbase dialog = super();
;
dialogFilename = dialog.addField(extendedTypeStr(FilenameOpen));
dialogFilename.value(filename);
return dialog;
}
public boolean getFromDialog()
{
;
fileName = dialogFileName.value();
return super();
}
public container pack()
{
return [#CurrentVersion,#CurrentList];
}
public boolean unpack(container packedClass)
{
Version version = runbase::getVersion(packedClass);
;
switch (version)
{
case #CurrentVersion:
[version,#CurrentList] = packedClass;
break;
default:
return false;
}
return true;
}
public static RBReadFileFromDirectory construct()
{
return new RBReadFileFromDirectory();
}
public static void main(Args _args)
{
RBReadFileFromDirectory readFileFromDirectory;
;
readFileFromDirectory= RBReadFileFromDirectory::construct();
if (readFileFromDirectory.prompt())
{
readFileFromDirectory.run();
}
}
public void run()
{
SetEnumerator sE;
int row = 1;
if (!filename) // check file exist from dialog
{
filePath = @'C:\Test\'; // sepcify the folder path
this.getFiles();
sE = fileSet.getEnumerator();
while (sE.moveNext()) // loop through all files
{
filename = sE.current();
if (filename)
{
this.Process(filename);
}
}
}
else // this code run for the file from dialog
{
this.Process(filename);
}
}
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::CLRError)
{
throw error ("Error");
}
}
// Core Logic
private void Process(Filename _fileName)
{
#File
IO iO;
Container con;
boolean first = true;
SalesTable salesTable;
SalesLine salesLine;
FileIoPermission perm;
;
perm = new FileIoPermission(_fileName, #IO_Read);
perm.assert();
iO = new CommaTextIo(_fileName,#IO_Read);
if (! iO || iO.status() != IO_Status::Ok)
{
throw error("@SYS19358");
}
while (iO.status() == IO_Status::Ok)
{
con = iO.read();// read file
if (con)
{
if (first) //skip header
{
first = false;
}
else
{
salesOrderLogLinesIns.clear();
salesOrderTmp.SalesId = conPeek(con, 1);
salesOrderTmp.CustAccount = conPeek(con, 2);
salesOrderTmp.PaymMode = conpeek(con, 3);
salesOrderTmp.insert();
}
}
}
}
No comments:
Post a Comment