Powered By Blogger
Showing posts with label SFTP. Show all posts
Showing posts with label SFTP. Show all posts

how to get csv file data from dotnet to d365 through sftp

 class FCC_SFTPConnection 

{

    public static void main(Args _args)

    {

        FCC_SFTPConnection sftpConnect = new FCC_SFTPConnection();

        sftpConnect.sFTPConnection();

    }


    public void sFTPConnection()

    {

        //str                        sftpFile;  

        FCC_LedgerVoucherStaggingParameters    voucherstagging;

        //ClrObject                  list = new ClrObject("System.Collections.Generic.List`1[System.String]");

        //FCC_SFTPConnection.sftpConnection sftp = new FCC_SFTPConnection.sftpConnection();

        FCC_MySshNet.sftpConnection           sftp = new FCC_MySshNet.sftpConnection();

         

        voucherstagging = FCC_LedgerVoucherStaggingParameters::find();


        str  host = voucherstagging.Host;

        int  port = voucherstagging.Port;

        str username  = voucherstagging.UserName;

        str password = voucherstagging.Password;


        str remoteDirectory                 = "/";

        str archiveDirectory                = "C:\Users\Adminacbb1787ee\Documents\SFTP";


        System.ObjectDisposedException                  error_ObjectDisposedException;

        System.InvalidOperationException                error_InvalidOperationException;

        System.Net.Sockets.SocketException              error_SocketException;

        Renci.SshNet.Common.SshConnectionException      error_SshConnectionException;

        Renci.SshNet.Common.SshAuthenticationException  error_SshAuthenticationException;

        Renci.SshNet.Common.ProxyException              error_ProxyException;

        System.ArgumentNullException                    error_ArgumentNullException;

        Renci.SshNet.Common.SftpPathNotFoundException   error_SftpPathNotFoundException;

 


        //str remoteDirectory                 = voucherstagging.ImportPath;

        //str archiveDirectory                = voucherstagging.ArchivePath;


        using (var sftpConnection = sftp.OpenSFTPConnection(host,port,username,password)) //Connect

        {

            try

            {

                int totalFiles = 0;

    

                sftpConnection.ChangeDirectory(remoteDirectory);//Import Path


                //sftpConnection.ListDirectory(remoteDirectory,list);

                //list  = (sftp.GetDirectories(sftpConnection, remoteDirectory));// Files List


                System.Collections.IEnumerable list = sftpConnection.ListDirectory(remoteDirectory, null);

                System.Collections.IEnumerator enumerator = list.GetEnumerator();

                Renci.SshNet.Sftp.SftpFile sftpFile;

                str name;

                //ClrObject enumerator = list.getEnumerator();

                 

                while (enumerator.movenext())

                {

                    totalFiles ++;


                    sftpFile = enumerator.get_Current();

                    name = sftpFile.get_Name();

 

                    if(name != ".." && name !=null && name != ".")

                    {

                        if(name == "dataaa.csv")

                        {

                            System.IO.Stream Stream = sftp.DownloadFile(sftpConnection, remoteDirectory + '/'+ name);

      

                            //this.ReadCSVFile(Stream,sftpFile);

                            this.ReadCSVFileAndCreateJournal(Stream,name);


                            sftp.MoveFile(sftpConnection,

                            remoteDirectory+ '/'+name,

                            archiveDirectory+ '/'+ name,

                            false);

                        

                        }

                    }

                }

            }

            //catch

            //{

            //    throw error(infolog.text());

            //}

            catch (error_ObjectDisposedException)

            {

                throw error("The method was called after the client was disposed.. ");

            }

            catch (error_InvalidOperationException)

            {

                throw error("The client is already connected.");

            }

            catch (error_SocketException)

            {

                throw error("Socket connection to the SSH server or proxy server could not be established or an error occurred while resolving the hostname.");

            }

            catch (error_SshConnectionException)

            {

                throw error("SSH session could not be established.");

            }

            catch (error_SshAuthenticationException)

            {

                throw error("Authentication of SSH session failed.");

            }

            catch (error_ProxyException)

            {

                throw error("Failed to establish proxy connection.");

            }

            finally

            {

                if(sftpConnection.IsConnected)

                    sftpConnection.Disconnect();

            }

        }

              

    }


 

    public  boolean ReadCSVFileAndCreateJournal(System.IO.Stream  stream, str fileName)

