Exemple #1
0
        public override FileSystem.NetworkFileSystem CreateConnection()
        {
            FTPSClient          ftps = new FTPSClient();
            EDataConnectionMode edc;

            if (_passive == true)
            {
                edc = EDataConnectionMode.Passive;
            }
            else
            {
                edc = EDataConnectionMode.Active;
            }

            System.Net.NetworkCredential creds = null;
            if (_anon == false)
            {
                creds = new System.Net.NetworkCredential(_username, _password);
            }

            ftps.Connect(_server, _port, creds, ESSLSupportMode.ClearText, null, null, 0, 0, 0, 120, true, edc);

            FileSystem.FTPServerFileSystem fs = new FileSystem.FTPServerFileSystem(ftps);

            return(fs);
        }
        private async Task <FtpMessage> GetFromFtps(FtpConfiguration config, string path)
        {
            var host     = config.FtpHost.Host;
            var username = config.Username;
            var password = config.Password;
            var port     = config.FtpPort;


            using (var client = new FTPSClient())
            {
                client.Connect(host,
                               new NetworkCredential(username, password),
                               ESSLSupportMode.CredentialsRequired |
                               ESSLSupportMode.DataChannelRequested);

                var ftps = client.GetFile(path);
                var data = ReadToEnd(ftps);
                return(new FtpMessage
                {
                    Configuration = config,
                    Data = data,
                    Filename = path
                });
            }
        }
Exemple #3
0
        //private string hostname, username, password;

        public static void UploadFiles(ConfigurationProfile profile, string temppath, string remotedir)
        {
            // Setup session options
            // add support for: scp/sftp protocols, ssh host/private keys, active/passive mode, port, FtpSecure, timeout, ssl cert,

            using (FTPSClient session = new FTPSClient())
            {
                ESSLSupportMode sslSupportMode = ESSLSupportMode.ClearText;
                RemoteCertificateValidationCallback userValidateServerCertificate;
                userValidateServerCertificate = new RemoteCertificateValidationCallback(ValidateServerCertificate);

                // enable encryption if desired
                if (profile.Encryption.IsTrue())
                {
                    sslSupportMode |= ESSLSupportMode.ControlAndDataChannelsRequired | ESSLSupportMode.CredentialsRequired;
                    if (profile.EncryptionImplicit.IsTrue())
                    {
                        // implicit if desired
                        sslSupportMode |= ESSLSupportMode.Implicit;
                    }
                    if (profile.ForceEncryption.IsTrue())
                    {
                        // force encryption if desired
                        userValidateServerCertificate = new RemoteCertificateValidationCallback(delegate { return(true); });
                    }
                }

                session.Connect(profile.Hostname, new System.Net.NetworkCredential(profile.Username, profile.Password), sslSupportMode, userValidateServerCertificate);

                // Upload files
                //TransferOptions transferOptions = new TransferOptions();
                //transferOptions.TransferMode = TransferMode.Binary;

                //TransferOperationResult transferResult;
                //transferResult = session.PutFiles(Path.Combine(temppath, "*"), Common.Parse(remotedir), false, transferOptions);

                try
                {
                    session.SetCurrentDirectory(Common.ParseTemplate(remotedir));
                }
                catch
                {
                    session.MakeDir(Common.ParseTemplate(remotedir));
                }
                session.PutFiles(temppath, Common.ParseTemplate(remotedir), "*", EPatternStyle.Wildcard, false, new FileTransferCallback(TransferCallback));

                // Throw on any error
                //transferResult.Check();

                // Print results
                //foreach (TransferEventArgs transfer in transferResult.Transfers)
                //{
                //    Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                //}
            }
        }
        public void DeleteAllUpUntil(DateTime finalDate)
        {
            int deletedFiles = 0;

            _log.DebugFormat("Trying to delete all files created up until '{0}'", finalDate);

            using (FTPSClient client = new FTPSClient())
            {
                // Connect to the server, with mandatory SSL/TLS
                // encryption during authentication and
                // optional encryption on the data channel
                // (directory lists, file transfers)
                client.Connect(_server.Authority, _credential,

                               ESSLSupportMode.All, CertificateValidationCallback);


                var items = client.GetDirectoryList();

                //adding root dir to guarantee old files deletion in it.
                items.Add(new DirectoryListItem()
                {
                    IsDirectory = true, Name = "/"
                });

                var dirs = items.Where <DirectoryListItem>(x => x.IsDirectory);



                foreach (var dir in dirs)
                {
                    client.SetCurrentDirectory(dir.Name);

                    var files = client.GetDirectoryList().Where <DirectoryListItem>(x => x.IsDirectory == false);
                    foreach (var file in files)
                    {
                        try
                        {
                            if (!file.IsDirectory && file.CreationTime < finalDate)
                            {
                                client.DeleteFile(file.Name);
                                deletedFiles++;
                            }
                        }
                        catch (Exception e)
                        {
                            _log.ErrorFormat("'{0}' while deleting '{1}/{2}'", e.Message, dir.Name, file.Name);
                        }
                    }
                    client.SetCurrentDirectory("/");
                }
            }

            _log.DebugFormat("{0} files deleted", deletedFiles);
        }
