Beispiel #1
0
        public void ConstructorShouldSetProperties(string homeDirectory, int port)
        {
            var config = new FtpConfiguration(homeDirectory, port);

            config.HomeDirectory.ShouldBeEquivalentTo(homeDirectory);
            config.Port.ShouldBeEquivalentTo(port);
        }
        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
                });
            }
        }
Beispiel #3
0
 public FtpBinding(FtpConfiguration config, ParameterInfo parameter, TraceWriter trace, FtpAttribute ftpAttribute)
 {
     _config       = config;
     _parameter    = parameter;
     _trace        = trace;
     _ftpAttribute = ftpAttribute;
 }
        public void ConstructorShouldSetConfigurationProperty()
        {
            var ftpConfiguration = new FtpConfiguration("Home", 21);

            var server = new FtpServer(ftpConfiguration, new MockFileSystem(), Substitute.For <IOperatingSystem>());

            server.Configuration.ShouldBeEquivalentTo(ftpConfiguration);
        }
        public async Task <FtpMessage> GetFileAsync(FtpConfiguration config, string path)
        {
            switch (config.FtpHost.Scheme)
            {
            case "sftp":
                return(await GetFromSftp(config, path));

            case "ftps":
                return(await GetFromFtps(config, path));

            default: throw new ArgumentException("Unsupported uri scheme. Only ftps and sftp is supported.", nameof(config));
            }
        }
        public void DownloadFile(FtpConfiguration ftpConfig)
        {
            try
            {
                const int BufferSize = 2048;
                byte[]    Buffer     = new byte[BufferSize];

                FtpWebRequest  Request;
                FtpWebResponse Response;
                string         filePath = Path.Combine(ftpConfig.DownloadLocalDirectory, ftpConfig.FileName);

                if (File.Exists(filePath))
                {
                    if (ftpConfig.OverwriteExisting)
                    {
                        File.Delete(filePath);
                    }
                    else
                    {
                        //log
                        //Console.WriteLine(string.Format("File {0} already exist.", FileName));
                        return;
                    }
                }

                //Request = (FtpWebRequest)FtpWebRequest.Create(new Uri(Path.Combine(ftpConfig.FtpLocationToWatch, ftpConfig.FileName)));
                Request             = (FtpWebRequest)FtpWebRequest.Create(new Uri(Path.Combine(ftpConfig.DownloadLocalDirectory, ftpConfig.FileName)));
                Request.Credentials = new NetworkCredential(UserName, Password);
                Request.Proxy       = null;
                Request.Method      = WebRequestMethods.Ftp.DownloadFile;
                Request.UseBinary   = true;

                Response = (FtpWebResponse)Request.GetResponse();

                using (Stream s = Response.GetResponseStream())
                {
                    //using (FileStream fs = new FileStream(Path.Combine(ftpConfig.DownloadTo, ftpConfig.FileName), FileMode.CreateNew, FileAccess.ReadWrite))
                    using (FileStream fs = new FileStream(Path.Combine(ftpConfig.FtpDirecrory, ftpConfig.FileName), FileMode.CreateNew, FileAccess.ReadWrite))
                    {
                        while (s.Read(Buffer, 0, BufferSize) != -1)
                        {
                            fs.Write(Buffer, 0, BufferSize);
                        }
                    }
                }
            }
            catch { }
        }
        protected override async Task <Action <NativeActivityContext> > ExecuteAsync(NativeActivityContext context, CancellationToken cancellationToken)
        {
            IFtpSession      ftpSession       = null;
            FtpConfiguration ftpConfiguration = new FtpConfiguration(Host.Get(context));

            ftpConfiguration.Port = Port.Expression == null ? null : (int?)Port.Get(context);
            ftpConfiguration.UseAnonymousLogin         = UseAnonymousLogin;
            ftpConfiguration.SslProtocols              = SslProtocols;
            ftpConfiguration.ClientCertificatePath     = ClientCertificatePath.Get(context);
            ftpConfiguration.ClientCertificatePassword = ClientCertificatePassword.Get(context);
            ftpConfiguration.AcceptAllCertificates     = AcceptAllCertificates;

            if (ftpConfiguration.UseAnonymousLogin == false)
            {
                ftpConfiguration.Username = Username.Get(context);
                ftpConfiguration.Password = Password.Get(context);

                if (string.IsNullOrWhiteSpace(ftpConfiguration.Username))
                {
                    throw new ArgumentNullException(Resources.EmptyUsernameException);
                }

                if (string.IsNullOrWhiteSpace(ftpConfiguration.Password) && string.IsNullOrWhiteSpace(ftpConfiguration.ClientCertificatePath))
                {
                    throw new ArgumentNullException(Resources.NoValidAuthenticationMethod);
                }
            }

            if (UseSftp)
            {
                ftpSession = new SftpSession(ftpConfiguration);
            }
            else
            {
                ftpSession = new FtpSession(ftpConfiguration, FtpsMode);
            }

            await ftpSession.OpenAsync(cancellationToken);

            return((nativeActivityContext) =>
            {
                if (Body != null)
                {
                    _ftpSession = ftpSession;
                    nativeActivityContext.ScheduleAction(Body, ftpSession, OnCompleted, OnFaulted);
                }
            });
        }
        public void ConstructorShouldThrowArgumentExceptionWhenArgumentsAreInvalid(
            string expectedParameterName,
            string expectedMessage,
            Type expectedType,
            FtpConfiguration configuration)
        {
            Action constructor =
                () => new FtpServer(configuration, new MockFileSystem(), Substitute.For <IOperatingSystem>());

            constructor.ShouldThrow <ArgumentException>()
            .WithMessage(expectedMessage)
            .Where(
                exception => exception.ParamName == expectedParameterName,
                "the parameter name should be of the problematic parameter")
            .And.Should()
            .BeOfType(expectedType);
        }
