Tag Archives: FTP

Uploading a ​file to FTP server through X++ using batch processing…

Hi experts,

I came with one more stuff related to the uploading file to FTP server which is using batch processing, there is a lot of code change difference in file uploading to FTP server manually and using batch processing.

A class object must have RunOn property as “Server” and every time you make changes to an object, you must generate CIL.

if you would like to debug your code while it is running using batch processing, you need to debug from Visual studio and attach process to it.

Here is a sample class which uploads file to FTP server using batch processing

Sample file upload to FTP server using batch processing

Please feel free to comment your errors or suggestions or if you would like to know how to debug batch jobs using visual studio.

Thant’s it from my side, thank you

Happy Daxing…

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..,