コード例 #1
1
        private static void TestFtp(ConnectionTester connectionTesterWindow, FtpUploader command)
        {
            connectionTesterWindow.StatusText = string.Format("Testing FTP connection to {0}...", command.Host);
            connectionTesterWindow.TryStatus = TryStatus.Trying;

            using (var client = new FTPSClient()) {
                try {
                    const int timeout = 20 * 1000;

                    client.Connect(command.Host, command.Port, new NetworkCredential(command.UserName, command.Password), 0, null, null, 0, 0, 0, timeout);
                } catch (TimeoutException) {
                    connectionTesterWindow.StatusText = "Connection timed out";
                    connectionTesterWindow.TryStatus = TryStatus.Failure;

                    return;
                } catch (Exception e) {
                    connectionTesterWindow.StatusText = string.Format("Connection to FTP server failed: {0}", e.Message);
                    connectionTesterWindow.TryStatus = TryStatus.Failure;

                    return;
                }

                connectionTesterWindow.StatusText = "Connection successful";
                connectionTesterWindow.TryStatus = TryStatus.Success;
            }
        }
コード例 #2
0
ファイル: DokanFtpClient.cs プロジェクト: forger/MountFTP
        internal DokanFtpClient(FTPSClient fTPSClient, IFtpOptions ftpOptions)
        {
            this.fTPSClient = fTPSClient;
            this.ftpOptions = ftpOptions;

            const string ROOT = "\\";
            cachedDirectoryFileInformation.Add(
                ROOT,
                new DirectoryFileInformation(true)
                {
                    FileName = ROOT
                });

            this.fTPSClient.Connect(
                ftpOptions.HostName,
                new NetworkCredential(ftpOptions.UserName, ftpOptions.Password),
                ESSLSupportMode.ClearText);

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    fTPSClientTaskQueue.Take().RunSynchronously();
                }
            });
        }
コード例 #3
0
 public FtpVirtualPathProvider(FTPSClient client, string host, int? port, string username, string password)
 {
     this.Client = client;
     this.Host = host;
     this.Username = username;
     this.Password = password;
     this.Port = port;
 }
コード例 #4
0
ファイル: Upload.cs プロジェクト: mard/Uploader
        //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);
                //}
            }
        }
コード例 #5
0
ファイル: Repository.cs プロジェクト: ralfw/appzwitschern
        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);
        }
コード例 #6
0
ファイル: Transmitter.cs プロジェクト: abhinavc/scanbotOnWin
        public static void start()
        {
            DirectoryInfo  within = new DirectoryInfo (source);
             FileInfo[]     files = within.GetFiles ();
             int            nFiles = files.Length,index = 0;
             float          fraction = 0;
             Credentials    credentials = new Credentials ();

             string target = credentials.bankRelPath + "/staging/";

             FTPSClient client = new FTPSClient ();
             client.Connect (credentials.ftpServer,
                         new NetworkCredential (credentials.username, credentials.password),
                         ESSLSupportMode.CredentialsRequested);

             client.SetTransferMode (ETransferMode.Binary);

             foreach (FileInfo f in files) {
            index += 1;
            fraction = ((float)index) / nFiles;
            try {
               client.PutFile (f.FullName, target + f.Name);
            } catch {
               // Console.WriteLine (" -- putfile exception");
               client.Close ();
               client = new FTPSClient ();
               client.Connect (credentials.ftpServer,
                         new NetworkCredential (credentials.username, credentials.password),
                         ESSLSupportMode.CredentialsRequested);
               client.SetTransferMode (ETransferMode.Binary);
               client.PutFile (f.FullName, target + f.Name);
            }
            Gtk.Application.Invoke (delegate {
               MainClass.getAppWindow ().getTransmissionPBar ().Fraction = fraction;});
            f.Delete() ; // delete the file from within .resolved/
             }
             client.Close ();

             Gtk.Application.Invoke (delegate {
            MainClass.doneTransmitting ();
            MainClass.resetDisplay (); });
        }