Beispiel #9
0
        // PUBLIC INTERFACE METHODS SECTION
        //---------------------------------------------------------------------

        #region IGuideService members

        public GuidesCollection GetGuides()
        {
            var serviceStateAgrs = new GuideServiceEventArgs();

            FtpConfiguration    ftpConfiguration    = _ftpConfigManager.Get();
            GuidesConfiguration guidesConfiguration = _guidesConfigManager.Get();

            var ftpClient = new FtpClient(ftpConfiguration.Uri,
                                          ftpConfiguration.User, ftpConfiguration.Password);


            string[]        ftpFolderMetadata = ftpClient.GetFtpFolderMetadata();
            List <FileMeta> filesMetadata     = ParseFtpFolderMetadata(ftpFolderMetadata);

            serviceStateAgrs.Message = "Checking guides for download.";
            OnStageChanged(serviceStateAgrs);

            var isForDownload = CheckGuidesForDownload(filesMetadata, guidesConfiguration.Guides);

            if (isForDownload)
            {
                try
                {
                    serviceStateAgrs.Message = "Downloading guides.";
                    OnStageChanged(serviceStateAgrs);

                    DownloadGuides(ftpClient, filesMetadata, guidesConfiguration.Path);
                    UpdateDates(filesMetadata, guidesConfiguration);
                }
                catch (HttpListenerException ex)
                {
                    throw new RemoteServerException(ex.Message, ex);
                }
                catch (IOException ex)
                {
                    throw new FileSaveException(ex.Message, ex);
                }
            }

            serviceStateAgrs.Message = "Loading guides.";
            OnStageChanged(serviceStateAgrs);

            var guides = LoadGuides(guidesConfiguration);

            return(guides);
        }