    {

        

        ledgerJournalName               JournalName ;

        boolean                         journalCreated = true;

        FCC_VoucherJournalStaging       voucherJournalStaging;

        int  recordCount = 0;

 

        try

        {

            Array                                           fileLines;

            FileUploadTemporaryStorageResult                fileUpload;

            AsciiStreamIo                                   file;

            container                                       record;

            LedgerJournalEngine                             ledgerJournalEngine;

            UnknownNoYes                                    triangulationResult;

            ExchRateSecondTxt                               exchRateSecondTxt;

          

            file = AsciiStreamIo::constructForRead(stream);

            if (file)

            {

                if (file.status())

                {

                    throw error("@SYS52680");

                }

                file.inFieldDelimiter(',');

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

           

                ttsbegin;

                JournalName = ledgerJournalName::find("JV");

 

                if(!JournalName .RecId)

                  throw error("@11250");

 

               

 

                

                while (!file.status())

                {

                    record = file.read();

                    recordCount++;

 

                    if (conLen(record) && recordCount !=1)

                    {

                        voucherJournalStaging.JVVoucherNo = conPeek(record,1);

                        voucherJournalStaging.JVLineNo    = conPeek(record,2);

                        voucherJournalStaging.JVAcntCode  = conPeek(record,4);

                        voucherJournalStaging.JVAcntType  = conPeek(record,5);

                        voucherJournalStaging.JVDebitAmtFC   = conPeek(record,6);

                        voucherJournalStaging.JVCreditAmtFC  = conPeek(record,7);

                        voucherJournalStaging.JVLegalEntityD365   = conPeek(record,8);

                        voucherJournalStaging.JVCurrency       = conPeek(record,9);

                        voucherJournalStaging.JVExRate        = conPeek(record,10);

                        voucherJournalStaging.TransDate        = conPeek(record,14);

                        voucherJournalStaging.insert();


                    }

                }               

              ttscommit;

              info(strFmt("Records Inserted Succesfully"));

            }

        }

        catch

        {

            ttsabort;

            checkFailed(strFmt("@CL:ErrorImportingFile",recordCount));

        }

        finally

        {

              info(strFmt("@CL:ImportSucessfully",fileName));

        }

        return journalCreated;

    }


}

Connect SFTP server using x++

 Connect SFTP server using x++.


For this, we need to create a C# project and we need to write code in C#. After that DLL file, I need to add it as a reference for my D365 project.

We need to download Renci.ssh.Net from the NuGet package.

We can download SSH from the below link:

https://github.com/sshnet/SSH.NET/releases/tag/2020.0.1

or

https://www.dllme.com./dll/files/renci_sshnet

Please follow this blog for Renci. Link


C# Code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Renci.SshNet;
namespace SFTPConnect
{
    public class sftpConnection
    {
        public SftpClient sftpClient;
 
        public SftpClient OpenSFTPConnection(string host, int port, string username, string password)
        {
            if (this.sftpClient == null)
            {
                this.sftpClient = new Renci.SshNet.SftpClient(host, port, username, password);
				
		--------------or-------------------------
		List<AuthenticationMethod> 	methods = new List<AuthenticationMethod>
		{
		    new PasswordAuthenticationMethod(username, password)
		};

		var connectionInfo = new ConnectionInfo(host, port, username, methods.ToArray());
						
		this.sftpClient = new SftpClient(connectionInfo);
            }
 
            if (!this.sftpClient.IsConnected)
            {
                this.sftpClient.Connect();
            }
 
            return this.sftpClient;
        }
 
        public List<string> GetDirectories(SftpClient _SftpClient, string path)
        {
            return _SftpClient.ListDirectory(path)/*.Where(n => n.IsDirectory)*/.Select(n => n.Name).ToList();
        }
 
        public void MoveFile(SftpClient _SftpClient, string sourcePath, string destinationPath, bool isPosix)
        {
            _SftpClient.RenameFile(sourcePath, destinationPath, isPosix);
        }
 
        public Stream DownloadFile(SftpClient _SftpClient, string sourcePath)
        {
            var memoryStream = new MemoryStream();
 
            _SftpClient.DownloadFile(sourcePath, memoryStream);
 
            memoryStream.Position = 0;
 
            return memoryStream;
        }
	public void upLoadFile(SftpClient _SftpClient, System.IO.Stream _sourceFile, string _fileName)
	{
	    _sourceFile.Position = 0;
	    _SftpClient.BufferSize = 8 * 1024;
	    _SftpClient.UploadFile(_sourceFile, _fileName);
	}
    }
}


X++ Code:

    public void sFTPConnection()
    {	
        str                       	sftpFile;
        ClrObject                 	list = new ClrObject("System.Collections.Generic.List`1[System.String]");
        SFTPConnect.sftpConnection	sftp = new SFTPConnect.sftpConnection();

        using (var sftpConnection = sftp.OpenSFTPConnection(host, port, username, password)) // Connect
        {
            try
            {
                int totalFiles = 0;
				
                sftpConnection.ChangeDirectory('/Upload');//Import Path

                list  = (sftp.GetDirectories(sftpConnection, '/Upload/'));// Files List
ClrObject enumerator = list.getEnumerator(); while (enumerator.movenext()) { totalFiles ++; sftpFile = enumerator.get_Current(); if(sftpFile != ".." && sftpFile !=null && sftpFile != ".") {         System.IO.Stream Stream = sftp.DownloadFile(sftpConnection, '/Upload' + '/'+ sftpFile);
this.ReadCSVFile(Stream,sftpFile); sftp.MoveFile(sftpConnection, 'Import Path'+ '/'+sftpFile, 'destination path'+ '/'+ sftpFile, false); } } }     catch     { throw error(infolog.text());     } finally { if(sftpConnection.IsConnected) sftpConnection.Disconnect(); } } }          public boolean ReadCSVFile(System.IO.Stream stream, str fileName)     { AsciiStreamIo file; container record; file = AsciiStreamIo::constructForRead(stream); if (file) { if (file.status()) {              throw error("@SYS52680"); } file.inFieldDelimiter(','); file.inRecordDelimiter('\r\n'); while (!file.status()) {         record = file.read(); recordCount++; if (conLen(record) && recordCount !=1) {     conPeek(record,2)); } } } return true; }  

DisableStandredButton

 My requirement is to disable the delete button for journals that were posted:- After Posting the button is enabled fig:- Line level also th...