コード例 #7
0
        public void GetFilesWithFTPNewMode(string host, string remoteLocation)
        {
            FTPSClient client = new FTPSClient();
            try {
                client.Connect(host,ESSLSupportMode.All);
                try {
                    client.SetCurrentDirectory(remoteLocation);
                    ScriptName = client.GetCurrentDirectory();
                    string localDownloadDirectory = downloadDir + ScriptName;

                    client.GetFiles(localDownloadDirectory, "*.log", EPatternStyle.Wildcard, false);

                } catch (Exception ex) {

                }
            } finally {
                client.Close();
                client.Dispose();
            }
        }
コード例 #8
0
ファイル: Drive.cs プロジェクト: forger/MountFTP
        /// <summary>
        /// Mounts the <see cref="Drive"/>.
        /// </summary>
        /// <returns></returns>
        public string Mount()
        {
            string result;

            var fTPSClient = new FTPSClient();
            fTPSClient.LogCommand += new LogCommandEventHandler(OnFTPSClientLogCommand);
            fTPSClient.LogServerReply += new LogServerReplyEventHandler(OnFTPSClientLogServerReply);

            var dokanFtpClient = new DokanFtpClient(fTPSClient, options);
            dokanFtpClient.MethodCall += new LogEventHandler(OnFtpClientMethodCall);
            dokanFtpClient.Debug += new LogEventHandler(OnFtpClientDebug);

            var status = DokanNet.DokanMain(options.GetDokanOptions(), dokanFtpClient);
            switch (status)
            {
                case DokanNet.DOKAN_DRIVE_LETTER_ERROR:
                    result = "Drive letter error";
                    break;
                case DokanNet.DOKAN_DRIVER_INSTALL_ERROR:
                    result = "Driver install error";
                    break;
                case DokanNet.DOKAN_MOUNT_ERROR:
                    result = "Mount error";
                    break;
                case DokanNet.DOKAN_START_ERROR:
                    result = "Start error";
                    break;
                case DokanNet.DOKAN_ERROR:
                    result = "Unknown error";
                    break;
                case DokanNet.DOKAN_SUCCESS:
                    result = "Success";
                    break;
                default:
                    result = string.Format("Unknown status: %d", status);
                    break;
            }

            return result;
        }
コード例 #9
0
ファイル: Manifest.cs プロジェクト: abhinavc/scanbotOnWin
        public static bool load(string qrc)
        {
            // qrc for the just detected QR Code
             string   manifest = qrc.Substring(0,6) ;

             if (Folder.GetFiles(manifest).Length == 0) { // manifest not present locally
            Credentials   credentials = new Credentials() ;
            FTPSClient  ftp = new FTPSClient() ;

            ftp.Connect(credentials.ftpServer,
               new NetworkCredential(credentials.username, credentials.password),
               ESSLSupportMode.CredentialsRequested) ;
            ftp.GetFile(credentials.bankRelPath + "/atm/" + manifest + "/keyFile",
                        Folder.FullName + Path.DirectorySeparatorChar + manifest) ;
            ftp.Close() ;
             }

             FileInfo[]  m = Folder.GetFiles(manifest) ; // there should be just one
             foreach (FileInfo f in m) Manifest.load(f) ;

             return true ;
        }
コード例 #10
0
ファイル: FtpUploader.cs プロジェクト: strager/NoCap
        private void UploadData(Stream stream, string fileName, IMutableProgressTracker progress, CancellationToken cancelToken)
        {
            using (var client = new FTPSClient()) {
                try {
                    progress.Status = "Connecting to FTP";

                    client.Connect(Host, Port, new NetworkCredential(UserName, Password), 0, null, null, 0, 0, 0, Timeout);
                } catch (TimeoutException e) {
                    throw new CommandCanceledException(this, "Connection to FTP server timed out", e);
                } catch (IOException e) {
                    throw new CommandCanceledException(this, "Connection to FTP server failed", e);
                }

                using (var outStream = client.PutFile(GetRemotePathName(fileName)))
                using (var outStreamWrapper = new ProgressTrackingStreamWrapper(outStream, stream.Length)) {
                    outStreamWrapper.BindTo(progress);

                    progress.Status = "Uploading file to FTP";

                    stream.CopyTo(outStreamWrapper, cancelToken);
                }
            }
        }