Beispiel #10
0
        // ON EVENTS SUBSCRIBERS SECTION
        //---------------------------------------------------------------------

        #region On events subscribers

        private void OnInitializeView()
        {
            try
            {
                _ftpConfiguration = _ftpConfigurationManager.Get();

                View.FtpHost     = _ftpConfiguration.Uri;
                View.FtpPort     = _ftpConfiguration.Port;
                View.FtpUser     = _ftpConfiguration.User;
                View.FtpPassword = _ftpConfiguration.Password;
            }
            catch (RepositoryLoadException ex)
            {
                _log.Error(ex.ToString());
                View.Error = "Error on ftp configuration load :" +
                             Environment.NewLine +
                             ex.Message;
            }
        }
        /// <summary>
        /// Populates file upload path
        /// </summary>
        /// <param name="jobType">Contains which job to be executed</param>
        /// <param name="fileName">Name of file for which path is needed</param>
        /// <returns>File upload path</returns>
        public string GetFileUploadPath(string jobType, string fileName)
        {
            FtpConfiguration configType = new FtpConfiguration();

            switch (jobType.ToLower())
            {
            case "announcement":
            case "ann":
            {
                configType = _bulkUplaodRepositoy.GetFtpConfig(FtpConfigurationType.Announcement);
                break;
            }

            case "pipelineorder":
            case "po":
            {
                configType = _bulkUplaodRepositoy.GetFtpConfig(FtpConfigurationType.PipelineOrder);
                break;
            }

            case "pricereport":
            case "pr":
            {
                configType = _bulkUplaodRepositoy.GetFtpConfig(FtpConfigurationType.PriceReport);
                break;
            }

            case "qcreport":
            case "qc":
            {
                configType = _bulkUplaodRepositoy.GetFtpConfig(FtpConfigurationType.QCReport);
                break;
            }
            }
            if (!Directory.Exists(configType.DownloadLocalDirectory + configType.FtpDirecrory))
            {
                Directory.CreateDirectory(configType.DownloadLocalDirectory + configType.FtpDirecrory);
            }
            string filePath = string.Format("{0}{1}/{2}", configType.DownloadLocalDirectory, configType.FtpDirecrory, fileName);

            return(filePath);
        }
        public FtpAttributeBindingProvider(FtpConfiguration config, INameResolver nameResolver, TraceWriter trace)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (nameResolver == null)
            {
                throw new ArgumentNullException(nameof(nameResolver));
            }

            if (trace == null)
            {
                throw new ArgumentNullException(nameof(trace));
            }

            _config       = config;
            _nameResolver = nameResolver;
            _trace        = trace;
        }
        private async Task <FtpMessage> GetFromSftp(FtpConfiguration config, string path)
        {
            var host     = config.FtpHost.Host;
            var username = config.Username;
            var password = config.Password;
            var port     = config.FtpPort;

            using (var sftpClient = new SftpClient(host, port, username, password))
            {
                sftpClient.Connect();
                var data = sftpClient.ReadAllBytes(path);
                sftpClient.Disconnect();

                return(new FtpMessage
                {
                    Configuration = config,
                    Data = data,
                    Filename = path
                });
            }
        }
        protected override async Task <Action <NativeActivityContext> > ExecuteAsync(NativeActivityContext context, CancellationToken cancellationToken)
        {
            IFtpSession      ftpSession       = null;
            FtpConfiguration ftpConfiguration = new FtpConfiguration(Host.Get(context));

            ftpConfiguration.Port = Port.Expression == null ? null : (int?)Port.Get(context);
            ftpConfiguration.UseAnonymousLogin         = UseAnonymousLogin;
            ftpConfiguration.ClientCertificatePath     = ClientCertificatePath.Get(context);
            ftpConfiguration.ClientCertificatePassword = ClientCertificatePassword.Get(context);
            ftpConfiguration.AcceptAllCertificates     = AcceptAllCertificates;

            if (ftpConfiguration.UseAnonymousLogin == false)
            {
                ftpConfiguration.Username = Username.Get(context);
                ftpConfiguration.Password = Password.Get(context);
            }

            if (UseSftp)
            {
                ftpSession = new SftpSession(ftpConfiguration);
            }
            else
            {
                ftpSession = new FtpSession(ftpConfiguration, FtpsMode);
            }

            await ftpSession.OpenAsync(cancellationToken);

            return((nativeActivityContext) =>
            {
                if (Body != null)
                {
                    _ftpSession = ftpSession;
                    nativeActivityContext.ScheduleAction(Body, ftpSession, OnCompleted, OnFaulted);
                }
            });
        }
 public FtpAttributeBindingProvider(FtpConfiguration config, TraceWriter trace)
 {
     _config = config;
     _trace  = trace;
 }