Exemple #5
0
        public AutoUploadLog(int sessionid)
        {
            string val      = PackString(FingerPrint.Value(), 9);
            string uniqueid = "log-" + sessionid.ToString() + "-" + val;

            FTPSClient fli = new FTPSClient();

            fli.Connect("hostname", new System.Net.NetworkCredential("username", "password"), ESSLSupportMode.DataChannelRequested);
            fli.PutFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\BExplorer\\log.txt", uniqueid + ".txt");
            fli.Close();
        }
Exemple #6
0
 /// <summary>
 ///     Connect to remote host
 /// </summary>
 /// <param name="server"></param>
 /// <param name="port"></param>
 /// <param name="user"></param>
 /// <param name="password"></param>
 /// <returns></returns>
 public virtual bool Connect(string server, string port, string user, string password)
 {
     try
     {
         _client = new FTPSClient();
         _client.Connect(server, new NetworkCredential(user, password), ESSLSupportMode.ClearText);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Exemple #7
0
        public Repository(string host, Token token, string repoFolderPath)
        {
            _ftp = new FTPSClient();
            _ftp.Connect(host,
                         new NetworkCredential(token.Key, token.Secret),
                         ESSLSupportMode.ClearText);

            try
            {
                _ftp.MakeDir(repoFolderPath);
            }
            catch {}
            _ftp.SetCurrentDirectory(repoFolderPath);
        }
Exemple #8
0
        private static void DoConnect(FTPSClient client)
        {
            WriteCredentialsEncryptionWarning();

            CheckPassword();

            int port = options.port;

            if (port == 0)
            {
                port = (options.sslRequestSupportMode & ESSLSupportMode.Implicit) == ESSLSupportMode.Implicit ? 990 : 21;
            }

            NetworkCredential credential = null;

            if (options.userName != null && options.userName.Length > 0)
            {
                credential = new NetworkCredential(options.userName, options.password);
            }

            X509Certificate x509ClientCert = null;

            if (options.sslClientCertPath != null)
            {
                x509ClientCert = X509Certificate.CreateFromCertFile(options.sslClientCertPath);
            }

            client.Connect(options.hostName, port,
                           credential,
                           options.sslRequestSupportMode,
                           new RemoteCertificateValidationCallback(ValidateTestServerCertificate),
                           x509ClientCert,
                           options.sslMinKeyExchangeAlgStrength,
                           options.sslMinCipherAlgStrength,
                           options.sslMinHashAlgStrength,
                           options.timeout * 1000,
                           options.useCtrlEndPointAddressForData,
                           options.dataConnectionMode);

            // client.Connect already sets binary by default
            if (options.transferMode != ETransferMode.Binary)
            {
                client.SetTransferMode(options.transferMode);
            }

            WriteConnectionInfo(client);

            WriteSslStatus(client);
        }
Exemple #9
0
        public IEnumerable <FtpFileInfo> GetDirectoryList(string remoteDirectory)
        {
            var remoteDirectoryName = remoteDirectory;

            if (!this.IsDirectory(remoteDirectory))
            {
                remoteDirectoryName = this.GetDirectoryName(remoteDirectory);
            }

            if (string.IsNullOrEmpty(remoteDirectory))
            {
                remoteDirectory = ".";
            }

            var ftp = new FTPSClient();

            try
            {
                ftp.Connect(this.host, new NetworkCredential(this.user, this.password), ESSLSupportMode.ClearText);
                ftp.SetTransferMode(this.UseBinary ? ETransferMode.Binary : ETransferMode.ASCII);

                var ftpFiles = ftp.GetDirectoryList(remoteDirectory);
                var files    = new List <FtpFileInfo>();
                foreach (var ftpFile in ftpFiles)
                {
                    var ftpFileInfo = new FtpFileInfo();
                    ftpFileInfo.Name         = ftpFile.Name;
                    ftpFileInfo.CreationTime = ftpFile.CreationTime;
                    ftpFileInfo.Flags        = ftpFile.Flags;
                    ftpFileInfo.IsDirectory  = ftpFile.IsDirectory;
                    ftpFileInfo.FullName     = Path.Combine(remoteDirectoryName, ftpFileInfo.Name);
                    files.Add(ftpFileInfo);
                }

                return(files);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (ftp != null)
                {
                    ftp.Close();
                    ftp.Dispose();
                }
            }
        }
Exemple #10
0
 public bool Connect()
 {
     try
     {
         client = new FTPSClient();
         client.Connect(_host, _post, new NetworkCredential(_userName, _passWord),
                        ESSLSupportMode.Implicit | ESSLSupportMode.CredentialsRequired | ESSLSupportMode.DataChannelRequested,
                        new RemoteCertificateValidationCallback(ValidateServerCertificate), null, 0, 0, 0, null);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Exemple #11
0
 /// <summary>
 ///     Connect to remote host
 /// </summary>
 /// <param name="server"></param>
 /// <param name="port"></param>
 /// <param name="user"></param>
 /// <param name="password"></param>
 /// <returns></returns>
 public override bool Connect(string server, string port, string user, string password)
 {
     try
     {
         _client = new FTPSClient();
         //it doesn't validate the certificate due to some errors with selfsigned certificates
         _client.Connect(server, new NetworkCredential(user, password), ESSLSupportMode.All,
                         (sender, certificate, chain, errors) => true);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Exemple #12
0
        public IEnumerable <string> DownloadFiles(string remoteFiles, string localDirectory, bool deleteRemoteFile = false)
        {
            var downloadedFiles = new List <string>();

            var ftp = new FTPSClient();

            try
            {
                ftp.Connect(this.host, new NetworkCredential(this.user, this.password), ESSLSupportMode.ClearText);
                ftp.SetTransferMode(this.UseBinary ? ETransferMode.Binary : ETransferMode.ASCII);
                //ftp.SetCurrentDirectory(remoteFolder);

                var directoryName     = this.GetDirectoryName(remoteFiles);
                var remoteFileInfos   = this.GetDirectoryList(directoryName);
                var remoteFilePattern = Path.GetFileName(remoteFiles);

                foreach (var remoteFileInfo in remoteFileInfos)
                {
                    if (string.IsNullOrEmpty(remoteFilePattern) || FileUtil.MatchesWildcard(remoteFileInfo.Name, remoteFilePattern))
                    {
                        var localFileName = Path.Combine(localDirectory, Path.GetFileName(remoteFileInfo.Name));

                        ftp.GetFile(remoteFileInfo.FullName, localFileName);
                        downloadedFiles.Add(remoteFileInfo.FullName);

                        if (deleteRemoteFile == true)
                        {
                            ftp.DeleteFile(remoteFileInfo.FullName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (ftp != null)
                {
                    ftp.Close();
                    ftp.Dispose();
                }
            }

            return(downloadedFiles);
        }
Exemple #13
0
        private void uploadFileFTPS(string lokasifile)
        {
            using (FTPSClient client = new FTPSClient())
            {
                string namafile = "";
                //ambil nama filenya
                bool sesuaiFormat = false;
                try
                {
                    sesuaiFormat = Regex.IsMatch(lokasifile, "[\\w\\W\\s]*Outbox[\\\\]([\\w\\W\\s]*)");
                    if (sesuaiFormat)
                    {
                        try
                        {
                            Regex RegexObj = new Regex("[\\w\\W\\s]*Outbox[\\\\]([\\w\\W\\s]*)");
                            namafile = RegexObj.Match(lokasifile).Groups[1].Value;
                        }
                        catch (ArgumentException ex)
                        {
                        }
                    }
                }
                catch (ArgumentException ex)
                {
                }

                Console.WriteLine("Namafile:" + namafile);
                Console.WriteLine("Lokasifile:" + lokasifile);

                FileInfo objFile = new FileInfo(lokasifile);
                Console.WriteLine("" + objFile.Name);

                try
                {
                    client.Connect(urlftp, new NetworkCredential(username, password),
                                   ESSLSupportMode.All, new RemoteCertificateValidationCallback(ValidateTestServerCertificate));
                    Console.WriteLine("" + objFile.Directory);

                    //mulai upload
                    client.PutFile(lokasifile, direktoritujuan + namafile);
                }
                catch (Exception e)
                {
                    Console.WriteLine("" + e.StackTrace);
                }
            }
        }
Exemple #14
0
        public void DownloadFile(string remoteFile, string localFile, bool deleteRemoteFile = false)
        {
            var ftp = new FTPSClient();
            var localDownloadFile = localFile;

            try
            {
                //ftp.Connect(hostname: host,
                //            port: this.port,
                //            credential: new NetworkCredential(this.user, this.password),
                //            sslSupportMode: ESSLSupportMode.All,
                //            userValidateServerCertificate: null,
                //            x509ClientCert: null,
                //            dataConnectionMode: EDataConnectionMode.Passive);
                ftp.Connect(this.host, new NetworkCredential(this.user, this.password), ESSLSupportMode.ClearText);
                ftp.SetTransferMode(this.UseBinary ? ETransferMode.Binary : ETransferMode.ASCII);

                //ftp.SetCurrentDirectory(remoteFolder);

                if (Directory.Exists(localFile) && !Path.HasExtension(localFile))
                {
                    localDownloadFile = Path.Combine(localFile, Path.GetFileName(remoteFile));
                }

                ftp.GetFile(remoteFile, localDownloadFile);

                if (deleteRemoteFile == true)
                {
                    ftp.DeleteFile(remoteFile);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (ftp != null)
                {
                    ftp.Close();
                    ftp.Dispose();
                }
            }
        }
Exemple #15
0
 public void Connect(string host, int port)
 {
     _host = host;
     _port = port;
     Debug.WriteLine("Connecting to FTP " + host + ":" + port);
     client.Connect(host, port,
                    new NetworkCredential("yourUsername", "yourPassword"),
                    ESSLSupportMode.ClearText,
                    null,
                    null,
                    0,
                    0,
                    0,
                    3000,
                    true,
                    EDataConnectionMode.Active
                    );
     Debug.WriteLine("Connection successful " + host + ":" + port);
 }
Exemple #16
0
        public bool CheckConnect()
        {
            bool isAvailable;

            using (FTPSClient cli = new FTPSClient())
            {
                try
                {
                    cli.Connect(_host, _post, new NetworkCredential(_userName, _passWord),
                                ESSLSupportMode.Implicit | ESSLSupportMode.CredentialsRequired | ESSLSupportMode.DataChannelRequested,
                                new RemoteCertificateValidationCallback(ValidateServerCertificate), null, 0, 0, 0, null);
                    isAvailable = cli.WelcomeMessage == String.Empty ? false : true;
                }
                catch (Exception)
                {
                    isAvailable = false;
                }
            }
            return(isAvailable);
        }
        private async Task SendByFtps(FtpMessage ftpMessage)
        {
            var host     = ftpMessage.Configuration.FtpHost;
            var path     = ftpMessage.Filename;
            var username = ftpMessage.Configuration.Username;
            var password = ftpMessage.Configuration.Password;
            var port     = ftpMessage.Configuration.FtpPort;


            using (var client = new FTPSClient())
            {
                client.Connect(host.Host,
                               new NetworkCredential(username, password),
                               ESSLSupportMode.CredentialsRequired |
                               ESSLSupportMode.DataChannelRequested);

                var ftps = client.PutFile(path);

                await ftps.WriteAsync(ftpMessage.Data, 0, ftpMessage.Data.Length);

                ftps.Close();
            }
        }
Exemple #18
0
        public void CreateDirectory(string newDirectory)
        {
            var ftp = new FTPSClient();

            try
            {
                ftp.Connect(this.host, new NetworkCredential(this.user, this.password), ESSLSupportMode.ClearText);
                ftp.SetTransferMode(this.UseBinary ? ETransferMode.Binary : ETransferMode.ASCII);

                ftp.MakeDir(newDirectory);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (ftp != null)
                {
                    ftp.Close();
                    ftp.Dispose();
                }
            }
        }
Exemple #19
0
        public static string GetXMLFile(int saleid)
        {
            string   Host     = null;
            Int32    Port     = 0;
            string   Username = null;
            string   Password = null;
            string   thisone  = "";
            DateTime Latest   = Convert.ToDateTime("1/1/1970");

            // Get FTP credentials from config
//            Auction.AuctionConfig config = Administration.ReadConfigFile();

//            LogMsg("GetXMLFile");

            try
            {
                // Ftp Server settings

/*                                Host = config.FtpServer;
 *                              Username = config.FtpUser;
 *                              Password = Auction.DecodeFrom64(config.FtpPassword);
 *                              Port = Int32.Parse(config.FtpPort);*/
//                Host = "54.154.210.120";
                Host     = "192.168.44.40";
                Username = "******";
                Password = "******";
                Port     = 990;
            }
            catch (ArgumentNullException ne)
            {
                LogMsg(ne);
                return("");
            }
            catch (FormatException fe)
            {
                LogMsg(fe);
                return("");
            }

            string targetDirectory = "C:\\TransactionLogs";

            ulong?largest = 0;

            // Download the XML transcript and pop it into AMS...
            using (FTPSClient client = new FTPSClient())
            {
                try
                {
                    client.Connect(Host, Port,
                                   new NetworkCredential(Username,
                                                         Password),
                                   ESSLSupportMode.CredentialsRequired | ESSLSupportMode.DataChannelRequested | ESSLSupportMode.Implicit,
                                   new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications),
                                   new System.Security.Cryptography.X509Certificates.X509Certificate(),
                                   0, 0, 0, 60000, true);
                    LogMsg("GetXMLFile - FTP Connected to sale " + saleid);
                }
                catch (FTPCommandException fe)
                {
                    LogMsg(fe);
                    return("");
                }
                catch (IOException ie)
                {
                    LogMsg(ie);
                    return("");
                }
                catch (SocketException ie)
                {
                    LogMsg(ie);
                    return("");
                }

                try
                {
                    // Change to Transaction log directory
                    String pwd = client.GetCurrentDirectory();
                    client.SetCurrentDirectory("TransactionLogs");
                }
                catch (FTPCommandException fe)
                {
                    LogMsg(fe);
                    return("");
                }

                try
                {
                    string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                                    @"Humboldt\AuctionController\transactionlogs\");
                    directory = "C:\\TransactionLogs\\";
                    // Make sure directory exists
                    if (Directory.Exists(directory))
                    {
                    }
                    else
                    {
                        Directory.CreateDirectory(directory);
                    }

                    {
                        // Find latest file
                        List <DirectoryListItem> ftpItems = client.GetDirectoryList().ToList();
                        LogMsg("GetXMLFile - Current Sale");

                        largest = 0;
                        foreach (DirectoryListItem FtpItem in ftpItems)
                        {
                            if (FtpItem.Name.IndexOf(saleid.ToString()) == 0)
                            {
                                ulong?size = client.GetFileTransferSize(FtpItem.Name);
                                if (size > largest)
                                {
                                    thisone = FtpItem.Name;
                                    largest = size;
                                }
                            }
                        }
                    }

                    LogMsg("GetXMLFile - getting " + thisone + " into " + directory + thisone);

                    if (thisone.Length > 0)
                    {
                        client.GetFile(thisone, directory + thisone);
                    }
                    return(directory + thisone);
                }
                catch (FTPCommandException fe)
                {
                    LogMsg(fe);
                    return("");
                }
                catch (IOException ie)
                {
                    LogMsg(ie);
                    return("");
                }
                catch (IndexOutOfRangeException ie)
                {
                    LogMsg(ie);
                    return("");
                }
            }
        }
Exemple #20
0
        private static void DoConnect(FTPSClient client)
        {
            WriteCredentialsEncryptionWarning();

            CheckPassword();

            int port = options.port;
            if (port == 0)
                port = (options.sslRequestSupportMode & ESSLSupportMode.Implicit) == ESSLSupportMode.Implicit ? 990 : 21;

            NetworkCredential credential = null;
            if (options.userName != null && options.userName.Length > 0)
                credential = new NetworkCredential(options.userName, options.password);

            X509Certificate x509ClientCert = null;
            if (options.sslClientCertPath != null)
                x509ClientCert = X509Certificate.CreateFromCertFile(options.sslClientCertPath);

            client.Connect(options.hostName, port,
                           credential,
                           options.sslRequestSupportMode,
                           new RemoteCertificateValidationCallback(ValidateTestServerCertificate),
                           x509ClientCert,
                           options.sslMinKeyExchangeAlgStrength,
                           options.sslMinCipherAlgStrength,
                           options.sslMinHashAlgStrength,
                           options.timeout * 1000,
                           options.useCtrlEndPointAddressForData,
                           options.dataConnectionMode);

            // client.Connect already sets binary by default
            if (options.transferMode != ETransferMode.Binary)
                client.SetTransferMode(options.transferMode);

            WriteConnectionInfo(client);

            WriteSslStatus(client);
        }
Exemple #21
0
        public static bool GetCurrentRecords(string Server, string SignalId, string User, string Password,
                                             string LocalDir, string RemoteDir, bool DeleteFilesAfterFTP, int SNMPRetry, int SNMPTimeout, int SNMPPort,
                                             bool ImportAfterFTP, bool activemode, int waitbetweenrecords, BulkCopyOptions Options,
                                             int FTPTimeout) //, CancellationToken Token)
        {
            var recordsComplete = false;

            var errorRepository = ApplicationEventRepositoryFactory.Create();


            //Initialize the FTP object
            var RetryFiles = new List <string>();
            var FTP        = new FTPSClient();
            var Cred       = new NetworkCredential(User, Password);
            var SSLMode    = ESSLSupportMode.ClearText;
            var DM         = EDataConnectionMode.Passive;

            if (activemode)
            {
                DM = EDataConnectionMode.Active;
            }


            var connected   = false;
            var FilePattern = ".dat";


            try
            {
                try
                {
                    var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                    var token2      = tokenSource.Token;

                    Task task = Task.Factory.StartNew(
                        () => FTP.Connect(Server, 21, Cred, SSLMode, null, null, 0, 0, 0, FTPTimeout, true, DM)
                        , token2);

                    task.Wait(token2);

                    if (token2.IsCancellationRequested)
                    {
                        token2.ThrowIfCancellationRequested();
                    }
                }
                catch (AggregateException)
                {
                    errorRepository.QuickAdd("FTPFromAllcontrollers", "Signal", "ConnectToController",
                                             ApplicationEvent.SeverityLevels.Medium, "The connection task timed out for signal " + Server);
                }
                {
                    Console.WriteLine("Connection Failure");
                }

                connected = true;
            }
            //If there is an error, Print the error and go on to the next file.
            catch (FTPException ex)
            {
                errorRepository.QuickAdd("FTPFromAllcontrollers", "Signal", "ConnectToController",
                                         ApplicationEvent.SeverityLevels.Medium, Server + " " + ex.Message);
                Console.WriteLine(ex.Message);
            }
            catch (AggregateException)
            {
                Console.WriteLine("Connection Failure");
            }

            catch (SocketException ex)
            {
                errorRepository.QuickAdd("FTPFromAllcontrollers", "Signal", "ConnectToController",
                                         ApplicationEvent.SeverityLevels.Medium, Server + " " + ex.Message);
                Console.WriteLine(ex.Message);
            }
            catch (IOException ex)
            {
                errorRepository.QuickAdd("FTPFromAllcontrollers", "Signal", "ConnectToController",
                                         ApplicationEvent.SeverityLevels.Medium, Server + " " + ex.Message);
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                errorRepository.QuickAdd("FTPFromAllcontrollers", "Signal", "ConnectToController",
                                         ApplicationEvent.SeverityLevels.Medium, Server + " " + ex.Message);
                Console.WriteLine(ex.Message);
            }

            if (connected)
            {
                try
                {
                    //if (Token.IsCancellationRequested)
                    //{
                    //    Token.ThrowIfCancellationRequested();
                    //}

                    FTP.SetCurrentDirectory("..");


                    FTP.SetCurrentDirectory(RemoteDir);
                }
                catch (AggregateException)
                {
                    Console.WriteLine("Connection Failure for " + Server);
                }

                catch (Exception ex)
                {
                    errorRepository.QuickAdd("FTPFromAllcontrollers", "Signal", "GetCurrentRecords",
                                             ApplicationEvent.SeverityLevels.Medium, Server + " " + ex.Message);
                    Console.WriteLine(ex.Message);
                }


                try
                {
                    IList <DirectoryListItem> RemoteFiles = null;
                    var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                    var token       = tokenSource.Token;

                    Task task = Task.Factory.StartNew(() => RemoteFiles = FTP.GetDirectoryList(RemoteDir)
                                                      , token);

                    task.Wait(token);

                    if (token.IsCancellationRequested)
                    {
                        token.ThrowIfCancellationRequested();
                    }

                    var RetrievedFiles = new List <string>();


                    //errorRepository.QuickAdd("FTPFromAllcontrollers","Signal", "GetFTPFileList", Models.ApplicationEvent.SeverityLevels.Information, "Retrevied File list from " + Server);
                    if (RemoteFiles != null)
                    {
                        foreach (var FTPFile in RemoteFiles)
                        {
                            if (!FTPFile.IsDirectory && FTPFile.Name.Contains(FilePattern))
                            {
                                try
                                {
                                    //if (Token.IsCancellationRequested)
                                    //{
                                    //    Token.ThrowIfCancellationRequested();
                                    //}

                                    //If there are no errors, get the file, and add the filename to the retrieved files array for deletion later


                                    var token2 = tokenSource.Token;

                                    var task2 = Task.Factory.StartNew(
                                        () => TransferFiles(FTP, FTPFile.Name, LocalDir, RemoteDir, Server)
                                        , token2);

                                    task2.Wait(token2);

                                    if (token2.IsCancellationRequested)
                                    {
                                        token2.ThrowIfCancellationRequested();
                                    }
                                    else
                                    {
                                        RetrievedFiles.Add(FTPFile.Name);

                                        recordsComplete = true;
                                    }
                                }
                                //If there is an error, Print the error and try the file again.
                                catch (AggregateException)
                                {
                                    errorRepository.QuickAdd("FTPFromAllcontrollers", "Signal", "TransferFiles",
                                                             ApplicationEvent.SeverityLevels.Medium, "Transfer Task Timed Out");
                                }
                                catch (Exception ex)
                                {
                                    var errorMessage = "Exception:" + ex.Message + " While Transfering file: " +
                                                       FTPFile + " from " + RemoteDir + " on " + Server + " to " +
                                                       LocalDir;
                                    Console.WriteLine(errorMessage);
                                    errorRepository.QuickAdd("FTPFromAllcontrollers", "Signal", "TransferFiles",
                                                             ApplicationEvent.SeverityLevels.Medium, errorMessage);
                                    RetryFiles.Add(FTPFile.Name);
                                }
                                Thread.Sleep(waitbetweenrecords);
                            }
                        }
                    }

                    //Delete the files we downloaded.  We don't want ot have to deal with the file more than once.  If we delete the file form the controller once we capture it, it will reduce redundancy.


                    if (DeleteFilesAfterFTP)
                    {
                        DeleteFilesFromFTPServer(FTP, RetrievedFiles, waitbetweenrecords, RemoteDir,
                                                 Server); //, Token);
                    }
                }

                catch (Exception ex)
                {
                    errorRepository.QuickAdd("FTPFromAllcontrollers", "Signal", "RetrieveFiles",
                                             ApplicationEvent.SeverityLevels.Medium, Server + " " + ex.Message);
                    Console.WriteLine(ex.Message);
                }


                FTP.Close();
                FTP.Dispose();

                //**********************************************************
                //I don't think this is doing much good. -SJ 11-22-2016

                //Try to get the missing files again with a new FTP connection

                //if (RetryFiles.Count > 1)
                //{

                //    foreach (string FTPFile in RetryFiles)
                //    {
                //        try
                //        {

                //            Thread.Sleep(waitbetweenrecords);

                //            FTPSClient _FTP = new FTPSClient();
                //            _FTP.Connect(Server, 21, Cred, SSLMode, null, null, 0, 0, 0, 6000, false, DM);

                //            TransferFiles(_FTP, FTPFile, LocalDir, RemoteDir, Server);


                //            if (DeleteFilesAfterFTP)
                //            {
                //                try
                //                {
                //                    _FTP.DeleteFile(FTPFile);
                //                }
                //                catch (Exception ex)
                //                {
                //                    Console.WriteLine("Exception:" + ex.Message + " While Deleting file: " + FTPFile + " from " + RemoteDir + " on " + Server + " to " + LocalDir);

                //                }
                //            }
                //            _FTP.Close();
                //            _FTP.Dispose();


                //        }
                //        //If there is an error, Print the error and move on.
                //        catch (Exception ex1)
                //        {
                //            Console.WriteLine("Exception:" + ex1.Message + " While Transfering file: " + FTPFile + " from " + RemoteDir + " on " + Server + " to " + LocalDir);
                //        }

                //    }

                // }


                // RetryFiles.Clear();
                //**************************************

                //Turn Logging off.
                //The ASC3 controller stoploggin if the current file is removed.  to make sure logging comtinues, we must turn the loggin feature off on the
                //controller, then turn it back on.
                try
                {
                    TurnOffASC3LoggingOverSNMP(SNMPRetry, SNMPPort, SNMPTimeout, Server);

                    Thread.Sleep(SNMPTimeout);


                    TurnOnASC3LoggingOverSNMP(SNMPRetry, SNMPPort, SNMPTimeout, Server);
                }
                catch
                {
                }
            }
            return(recordsComplete);
        }
Exemple #22
0
        internal static long GetLatestSaleNo()
        {
            string   Host     = null;
            Int32    Port     = 0;
            string   Username = null;
            string   Password = null;
            DateTime Latest   = Convert.ToDateTime("1/1/1970");

            Host     = "192.168.44.40";
            Username = "******";
            Password = "******";
            Port     = 990;

            long saleNo = 0;

            Console.WriteLine("Opening ftp connection");

            // Download the XML transcript and pop it into AMS...
            using (FTPSClient client = new FTPSClient())
            {
                try
                {
                    client.Connect(Host, Port,
                                   new NetworkCredential(Username,
                                                         Password),
                                   ESSLSupportMode.CredentialsRequired | ESSLSupportMode.DataChannelRequested | ESSLSupportMode.Implicit,
                                   new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications),
                                   new System.Security.Cryptography.X509Certificates.X509Certificate(),
                                   0, 0, 0, 60000, true);
                    LogMsg("GetLatestSaleNo - FTP Connected ");
                    Console.WriteLine("FTP connected");
                }
                catch (FTPCommandException fe)
                {
                    LogMsg(fe);
                    return(0);
                }
                catch (IOException ie)
                {
                    LogMsg(ie);
                    return(0);
                }
                catch (SocketException ie)
                {
                    LogMsg(ie);
                    return(0);
                }

                try
                {
                    // Change to Transaction log directory
                    String pwd = client.GetCurrentDirectory();
                    client.SetCurrentDirectory("TransactionLogs");
                }
                catch (FTPCommandException fe)
                {
                    LogMsg(fe);
                    return(0);
                }

                try
                {
                    {
                        Console.WriteLine("Find latest file");

                        // Find latest file
                        List <DirectoryListItem> ftpItems = client.GetDirectoryList().ToList();

                        string lastFile = "";
                        // Find latest file
                        foreach (DirectoryListItem FtpItem in ftpItems)
                        {
                            if (FtpItem.Name.CompareTo(lastFile) > 0)
                            {
                                lastFile = FtpItem.Name;
                            }
                        }

                        Console.WriteLine("GetLatestSaleNo " + lastFile);
                        if (lastFile != null)
                        {
                            saleNo = Convert.ToInt64(lastFile.Substring(0, 4));
                        }

                        LogMsg("GetLatestSaleNo " + saleNo);
                        Console.WriteLine("GetLatestSaleNo " + saleNo);
                    }

                    return(saleNo);
                    //return (4800);
                }
                catch (FTPCommandException fe)
                {
                    LogMsg(fe);
                    return(0);
                }
                catch (IOException ie)
                {
                    LogMsg(ie);
                    return(0);
                }
                catch (IndexOutOfRangeException ie)
                {
                    LogMsg(ie);
                    return(0);
                }
            }
        }