コード例 #11
0
ファイル: Upload.cs プロジェクト: mard/Uploader
 private static void TransferCallback(FTPSClient sender, ETransferActions action, string localObjectName, string remoteObjectName, ulong fileTransmittedBytes, ulong? fileTransferSize, ref bool cancel)
 {
     switch (action)
     {
         case ETransferActions.FileDownloaded:
         case ETransferActions.FileUploaded:
             //OnFileTransferCompleted(fileTransmittedBytes, fileTransferSize);
             break;
         case ETransferActions.FileDownloadingStatus:
         case ETransferActions.FileUploadingStatus:
             //OnFileTransferStatus(action, localObjectName, remoteObjectName, fileTransmittedBytes, fileTransferSize);
             break;
         case ETransferActions.RemoteDirectoryCreated:
             //if (options.verbose)
             {
                 Console.WriteLine();
                 Console.WriteLine("Remote directory created: " + remoteObjectName);
             }
             break;
         case ETransferActions.LocalDirectoryCreated:
             //if (options.verbose)
             {
                 Console.WriteLine();
                 Console.WriteLine("Local directory created: " + localObjectName);
             }
             break;
     }
 }
コード例 #12
0
        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
                };
            }
        }
コード例 #13
0
        static void ListFiles(FTPSClient client)
        {
            IList<DirectoryListItem> list = null;

            try
            {
                list = client.GetDirectoryList();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (list != null)
            {
                var items = list.Where(x => !x.IsDirectory && x.Name.EndsWith("xml", StringComparison.CurrentCultureIgnoreCase));

                foreach (var item in items)
                {
                    Console.WriteLine(item.Name.Substring(0, item.Name.LastIndexOf(".")));
                }
            }
        }
コード例 #14
0
        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();
            }
        }