Beispiel #16
0
 public FtpBinding(FtpConfiguration config, ParameterInfo parameter, BindingTemplate bindingTemplate)
 {
     _config          = config;
     _parameter       = parameter;
     _bindingTemplate = bindingTemplate;
 }
 public FtpStorageProviderSession(ICloudStorageAccessToken token, FtpConfiguration config, IStorageProviderService service)
 {
     SessionToken         = token;
     ServiceConfiguration = config;
     Service = service;
 }
 public FtpClient(FtpConfiguration config)
 {
     _config = config;
 }
Beispiel #19
0
 public SftpProcessor(FtpConfiguration configuration, IFileContentProcessor fileProcessor, ILogger logger)
 {
     _ftpConfiguration = configuration;
     _fileProcessor    = fileProcessor;
     _logger           = logger;
 }
 public bool Setftpconn(FtpConfiguration con)
 {
     return(_kvclient.SetStringKey <FtpConfiguration>("Conn:ftp:" + con.Key, con));
 }
 public FtpStorageProviderSession(ICloudStorageAccessToken token, FtpConfiguration config, IStorageProviderService service)
 {
     SessionToken = token;
     ServiceConfiguration = config;
     Service = service;
 }
 public FtpUploader(FtpConfiguration conf)
     : this(conf.Hostname, conf.Username, conf.Password, true, conf.UploadThreads)
 {
 }
Beispiel #23
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            PropertyDescriptor ftpSessionProperty = context.DataContext.GetProperties()[WithFtpSession.FtpSessionPropertyName];
            IFtpSession        ftpSession         = ftpSessionProperty?.GetValue(context.DataContext) as IFtpSession;

            if (ftpSession == null)
            {
                throw new InvalidOperationException(Resources.FTPSessionNotFoundException);
            }

            string localPath  = LocalPath.Get(context);
            string remotePath = RemotePath.Get(context);

            if (Directory.Exists(localPath))
            {
                if (string.IsNullOrWhiteSpace(Path.GetExtension(remotePath)))
                {
                    if (!(await ftpSession.DirectoryExistsAsync(remotePath, cancellationToken)))
                    {
                        if (Create)
                        {
                            await ftpSession.CreateDirectoryAsync(remotePath, cancellationToken);
                        }
                        else
                        {
                            throw new ArgumentException(string.Format(Resources.PathNotFoundException, remotePath));
                        }
                    }
                }
                else
                {
                    throw new InvalidOperationException(Resources.IncompatiblePathsException);
                }
            }
            else
            {
                if (File.Exists(localPath))
                {
                    if (string.IsNullOrWhiteSpace(Path.GetExtension(remotePath)))
                    {
                        remotePath = FtpConfiguration.CombinePaths(remotePath, Path.GetFileName(localPath));
                    }

                    string directoryPath = FtpConfiguration.GetDirectoryPath(remotePath);

                    if (!(await ftpSession.DirectoryExistsAsync(directoryPath, cancellationToken)))
                    {
                        if (Create)
                        {
                            await ftpSession.CreateDirectoryAsync(directoryPath, cancellationToken);
                        }
                        else
                        {
                            throw new InvalidOperationException(string.Format(Resources.PathNotFoundException, directoryPath));
                        }
                    }
                }
                else
                {
                    throw new ArgumentException(string.Format(Resources.PathNotFoundException, localPath));
                }
            }

            await ftpSession.UploadAsync(localPath, remotePath, Overwrite, Recursive, cancellationToken);

            return((asyncCodeActivityContext) =>
            {
            });
        }
 public FtpValueBinder(IFtpClient client, FtpConfiguration config, FtpAttribute ftpAttribute)
 {
     _client       = client;
     _config       = config;
     _ftpAttribute = ftpAttribute;
 }
Beispiel #25
0
 public FTPUtils(FtpConfiguration config)
 {
     _config = config;
 }
Beispiel #26
0
 public FtpProvider(IAuditConfiguration configuration, ILogManager logManager)
 {
     _logManager    = logManager;
     _configuration = configuration.FtpConfiguration;
 }