Category Archives: File operations

Uploading a ​file to FTP server through X++ with detail explanation.

The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files between a client and server on a computer network but in our case, transfers file from AX client to file directory present on FTP server. You can easily find the code on the web on how to upload a file to FTP through X++ code but not in detail. In this post, I will try to explain detail about each line what it does during execution. So, let’s start.

  • The file name must not have spaces and colons in it otherwise it throws error. so, below in the example

filename = File09-12-2016_11.25.59pm.CSV;//Correct
filename = File09-12-2016_11.25.59 pm.CSV;//wrong, because there is space before pm
filename = File09-12-2016_11:25:59pm.CSV;//wrong, there is colon characters between hour, minutes and seconds.

  • Make sure you must have proper file path otherwise, it throws an error.

TempPath = System.IO.Path::GetTempPath(); //Automatically creates temporary directory
TempPath += filename;//append file to TemPath without using ‘/’ backslash.

  • If you don’t want to rename file name while file uploading on FTP server, then, use below code which works perfectly. FTP server gives it own name to file

ftpFilename = “ftp://ftpname.com”;
request = System.Net.WebRequest::Create(new System.Uri(ftpFileName));
ftpRequest = request; //Type casting object to ftpwebrequest object
credential = new System.Net.NetworkCredential(“Uname”, “Pword”);
ftpRequest.set_Credentials(credential);
//FTP file UploadFileWithUniqueName represents STOU
ftpRequest.set_Method(“STOU”);

  • If you want to rename file name while file uploading on FTP server, then use below code which works perfectly

fileNameString = YourDesiredName.extension;
//if you don’t use @”/”, will get error.
ftpFileName = “ftp://ftpname.com” + @”/” + fileNameString;
request = System.Net.WebRequest::Create(new System.Uri(ftpFileName));
ftpRequest = request; //Type casting object to ftpwebrequest object
credential = new System.Net.NetworkCredential(“Uname”, “Pword”);
ftpRequest.set_Credentials(credential);
//FTP file UploadFile represents STOR
ftpRequest.set_Method(“STOR”);

  • If you want to rename file name while file uploading on FTP server, then disable the proxy of FTP web request.

//UploadFile is not supported through an Http proxy, disable the proxy for this request.
ftpRequest.set_Proxy(null);

  • The entry point for access stream to FTP server, which generally throws error, if any one of above mentioned statements have errors, so, be careful while writing code in above mentioned statements.

requestStream = ftpRequest.GetRequestStream();

  • Don’t keep open temporary directory in file explorer from which FTP Server reads file, otherwise, it throws  timeout error.
  • Below is perfect code to upload file to FTP server, please have a glance.

Public void uploadFiletoFTPServer
{
System.Object request,response,credential;
System.IO.StreamReader streamReader;
System.IO.Stream requestStream;
System.Array files;
System.Net.FtpWebRequest ftpRequest;
System.Net.FtpWebResponse ftpResponse;
System.Byte[] bytes;
System.Text.Encoding getUTF8;
System.Exception sysException;
Str 120 TempPath,executedate;
str timeinstr,nextFile;
Commaio file;
container line;
Filename filepath,fileType,fileNameString,ftpFileName,fileName;

//removed spaces and colons because of FTP protocol voilation and throws error
timeinstr = time2str(timeNow(),DateSeparator::Dot,DateSeparator::Dot);
timeinstr = strRem(timeinstr,” “);

new InteropPermission(InteropKind::ClrInterop).assert();
//part of filename
executedate = date2Str(today(),213,DateDay::Digits2,
DateSeparator::Hyphen,
DateMonth::Digits2,
DateSeparator::Hyphen,
DateYear::Digits4)+”_”+timeinstr+”.CSV”;

TempPath = System.IO.Path::GetTempPath();
//complete filename with full path
TempPath += “mydesiredname”+executedate;
if (TempPath == ”)
{
error(“Please set up the location for export file.”);
return;
}

line = [“Microsoft”,”Dynamics”,”AX”,”7.0″,”ERP”];
file.writeExp(line);
file = null;

try
{
// reading filepath, filname and filetype in container
[filepath, filename, fileType] = fileNameSplit(TempPath);
ftpFileName = “ftp://ftpname.com” + @”/” + fileNameString;
//reading file in stream buffer
streamReader = new System.IO.StreamReader(TempPath);
//Encode characters and get buffer in array of bytes, then close stream buffer
getUTF8 = System.Text.Encoding::get_UTF8();
bytes = getUTF8.GetBytes(streamReader.ReadToEnd());
streamReader.Close();
// little workaround to get around the casting in .NET
request = System.Net.WebRequest::Create(new System.Uri(ftpFileName));
ftpRequest = request; //Type casting object to ftpwebrequest object
credential = new System.Net.NetworkCredential(“Uname”, “Pword”);
ftpRequest.set_Credentials(credential);
ftpRequest.set_ContentLength(bytes.get_Length());
//FTP file UploadFile represents STOR
ftpRequest.set_Method(“STOR”);
//UploadFile is not supported through an Http proxy, disable the proxy for this request.
ftpRequest.set_Proxy(null);
//entry point for ftp server
requestStream = ftpRequest.GetRequestStream();
requestStream.Write(bytes,0,bytes.get_Length());
requestStream.Close();
response = ftpRequest.GetResponse();
ftpResponse = response;//Type casting object to ftpwebresponse object
//Delete file from Temporary directory once it is uploaded to FTP server successfully.
if(ftpResponse != null)
{
WinAPI::deleteFile(nextFile);
}
}
catch(Exception::CLRError)
{
sysException = CLRInterop::getLastException();
info(sysException.get_Message());
}

CodeAccessPermission::revertAssert();

}

Hope you find my post as comprehensive and please feel free to comment below with your errors in code if you have any, I will try to figure and let you know.

Thanks and Happy DaXing..,

 

Advertisements

How to export table data in to csv file in AX 2012

A CSV is a comma separated values file, which allows data to be saved in a table structured format. Traditionally they take the form of a text file containing information separated by commas.

You can export table data outside of AX into file which separates value of field with a comma. e.g., “Mohammed”, “Raziq”, “Ali”, “Hussain”,”OU”, “MCA”,”27″. Row data are separated by commas.

Lets proceed with an example to understand how to export table into CSV file. The following code writes selected table data into file with proper validations.

CommaTextIo class plays major role in writing/reading file csv in AX 2012

public void exportCSVFile()
{
CommaTextIo file;
container line;
FileIoPermission perm;
#define.filename(@’filepath’)
#File
perm = new FileIoPermission(#filename, #io_write);
perm.assert();
file = new CommaTextIo(#filename, #io_write);
if (!file || file.status() != IO_Status::Ok)
{
throw error(“@SYS19358”);//throws error if file path is not found
}

select * from custTable where custTable.AccountNum == ‘0010’;

if(custTable)
{
line = [custTable.name(),custTable.custGroup,custTable.creditMax];
file.writeExp(line);
}

}
Assign null value to file object once you are done with writing.
file = null;
Hope you understood this simple code to write data into CSV file.

Thanks & Happy DaXing……..