コード例 #15
0
        /// <summary>
        /// FTPS procedure to upload or download files
        /// </summary>
        /// <param name="blShuttingDown"></param>
        public void FTPs(ref bool blShuttingDown)
        {
            FTPSClient FTPS = null;
            bool blFileFound = false;
            bool blOverwriteFile = false;
            try
            {
                FTPS = new FTPSClient();
                AES256 aes = new AES256(ep);
                string upassword = aes.Decrypt(_password);

                if (Protocol == ProtocolOptions.FTP)
                {
                    FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.ClearText, null, null, 0, 0, 0, Timeout);
                }
                else
                {
                    if (AllowAnyCertificate)
                    {
                        if (Protocol == ProtocolOptions.FTPsExplicit)
                        {
                            FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.CredentialsRequired | ESSLSupportMode.DataChannelRequested, new RemoteCertificateValidationCallback(ValidateTestServerCertificate), null, 0, 0, 0, Timeout);

                        }
                        else
                        {
                            FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.Implicit, new RemoteCertificateValidationCallback(ValidateTestServerCertificate), null, 0, 0, 0, Timeout);

                        }

                    }
                    else
                    {
                        if (Protocol == ProtocolOptions.FTPsExplicit)
                        {
                            FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.CredentialsRequired | ESSLSupportMode.DataChannelRequested, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, 0, 0, 0, Timeout);
                        }
                        else
                        {
                            FTPS.Connect(Host, Port, new NetworkCredential(Username, upassword), ESSLSupportMode.Implicit, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, 0, 0, 0, Timeout);
                        }
                    }
                }

                _evt.WriteEntry("Remote Sync: FTPS Connected Successfully to: " + Host, System.Diagnostics.EventLogEntryType.Information, 2005, 20);

                upassword = "";
                switch (TransferDirection)
                {
                    case TransferDirectionOptions.Upload:
                        BackupFolder = BackupFolder.Replace("\\\\", "\\");
                        IList<DirectoryListItem> RemoteFilesU=null;

                        try
                        {
                            FTPS.SetCurrentDirectory(RemoteDirectory);
                            RemoteFilesU = FTPS.GetDirectoryList();
                            UploadFiles = Common.WalkDirectory(BackupFolder, ref blShuttingDown, FileNameFilter);

                            //CreateRemote Directories
                            foreach (DirectoryInfo dir in Common.GetAllDirectories(BackupFolder))
                            {
                                string strRemotePath = "";
                                strRemotePath=Common.RemotePathCombine(RemoteDirectory, dir.FullName, BackupFolder);
                                if (blShuttingDown)
                                {
                                    throw new Exception("Shutting Down");
                                }

                                if (blShuttingDown)
                                {

                                    _evt.WriteEntry("Remote Sync: Shutting down about to possibly create a folder on Host: " + Host + " Folder: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 2040, 20);
                                    return;
                                }

                                try
                                {
                                    FTPS.MakeDir(strRemotePath);
                                    _evt.WriteEntry("Remote Sync: Folder Created on " + Host + " : " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 2040, 20);
                                }
                                catch (Exception)
                                {
                                }

                                //FTPS.SetCurrentDirectory(strRemotePath);
                            }

                            //Upload Each File
                            foreach (FileInfo fileU in UploadFiles)
                            {
                                if (blShuttingDown)
                                {
                                    throw new Exception("Shutting Down");
                                }
                                try
                                {
                                    string strRemotePath = "";

                                    strRemotePath = Common.RemotePathCombine(RemoteDirectory, fileU.DirectoryName, BackupFolder);
                                    strRemotePath = Common.RemotePathCombine(strRemotePath, fileU.Name);

                                    blFileFound = false;
                                    blOverwriteFile = false;
                                    try
                                    {

                                        if (FTPS.GetFileTransferSize(strRemotePath) > 0)
                                        {
                                            blFileFound = true;
                                            if (!(/*(fileU.LastAccessTimeUtc == FTPS.GetFileModificationTime(strRemotePath)) &&*/ ((ulong)fileU.Length == FTPS.GetFileTransferSize(strRemotePath))))
                                            {
                                                blOverwriteFile = true;
                                            }

                                        }
                                    }
                                    catch (Exception)
                                    {
                                        //File Not found No Action Necessary on Error
                                    }

                                    try
                                    {
                                        if (FTPS.GetFileTransferSize(strRemotePath + ".7z") > 0)
                                        {
                                            blFileFound = true;
                                            //7z file exists but there is no current way to compare the 7zipped file vs the non compressed file so the user overwrite option will force the appropriate action
                                            blOverwriteFile = true;
                                            /*
                                            if (!((fileU.LastAccessTimeUtc == FTPS.GetFileModificationTime(strRemotePath + ".7z")) && ((ulong)fileU.Length == FTPS.GetFileTransferSize(strRemotePath + ".7z"))))
                                            {
                                                blOverwriteFile = true;
                                            }
                                            */

                                        }
                                    }
                                    catch (Exception)
                                    {
                                        //File Not Found No Action Necessary on Error
                                    }
                                    if (blShuttingDown)
                                    {

                                        _evt.WriteEntry("Remote Sync FTPS: Shutting Down about to possible upload a file: " + fileU.FullName + " Host: " + Host + " To: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 2010, 20);
                                        return;
                                    }

                                    if ((!blFileFound || blOverwriteFile || (Overwrite == OverwriteOptions.ForceOverwrite && blFileFound)) && !(Overwrite == OverwriteOptions.NoOverwrite && blFileFound))
                                    {
                                        //This Uploads the file
                                        FTPS.PutFile(fileU.FullName, strRemotePath);
                                        _evt.WriteEntry("Remote Sync FTPS: File Uploaded: " + fileU.FullName + " Host: " + Host + " To: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 2010, 20);

                                    }

                                }
                                catch (Exception exp)
                                {
                                    _evt.WriteEntry("Remote Sync FTPS: Host:" + Host + " Upload FileName: " + fileU.FullName + " Error: " + exp.Message, System.Diagnostics.EventLogEntryType.Error, 2010, 20);
                                }

                            }
                        }
                        catch (Exception exu)
                        {
                            _evt.WriteEntry("Remote Sync FTPS: Upload Error on Host:" + Host + " Error: " + exu.Message, System.Diagnostics.EventLogEntryType.Error, 2010, 20);
                        }
                        finally
                        {
                            if (RemoteFilesU != null)
                            {
                                RemoteFilesU.Clear();
                            }
                            if (UploadFiles != null)
                            {
                                UploadFiles.Clear();
                            }
                            RemoteFilesU = null;
                            UploadFiles = null;

                        }
                        break;
                    case TransferDirectionOptions.Download:

                        List<RemoteFile> RemoteFilesD=null;

                        try
                        {
                            FTPS.SetCurrentDirectory(RemoteDirectory);
                            RemoteFilesD = Common.GetRemoteDirectories(RemoteDirectory, FTPS, "");
                            Common.CreateLocalFolderStructure(RemoteFilesD, BackupFolder);
                            foreach (RemoteFile FileD in RemoteFilesD)
                            {
                                string strLocalFile = "";
                                string strRemoteFile = "";

                                if (blShuttingDown)
                                {
                                    throw new Exception("Shutting Down");
                                }
                                try
                                {
                                    if (!FileD.IsDirectory)
                                    {

                                        strLocalFile = Common.WindowsPathCombine(BackupFolder, FileD.ParentDirectory);
                                        strLocalFile = Common.WindowsPathCombine(strLocalFile, FileD.Name);
                                        strRemoteFile = FileD.FullName;

                                        if (Common.DownloadFile(strLocalFile, strRemoteFile, FileD, Overwrite))
                                        {
                                            if ((!blFileFound || blOverwriteFile || (Overwrite == OverwriteOptions.ForceOverwrite && blFileFound)) && !(Overwrite == OverwriteOptions.NoOverwrite && blFileFound))
                                            {
                                                if (Common.FixNullstring(FileNameFilter) != "" && Common.VerifyPattern(FileNameFilter))
                                                {
                                                    if (Common.FileNameMatchesPattern(FileNameFilter, FileD.Name))
                                                    {
                                                        FTPS.GetFile(strRemoteFile, strLocalFile);
                                                        _evt.WriteEntry("Remote Sync FTPS: File Downloaded: " + strRemoteFile + " Host: " + Host + " To: " + strLocalFile, System.Diagnostics.EventLogEntryType.Information, 2020, 20);
                                                    }
                                                }
                                                else
                                                {
                                                    FTPS.GetFile(strRemoteFile, strLocalFile);
                                                    _evt.WriteEntry("Remote Sync FTPS: File Downloaded: " + strRemoteFile + " Host: " + Host + " To: " + strLocalFile, System.Diagnostics.EventLogEntryType.Information, 2020, 20);
                                                }
                                            }

                                        }

                                    }
                                }
                                catch (Exception exdi)
                                {
                                    _evt.WriteEntry("Remote Sync FTPS: File Download Error: " + strRemoteFile + " Host: " + Host + " To: " + strLocalFile + " Error: " + exdi.Message, System.Diagnostics.EventLogEntryType.Error, 2020, 20);
                                }

                            }
                        }
                        catch (Exception exd)
                        {
                            _evt.WriteEntry("Remote Sync FTPS: Download Error: Host: " + Host + " Error: " + exd.Message, System.Diagnostics.EventLogEntryType.Error, 2020, 20);
                        }
                        finally
                        {
                            if (RemoteFilesD !=null)
                            {
                                RemoteFilesD.Clear();
                            }
                            RemoteFilesD = null;
                        }
                        break;

                }
            }
            catch (Exception ex)
            {
                _evt.WriteEntry("Remote Sync FTPS: Error: Host: " + Host + " Error: " + ex.Message, System.Diagnostics.EventLogEntryType.Error, 2000, 20);
            }
            finally
            {
                if (FTPS != null)
                {
                    try
                    {
                        FTPS.Close();
                    }
                    catch (Exception)
                    {

                    }

                    FTPS.Dispose();

                }
                FTPS = null;
            }
        }
コード例 #16
0
        static void GetFile(FTPSClient client, string packageName)
        {
            packageName += ".zip"; // add .zip so we get the full file name

            //Console.WriteLine(packageName);

            string tempFolder = Environment.GetEnvironmentVariable("TEMP");

            string destinationFile = string.Format("{0}\\{1}", tempFolder, packageName);

            //Console.WriteLine(destinationFile);

            try
            {
                client.GetFile(packageName, destinationFile);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #17
0
 /// <summary>
 /// Initialises a new instance of the <see cref="FtpMessageSender"/> class.
 /// </summary>
 /// <param name="client">An object to communicate over FTP.</param>
 public FtpMessageSender(FTPSClient client)
 {
     this._ftpClient = client;
 }
コード例 #18
0
ファイル: Transmitter.cs プロジェクト: abhinavc/Scanbot-WF
        public static void start()
        {
            DirectoryInfo within = new DirectoryInfo(source);
              FileInfo[] files = within.GetFiles();
              int nFiles = files.Length, processed = 0;
              int percentDone = 0;
              Credentials credentials = new Credentials();

              string target = credentials.target + "/staging/";
              Stopwatch stopWatch = new Stopwatch();
              FTPSClient client = new FTPSClient();
              string welcomeMsg = null;

              System.Diagnostics.Debug.WriteLine("[Transmitter]: Thread start()");

              try {
            welcomeMsg = client.Connect(credentials.ftpServer,
                    new NetworkCredential(credentials.username, credentials.password),
                    ESSLSupportMode.CredentialsRequested);
              } catch (SocketException e) {
            Program.Gui.Invoke((MethodInvoker)(delegate {
              Program.EstTransmission.Text = "No Net?";
              Label noNet = Program.Gui.NetConnectionStatus;

              noNet.Text = "Just make sure you're connected to the Net. I will try again later";
              noNet.Visible = true;
            }));
            client.Close();
            return;
              }

              // Have net ... Try logging in to FTP server

              if (welcomeMsg.StartsWith("Login successful")) {
            Program.Gui.Invoke((MethodInvoker)(delegate {
              Program.EstTransmission.Text = "Connected";
              Program.Gui.NetConnectionStatus.Visible = false;
            }));
              } else {
            Program.Gui.Invoke((MethodInvoker)(delegate {
              Program.EstTransmission.Text = "Couldn't login";
              Label noNet = Program.Gui.NetConnectionStatus;

              noNet.Text = "Happens sometimes. Not to worry. I will try again later";
              noNet.Visible = true;
            }));
            client.Close();
            return;
              }

              // Otherwise, we are good to go
              client.SetTransferMode(ETransferMode.Binary);
              stopWatch.Start();

              foreach (FileInfo f in files) {
            if (!Program.GuiAlive) {
              System.Diagnostics.Debug.WriteLine("[Transmitter]: Gui Dead!!");
              break;
            }

            ulong bytesSent = 0;
            ulong size = (ulong)f.Length;

            try {
              bytesSent = client.PutFile(f.FullName, target + f.Name);
            } catch {
              // Console.WriteLine (" -- putfile exception");
              client.Close();
              client = new FTPSClient();
              client.Connect(credentials.ftpServer,
                    new NetworkCredential(credentials.username, credentials.password),
                    ESSLSupportMode.CredentialsRequested);
              client.SetTransferMode(ETransferMode.Binary);
              bytesSent = client.PutFile(f.FullName, target + f.Name);
            }
            processed += 1;
            percentDone = (int)((processed * 100) / nFiles); // percentage

            TimeSpan elapsed = stopWatch.Elapsed;
            string estimate = Program.EstTimeToCompletion(elapsed, processed, nFiles);

            // Update the transmission progress bar
            if (Program.GuiAlive) {
              Program.Gui.Invoke((MethodInvoker)(delegate {
            Program.TransmissionBar.Value = percentDone;
            Program.EstTransmission.Text = estimate;
              }));
            }

            if (bytesSent == size)
              f.Delete();
            // delete file from .resolved/ only if it was transferred completely
              }

              stopWatch.Stop();
              client.Close();
              System.Diagnostics.Debug.WriteLine("[Transmitter]: Thread end()");

              if (Program.GuiAlive) {
            Program.Gui.Invoke((MethodInvoker)(delegate {
              Program.DoneTransmitting();
              Program.ResetDisplay();
            }));
              }
        }
コード例 #19
0
        static void ImportPackage(FTPSClient client, string packageName)
        {
            packageName += ".zip"; // add .zip so we get the full file name

            //var c = new EASBackend.ServiceSoapClient();

            //            c.ImportApplication();
        }
コード例 #20
0
ファイル: Manifest.cs プロジェクト: abhinavc/Scanbot-WF
        public static bool load(string qrc)
        {
            // qrc for the just detected QR Code
              mutex.WaitOne();

              string manifest = qrc.Substring(0, 6);
              bool sthLoaded = false;

              if (Folder.GetFiles(manifest).Length == 0) { // manifest not present locally
            Credentials credentials = new Credentials();
            FTPSClient ftp = new FTPSClient();

            ftp.Connect(credentials.ftpServer,
               new NetworkCredential(credentials.username, credentials.password),
               ESSLSupportMode.CredentialsRequested);
            ftp.GetFile(credentials.root + "/atm/" + manifest + "/keyFile",
                    Folder.FullName + Path.DirectorySeparatorChar + manifest);
            ftp.Close();
              }

              FileInfo[] m = Folder.GetFiles(manifest); // there should be just one
              foreach (FileInfo f in m)
            sthLoaded |= Manifest.load(f); // returns false if manifest already in DOM

              mutex.ReleaseMutex();
              return sthLoaded;
        }
コード例 #21
0
        static void Main(string[] args)
        {
            foreach (string arg in args)
            {
                // display help
                if (arg.Equals("/?", StringComparison.CurrentCultureIgnoreCase) | arg.Equals("/help", StringComparison.CurrentCultureIgnoreCase))
                {
                    DisplayHelp();
                }

                // switches
                if (arg.StartsWith("-"))
                {
                    if (arg.Equals("-list", StringComparison.CurrentCultureIgnoreCase))
                    {
                        _command = "list";
                    }

                    if (arg.Equals("-get", StringComparison.CurrentCultureIgnoreCase))
                    {
                        _command = "get";
                    }

                    if (arg.Equals("-import", StringComparison.CurrentCultureIgnoreCase))
                    {
                        _command = "import";
                    }
                }
                else if (arg.StartsWith("/"))
                {
                    if (arg.Contains(":"))
                    {
                        string key = arg.Split(':')[0];
                        string value = arg.Split(':')[1];

                        switch (key.ToLower())
                        {
                            case "host":
                                _host = value;

                                break;
                            case "port":
                                _port = int.Parse(value);

                                break;
                            case "username":
                                _username = value;

                                break;
                            case "password":
                                _password = value;

                                break;
                        }

                        //Console.WriteLine(key);
                        //Console.WriteLine(value);
                    }
                    //else
                    //    Console.WriteLine("{arg} - Invalid parameter!");
                }
                else
                {
                    _commandArgument = arg;
                }

            }

            FTPSClient client = new FTPSClient();

            client.Connect(_host, new NetworkCredential(_username, _password), ESSLSupportMode.ClearText);

            switch (_command)
            {
                case "import":
                    ImportPackage(client, _commandArgument);

                    break;
                case "get":
                    GetFile(client, _commandArgument);

                    break;
                case "list":
                    ListFiles(client);

                    break;
                default:
                    break;
            }

            client.Close();

            Console.ReadLine();

        }
コード例 #22
0
 public string Connect(string address, NetworkCredential credentials, ESSLSupportMode esslSupportMode)
 {
     _client = new FTPSClient();
     return _client.Connect(address, credentials, esslSupportMode);
 }
コード例 #23
0
 /// <summary>
 /// Initialises a new instance of the <see cref="FtpQueueClient"/> class.
 /// </summary>
 public FtpQueueClient()
 {
     this._ftpClient = new FTPSClient();
 }