Ejemplo n.º 1
0
        private void Delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否删除该文件夹", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                == DialogResult.Cancel)
            {
                return;
            }
            TreeNode pNode = this.SelectedNode;
            int      ID    = this.GetNodeID(pNode);

            IFtpClient pFtpClient = SysDBConfig.GetInstance().GetFtpClient("CHXQ");

            pFtpClient.Connect();
            pFtpClient.DeleteDirectory(GetFtpPathByNode(pNode));
            pFtpClient.Close();

            string sql = string.Format("delete from up_dirs where id={0}", ID);

            IDataBase pDataBase = SysDBConfig.GetInstance().GetOleDataBase("OrclConn");

            pDataBase.OpenConnection();
            pDataBase.ExecuteNonQuery(sql);
            pDataBase.CloseConnection();

            this.RefreshSubTreeView(pNode.Parent);
        }
Ejemplo n.º 2
0
        private static IEnumerable <string> DownloadFiles(string localPath, IFtpClient client, string directoryFullPath,
                                                          DateTime beginTime)
        {
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }
            var localFiles = new DirectoryInfo(localPath).GetFiles("*.*");

            var remoteFiles    = client.GetListing(directoryFullPath).Where(p => p.Modified >= beginTime);
            var downloads      = new List <string>();
            var localFullPaths = new List <string>();

            foreach (var remoteFile in remoteFiles)
            {
                if (remoteFile.Size <= 0)
                {
                    continue;
                }
                if (localFiles.Any(p => p.Name == remoteFile.Name))
                {
                    var localFile = localFiles.Single(p => p.Name == remoteFile.Name);
                    if (localFile.Length == remoteFile.Size)
                    {
                        continue;
                    }
                }
                downloads.Add(remoteFile.FullName);
                localFullPaths.Add(Path.Combine(localPath, remoteFile.Name));
            }
            client.DownloadFiles(localPath, downloads);
            Console.WriteLine($"Download {downloads.Count} records from {directoryFullPath}...");
            return(localFullPaths);
        }
Ejemplo n.º 3
0
        public static async ValueTask <bool> ConnectAsync(this IFtpClient ftpClient, Uri uri, CancellationToken token = default)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            var(hostName, address, port, encryptionLevel) = GetDetailsFromUri(uri);

            if (address != null && await ftpClient.ConnectAsync(address, port, encryptionLevel, token))
            {
                return(true);
            }

            var hostAddresses = Dns.GetHostAddresses(hostName);

            foreach (var hostAddress in hostAddresses)
            {
                if (await ftpClient.ConnectAsync(hostAddress, port, encryptionLevel, token))
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 4
0
        private void CreateSubDir_Click(object sender, EventArgs e)
        {
            TreeNode  pNode      = this.SelectedNode;
            int       ID         = this.GetNodeID(pNode);
            string    ParentPath = this.GetFtpPathByNode(pNode);
            string    sql        = "select SEQ_UP_DIRS.nextval from dual";
            IDataBase pDataBase  = SysDBConfig.GetInstance().GetOleDataBase("OrclConn");

            pDataBase.OpenConnection();
            string DirID = pDataBase.ExecuteScalar(sql).ToString();
            string Path  = string.Format("{0}/{1}", this.GetFtpPathByNode(pNode), DirID);

            sql = string.Format("insert into up_dirs values({0},'新建目录',{1},'{2}\\{0}',1)", DirID, ID, ParentPath);
            pDataBase.ExecuteNonQuery(sql);
            pDataBase.CloseConnection();

            this.RefreshSubTreeView(pNode);
            pNode.ExpandAll();
            TreeNode NewNode = this.FindNodeByID(int.Parse(DirID));

            IFtpClient pFtpClient = SysDBConfig.GetInstance().GetFtpClient("CHXQ");

            pFtpClient.Connect();
            string FtpPath = GetFtpPathByNode(NewNode);

            pFtpClient.CreateDirectory(FtpPath);
            pFtpClient.Close();
            this.SelectedNode = NewNode;
            this.LabelEdit    = true;
            NewNode.BeginEdit();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Async Delegate to do processing after we construct the content of file.
        /// 1. Upload the content to blob store, upload pending
        /// 2. Ftp to FDC
        /// 3. Mark as uploaded
        /// </summary>
        /// <param name="content">
        /// Content of the file
        /// </param>
        /// <returns>
        /// Async Task Wrapper
        /// </returns>
        public async Task OnPtsBuild(string content)
        {
            IFtpClient ftpClient = FirstDataFtpClientFactory.FirstDataPtsFtpClient(Logger);

            string connectionString           = CloudConfigurationManager.GetSetting("Lomo.Commerce.Fdc.Blob.ConnectionString");
            FirstDataPtsBlobClient blobClient = FirstDataBlobClientFactory.FirstDataPtsBlobClient(connectionString, Logger);

            // FDC requires EST.
            TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            DateTime     estNow      = TimeZoneInfo.ConvertTime(DateTime.UtcNow, easternZone);
            string       fileName    = estNow.ToString("yyyyMMddHmmss") + ".GPTD5628.TXT";

            //upload file to blob store
            byte[]       contentBytes = Encoding.ASCII.GetBytes(content);
            MemoryStream ms           = new MemoryStream(contentBytes);

            ms.Position = 0;
            await blobClient.UploadAsync(ms, fileName);

            Logger.Verbose("Uploaded file {0} to blob stored to be Ftped to FDC", fileName);

            // ftp it only if there are transactions
            if (!IsFileEmpty(ms))
            {
                ms.Position = 0;
                await ftpClient.UploadFileAsync(fileName, ms);

                Logger.Verbose("File {0} uploaded to FDC", fileName);
            }

            // mark done
            await blobClient.MarkAsUploadedAsync(fileName);

            Logger.Verbose("File {0} marked as uploaded", fileName);
        }
Ejemplo n.º 6
0
 public OpenDataRecordPublisher(IDocumentSession db, OpenDataPublisherConfig config, bool metadataOnly, IFtpClient ftpClient)
 {
     this.db = db;
     this.config = config;
     this.ftpClient = ftpClient;
     this.metadataOnly = metadataOnly;
 }
        /// <summary>
        /// Uploads file to blob store and FTP site as needed.
        /// </summary>
        /// <param name="content">
        /// The content of the file to upload.
        /// </param>
        /// <returns>
        /// The task to upload the file where needed.
        /// </returns>
        public async Task UploadRebateFile(string content)
        {
            string fileName = String.Concat("Rebate", DateTime.Now.ToString("yyyyMMddHmmss"), ".txt");
            MasterCardRebateBlobClient blobClient = MasterCardBlobClientFactory.MasterCardRebateBlobClient(Log);

            // Upload file to the blob store and MasterCard.
            byte[] contentBytes = Encoding.ASCII.GetBytes(content);
            using (MemoryStream memoryStream = new MemoryStream(contentBytes))
            {
                // Upload the file to the blob store.
                memoryStream.Position = 0;
                await blobClient.UploadAsync(memoryStream, fileName).ConfigureAwait(false);

                Log.Verbose("Uploaded file {0} to blob store.", fileName);

                // Upload the file to MasterCard.
                IFtpClient ftpClient = MasterCardFtpClientFactory.RebateFtpClient(Log);
                memoryStream.Position = 0;
                await ftpClient.UploadFileAsync(fileName, memoryStream);

                Log.Verbose("Uploaded file {0} to MasterCard.", fileName);
            }

            // Mark the file copy in the blob store as having been uploaded to MasterCard.
            await blobClient.MarkAsCompleteAsync(fileName).ConfigureAwait(false);

            Log.Verbose("File {0} marked as uploaded.", fileName);
        }
Ejemplo n.º 8
0
        private void DownloadFile(IFtpClient client, ILocalDirectory storageFolder, string fullRemotePath, IRemoteItem item, bool overwrite)
        {
            var file = storageFolder.TryGetItemAsync(item.Name).Result;

            if (file != null && !overwrite)
            {
                var downloadRemoteItem = DependencyService.Resolve <IDownloadRemoteItem>();
                downloadRemoteItem.Destination = storageFolder;
                downloadRemoteItem.Item        = item;

                FileConflicts.Add(downloadRemoteItem);
                return;
            }

            storageFolder.CreateFileAsync(item.Name, overwrite)
            .ContinueWith(fileStreamTask =>
            {
                var stream = fileStreamTask.Result.OpenStreamForWriteAsync().Result;

                using (var fileStream = stream)
                {
                    client.Download(fileStream, fullRemotePath);
                }
            }).Wait();
        }
Ejemplo n.º 9
0
        private static void SyncFilesToCloud(CloudBlobContainer container, IFtpClient client, string directoryFullPath,
                                             DateTime beginTime)
        {
            var remoteFiles = client.GetListing(directoryFullPath).Where(p => p.Modified >= beginTime).ToList();

            foreach (var remoteFile in remoteFiles)
            {
                if (remoteFile.Size <= 0)
                {
                    continue;
                }

                if (!client.Download(out var buffer, remoteFile.FullName))
                {
                    continue;
                }

                var blockBlob = container.GetBlockBlobReference(remoteFile.FullName.Substring(1));
                if (blockBlob.Exists())
                {
                    blockBlob.FetchAttributes();
                    if (blockBlob.Properties.Length == remoteFile.Size)
                    {
                        Console.WriteLine($"File {remoteFile.FullName} exists on cloud.");
                    }
                    continue;
                }
                blockBlob.UploadFromByteArray(buffer, 0, buffer.Length);
                Console.WriteLine($"Upload {remoteFile.FullName} to cloud.");
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        ///   Transfer a local file to a remote FTP client
        /// </summary>
        /// <param name="ftpClient">FTP client</param>
        /// <param name="localProductDomFilename">local product filename</param>
        /// <param name="remoteProductDomFilename">remote product filename</param>
        private void TransferProductFile(IFtpClient ftpClient, string localProductDomFilename, string remoteProductDomFilename)
        {
            FileStream fileStream = null;

            try
            {
                using (fileStream = File.OpenRead(localProductDomFilename))
                {
                    TraceVerbose("Uploading XML-file \"{0}\" to remote server \"{1}\" ...",
                                 Path.GetFileName(localProductDomFilename), ExportSettings.Server);
                    ftpClient.UploadFile(remoteProductDomFilename, fileStream);
                }
                LocalArchive(localProductDomFilename, SuccessDirectoryName);
            }
            catch (Exception ex)
            {
                TraceError("Error occured during transfer of XML-file \"{0}\" to remote server \"{1}\". Error: {1}",
                           Path.GetFileName(localProductDomFilename), ExportSettings.Server, ex.Message);

                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
                LocalArchive(localProductDomFilename, ErrorDirectoryName);
            }
        }
Ejemplo n.º 11
0
        private bool ConnectToFTP(IFtpClient client, bool message = false)
        {
            client.Host           = ipAddress.IPAddress.ToString();
            client.Port           = (int)numPort.Value;
            client.ConnectTimeout = (int)numTimeOut.Value;
            client.DataConnectionConnectTimeout = (int)numTimeOut.Value;
            client.DataConnectionReadTimeout    = (int)numTimeOut.Value;
            client.ReadTimeout = (int)numTimeOut.Value;

            try
            {
                client.GetWorkingDirectory();
                return(true);
            }
            catch (Exception ex)
            {
                if (!message)
                {
                    return(false);
                }
                MessageBox.Show("Unable to connect - please check your connection settings\n\nThe error says:\n\"" + ex.Message + "\"",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Log("Connection error: " + ex.Message);
                return(false);
            }
        }
Ejemplo n.º 12
0
 private static Task DeleteFile(IFtpClient client, string remoteFilePath)
 {
     return(Task.Run(() =>
     {
         client.DeleteFile(remoteFilePath);
     }));
 }
Ejemplo n.º 13
0
 public DataService(Env env, IFtpClient ftpClient, IFileHelper fileHelper, ISmtpClient smtpClient)
 {
     this.env        = env;
     this.ftpClient  = ftpClient;
     this.fileHelper = fileHelper;
     this.smtpClient = smtpClient;
 }
Ejemplo n.º 14
0
 private static Task DeleteDirectory(IFtpClient client, string remoteDirectoryPath)
 {
     return(Task.Run(() =>
     {
         client.DeleteDirectory(remoteDirectoryPath);
     }));
 }
Ejemplo n.º 15
0
        private void SyncDirectory(IFtpClient client, string remotePath, string localPath, bool isDel)
        {
            var localFolder = new DirectoryInfo(localPath);
            var infos       = localFolder.GetFileSystemInfos();

            foreach (var info in infos)
            {
                if (!client.IsConnected)
                {
                    client.Connect();
                }
                if (info is FileInfo)
                {
                    var size = (info as FileInfo).Length;

                    var remoteFile = Path.Combine(remotePath, info.Name);

                    if (!client.FileExists(remoteFile) || client.GetFileSize(remoteFile) != size)
                    {
                        client.UploadFile(info.FullName, remoteFile);

                        Logger.Info($"Uploaded==>{info.FullName}");
                    }
                }
                else if (info is DirectoryInfo)
                {
                    var remoteFile = Path.Combine(remotePath, info.Name);

                    if (!client.DirectoryExists(remoteFile))
                    {
                        client.CreateDirectory(remoteFile);

                        Logger.Info($"CreateFtpDirectory==>{remoteFile}");
                    }
                    SyncDirectory(client, Path.Combine(remotePath, info.Name), info.FullName, isDel);
                }
            }

            if (isDel)
            {
                var items = client.GetListing(remotePath);
                foreach (var item in items)
                {
                    if (infos.All(info => info.Name != item.Name))
                    {
                        if (item.Type == FtpFileSystemObjectType.File)
                        {
                            client.DeleteFile(item.FullName);
                        }
                        else if (item.Type == FtpFileSystemObjectType.Directory)
                        {
                            client.DeleteDirectory(item.FullName);
                        }

                        Logger.Info($"DeletedFtp==>{item.FullName}");
                    }
                }
            }
        }
Ejemplo n.º 16
0
        private async Task <LastRunConfig> ReadLastRunAsync(IFtpClient ftpClient)
        {
            var json = await ftpClient.DownloadStringAsync(_LastRunFileName);

            var result = json.ToObjectByJson <LastRunConfig>();

            return(result);
        }
Ejemplo n.º 17
0
        public ValuesController(IFtpClient ftpClient)
        {
            if (ftpClient == null)
            {
                throw new ArgumentNullException(nameof(ftpClient));
            }

            this.ftpClient = ftpClient;
        }
Ejemplo n.º 18
0
 public MainWindow()
 {
     _fsHelper = AppConfigurator.Instance.Resolve<IFileSystemHelper>();
     _client = AppConfigurator.Instance.Resolve<IFtpClient>();
     _appSettings = Settings.Default;
     _client.ListingDirectoryReceived += ClientOnListingDirectoryReceived;
     _client.Eror += ClientOnEror;
     InitializeComponent();
 }
 public ReadProjectCommandHandler(IFtpClient ftpClient, IGenericRepository <Project> projectRepository, IGenericRepository <GanttProject> ganttProjectRepository)
 {
     _ftpClient              = ftpClient;
     _projectRepository      = projectRepository;
     _ganttProjectRepository = ganttProjectRepository;
     _retryPolicy            = Policy.Handle <ArgumentOutOfRangeException>()
                               .WaitAndRetryAsync(3,
                                                  retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
 }
Ejemplo n.º 20
0
        public async Task Load(IDatabaseConnector databaseConnector, IFtpClient ftpClient, Directory moduleDirectory, IModuleLogger moduleLogger)
        {
            this.connectionString =
                await databaseConnector.GetDatabaseConnectionStringAsync(Guid.Parse(Id), DatabasePassword);

            this.cache        = new AnimeSearchCache(this.connectionString, new CrunchyrollApiService());
            this.GrpcServices = new[] { CrunchyrollService.BindService(new CrunchyRollImplementation(this.cache)), };
            Console.WriteLine("Loaded CR");
        }
Ejemplo n.º 21
0
 public MainWindow()
 {
     _fsHelper    = AppConfigurator.Instance.Resolve <IFileSystemHelper>();
     _client      = AppConfigurator.Instance.Resolve <IFtpClient>();
     _appSettings = Settings.Default;
     _client.ListingDirectoryReceived += ClientOnListingDirectoryReceived;
     _client.Eror += ClientOnEror;
     InitializeComponent();
 }
Ejemplo n.º 22
0
        private void BackupDirectory(IFtpClient client, string remotePath, string localPath, bool isDel)
        {
            var items = client.GetListing(remotePath);

            foreach (var item in items)
            {
                if (!client.IsConnected)
                {
                    client.Connect();
                }
                if (item.Type == FtpFileSystemObjectType.File)
                {
                    var size = client.GetFileSize(item.FullName);

                    var localFile = Path.Combine(localPath, item.Name);

                    if (!File.Exists(localFile) || new FileInfo(localFile).Length != size)
                    {
                        client.DownloadFile(localFile, item.FullName);

                        Logger.Info($"Downloaded==>{item.FullName}");
                    }
                }
                else if (item.Type == FtpFileSystemObjectType.Directory)
                {
                    if (!Directory.Exists(item.FullName))
                    {
                        Directory.CreateDirectory(item.FullName);

                        Logger.Info($"CreateDirectory==>{item.FullName}");
                    }
                    BackupDirectory(client, item.FullName, Path.Combine(localPath, item.Name), isDel);
                }
            }

            if (isDel)
            {
                var localFolder = new DirectoryInfo(localPath);
                var infos       = localFolder.GetFileSystemInfos();
                foreach (var info in infos)
                {
                    if (items.All(item => item.Name != info.Name))
                    {
                        if (info is DirectoryInfo)
                        {
                            (info as DirectoryInfo).Delete(true);
                        }
                        else
                        {
                            info.Delete();
                        }

                        Logger.Info($"Deleted==>{info.FullName}");
                    }
                }
            }
        }
Ejemplo n.º 23
0
        private static async Task UploadAsync(IFtpClient client, string fileName, Stream stream, bool overwrite, CancellationToken ct)
        {
            if (!overwrite && await client.FileExistsAsync(fileName, ct))
            {
                throw new AssetAlreadyExistsException(fileName);
            }

            await client.UploadAsync(stream, fileName, overwrite?FtpExists.Overwrite : FtpExists.Skip, true, null, ct);
        }
Ejemplo n.º 24
0
 public IrcAnimeImplementation(SearchService searchService, DownloadService downloadService, Func <IrcAnimeDbContext> getContext, IFtpClient ftpClient, Directory downloadDirectory, ILogger logger)
 {
     this.searchService     = searchService;
     this.downloadService   = downloadService;
     this.getContext        = getContext;
     this.ftpClient         = ftpClient;
     this.downloadDirectory = downloadDirectory;
     this.logger            = logger;
 }
Ejemplo n.º 25
0
 public MeasuresJobHelper(IConfigurationProvider configProvider, IMeasureService service, IFtpClient ftpClient, IMeasureFileExtracter measureFileExtracter, IPlantPowerService plantPowerService, IPlantPowerFileExtracter plantPowerFileExtracter, IPlantService plantService)
 {
     _configProvider = configProvider;
     _service = service;
     _ftpClient = ftpClient;
     _measureFileExtracter = measureFileExtracter;
     _plantPowerService = plantPowerService;
     _plantPowerFileExtracter = plantPowerFileExtracter;
     _plantService = plantService;
 }
Ejemplo n.º 26
0
		internal FtpWrapper(IFtpClient ftpClient, Settings settings)
		{
			_currentErrors = new Dictionary<string, int>();
			if (DownloadList == null)
			{
				DownloadList = new FtpListItemQueue();
			}
			_client = ftpClient;
			_settings = settings;
		}
Ejemplo n.º 27
0
        private void ExportProducts(IFtpClient ftpClient)
        {
            var document = CreateDocumentModel();

            if (document.Articles.Count > 0)
            {
                TraceVerbose("'{0}' articles are changed; These articles will be uploaded.", document.Articles.Count);

                var xmlProduct = ProductExporterHelper.SerializeModel(document);

                var fileName = String.Format("PIM_AI_{0:yyyyMMddHHmmss}.xml", DateTime.Now);

                try
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        TraceVerbose("Uploading XML-file \"{0}\" to remote server \"{1}\" ...", fileName, NavisionSettings.Server);

                        xmlProduct.Save(memoryStream);

                        memoryStream.Position = 0;

                        ftpClient.UploadFile(fileName, memoryStream);
                    }

                    foreach (var article in document.Articles)
                    {
                        var localProductXmlFilename = GetArchiveFullFileName(article.SupplierItemNumber);

                        var articleXml = ProductExporterHelper.SerializeModel(article);

                        articleXml.Save(localProductXmlFilename);
                    }
                }
                catch (IOException exception)
                {
                    TraceError("Unable to save the file to the ftp directory '{0}'. {1}", NavisionSettings.Server, exception.Message);
                }

                try
                {
                    TraceVerbose("Uploading XML-file '{0}' to local directory '{1}' ...", fileName, NavisionSettings.ArchiveDirectory);

                    xmlProduct.Save(Path.Combine(NavisionSettings.ArchiveDirectory, fileName));
                }
                catch (IOException exception)
                {
                    TraceWarning("Unable to save the file to the archive directory '{0}'. {1}", NavisionSettings.ArchiveDirectory, exception.Message);
                }
            }
            else
            {
                TraceVerbose("Upload not requiered. There is no article change.");
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Process MasterCard rebate confirmation file job execution.
        /// </summary>
        /// <param name="details">
        /// Details of the job to be executed.
        /// </param>
        /// <param name="log">
        /// Log within which to log status of job processing.
        /// </param>
        /// <returns>
        /// A task to execute the  job.
        /// </returns>
        /// <remarks>
        /// Once complete, this job will schedule a corresponding MasterCardProcessRebateConfirmationJob.
        /// </remarks>
        public async Task Execute(ScheduledJobDetails details,
                                  CommerceLog log)
        {
            Log = log;
            Log.Verbose("Starting execution of job.\r\nDetails {0}", details);

            MasterCardRebateConfirmationBlobClient blobClient = MasterCardBlobClientFactory.MasterCardRebateConfirmationBlobClient(log);

            // Download files from MasterCard and upload them to the blob store.
            IFtpClient ftpClient = MasterCardFtpClientFactory.RebateConfirmationFtpClient(Log);

            string[] files = await ftpClient.DirectoryListAsync();

            if (files != null)
            {
                foreach (string fileName in files)
                {
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        // Download the file from MasterCard.
                        await ftpClient.DownloadFileAsync(fileName, memStream).ConfigureAwait(false);

                        // Upload the file to the blob store.
                        memStream.Position = 0;
                        await blobClient.UploadAsync(memStream, fileName).ConfigureAwait(false);
                    }
                }
            }

            // Process all pending rebate confirmation files in the blob store.
            ICollection <string> fileNames = blobClient.RetrieveNamesOfPendingFiles();

            if (fileNames != null)
            {
                foreach (string fileName in fileNames)
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        // Download the file from the blob store.
                        memoryStream.Position = 0;
                        await blobClient.DownloadAsync(memoryStream, fileName).ConfigureAwait(false);

                        // Process the file.
                        memoryStream.Position = 0;
                        ISettlementFileProcessor rebateConfirmationProcessor = MasterCardFileProcessorFactory.MasterCardRebateConfirmationProcessor(memoryStream, fileName);
                        await rebateConfirmationProcessor.Process().ConfigureAwait(false);
                    }

                    // Mark the file as having been processed.
                    await blobClient.MarkAsCompleteAsync(fileName).ConfigureAwait(false);
                }
            }

            Log.Verbose("Execution of job {0} complete ", details.JobId);
        }
Ejemplo n.º 29
0
 private static async Task DownloadAsync(IFtpClient client, string fileName, Stream stream, CancellationToken ct)
 {
     try
     {
         await client.DownloadAsync(stream, fileName, token : ct);
     }
     catch (FtpException ex) when(IsNotFound(ex))
     {
         throw new AssetNotFoundException(fileName, ex);
     }
 }
Ejemplo n.º 30
0
 public void Init()
 {
     proxyftpClient = new FtpClient("10.27.68.155", "8021");
     host           = "10.27.68.155";
     port           = 21;
     user           = "******";
     pwd            = "icftp";
     proxyftpClient.Open(host, port);
     proxyftpClient.Logon(user, pwd);
     log2.Debug("開啟FTP " + ", host:" + host + ", port:" + port + ", user:"******", pwd:" + pwd);
 }
Ejemplo n.º 31
0
 private void SetUserCredential()
 {
     if (testeCredential == null)
     {
         _ftp = new FtpClient("anticimex", "hEkF?08q", "IDCFTPGW.INTRUM.NET", "22222");
     }
     else
     {
         _ftp = new FtpClient(testeCredential.User, testeCredential.Pass, testeCredential.Host);
     }
 }
Ejemplo n.º 32
0
 public RemoteDevService(IConfiguration configuration, IFtpClient ftpClient, IFolderMonitor folderMonitor)
 {
     _settings      = new Configuration();
     _ftpClient     = ftpClient;
     _folderMonitor = folderMonitor;
     configuration.Bind(_settings);
     _folderMonitor.FileChanged += OnFileChanged;
     _excludedDirectories        = new List <string>();
     foreach (var ignore_dir in _settings.Ignore)
     {
         _excludedDirectories.Add(String.Format("{0}{1}", _settings.LocalPath, ignore_dir));
     }
 }
Ejemplo n.º 33
0
        private void ProcessPricatFiles(IFtpClient client, ISimpleArchiveService archiver)
        {
            var successArchive = Path.Combine(PricatSettings.VendorArchive, SuccessDirectoryName);
            var errorArchive   = Path.Combine(PricatSettings.VendorArchive, ErrorDirectoryName);

            var sessionStart = DateTime.Now;

            foreach (var remoteFile in client.Files.Where(file => file.FileName.EndsWith(".csv", StringComparison.CurrentCultureIgnoreCase)))
            {
                var remoteFileName = remoteFile.FileName;

                using (var fileStream = client.DownloadFile(remoteFileName))
                {
                    TraceVerbose("Processing file '{0}'...", remoteFileName);

                    var lines = ReadRawPricatLines(fileStream);

                    _currentRemoteFileName = remoteFileName;

                    var importSuccess   = ProcessPricatFile(lines);
                    var intendedArchive = importSuccess ? successArchive : errorArchive;

                    if (archiver.ArchiveLines(lines, intendedArchive, sessionStart, remoteFileName))
                    {
                        if (intendedArchive == successArchive)
                        {
                            TraceInformation("The PRICAT-file '{0}' has been archived to the '{1}'-folder.", remoteFileName, intendedArchive);
                        }
                        else
                        {
                            TraceWarning("The PRICAT-file '{0}' has been archived to the '{1}'-folder.", remoteFileName, intendedArchive);
                        }
                    }
                    else
                    {
                        TraceError("Failed to archive the PRICAT-file '{0}' into the '{1}'-folder.", remoteFileName, intendedArchive);
                    }

                    //Move file on the FTP
                    if (!client.TryMoveFile(remoteFileName, importSuccess ? SuccessDirectoryName : ErrorDirectoryName))
                    {
                        TraceError("Moving file '{0}' to the folder '{1}' on the FTP failed.", remoteFileName, importSuccess ? SuccessDirectoryName : ErrorDirectoryName);
                    }
                }
            }

            //TraceVerbose("Generating product attribute configuration...");

            // DS: Inactive as for 2014-07-15
            //Database.Execute("EXEC [GenerateProductAttributeConfiguration] @0", "Color, Size, Subsize");    //TODO: SP missing in database
        }
Ejemplo n.º 34
0
        private void ExportProducts(IFtpClient ftpClient)
        {
            var skipCounter    = 0;
            var uploadCounter  = 0;
            var failureCounter = 0;
            var productCounter = _products.Count();

            foreach (var product in _products)
            {
                TraceVerbose("Processing product \"{0}\".", product.VendorItemNumber);

                if (_configurableProductWithImage.Contains(product.ProductID))
                {
                    var productModel = CreateProductBizTalkModel(product, DefaultConnector.ConnectorID);

                    var productDom = ProductExporterHelper.SerializeModel(productModel);

                    var localProductDomFilename  = Path.Combine(ExportSettings.LocalExportFolder, String.Format(Resources.ExportFileNameTemplate, product.VendorItemNumber));
                    var remoteProductDomFilename = Path.GetFileName(localProductDomFilename);

                    productDom.Save(localProductDomFilename);

                    if (File.Exists(localProductDomFilename))
                    {
                        if (UploadRequired(localProductDomFilename))
                        {
                            TransferProductFile(ftpClient, localProductDomFilename, remoteProductDomFilename);
                            uploadCounter++;
                        }
                        else
                        {
                            TraceVerbose("Skipping Product: {0}... This product already processed before; upload not required.", product.VendorItemNumber);
                            skipCounter++;
                        }
                    }
                    else
                    {
                        TraceError("XML-file \"{0}\" not ready for transfer to remote server \"{1}\"",
                                   Path.GetFileName(localProductDomFilename), ExportSettings.Server);
                        failureCounter++;
                    }
                }
                else
                {
                    skipCounter++;
                    TraceVerbose("Skipping Product: {0}... This product has no media!", product.VendorItemNumber);
                }

                TraceVerbose("Progress: {0} failure | {1} skipped | {2} uploaded | {3} Products", failureCounter, skipCounter, uploadCounter, productCounter);
            }
        }
Ejemplo n.º 35
0
        private void prepareContextData(IJobExecutionContext context)
        {
            _logger.Info("Getting Job Data from context");

            var confProvider = context.Trigger.JobDataMap.Get("ConfigurationProvider") as IConfigurationProvider;
            if (confProvider == null)
                throw new ArgumentException("Cant get IConfigurationProvider from context");
            _configProvider = confProvider;

            var ftpClient = context.Trigger.JobDataMap.Get("FtpClient") as IFtpClient;
            if (ftpClient == null)
                throw new ArgumentException("Cant get IFtpClient from context");
            _ftpClient = ftpClient;

            var service = context.Trigger.JobDataMap.Get("MeasureService") as IMeasureService;
            if (service == null)
                throw new ArgumentException("Cant get IMeasureService from context");
            _measureService = service;

            var plantPowerService = context.Trigger.JobDataMap.Get("PlantPowerService") as IPlantPowerService;
            if (plantPowerService == null)
                throw new ArgumentException("Cant get IPlantPowerService from context");
            _plantPowerService = plantPowerService;

            var plantService = context.Trigger.JobDataMap.Get("PlantService") as IPlantService;
            if (plantService == null)
                throw new ArgumentException("Cant get IPlantService from context");
            _plantService = plantService;

            var extracter = context.Trigger.JobDataMap.Get("MeasureFileExtracter") as IMeasureFileExtracter;
            if (extracter == null)
                throw new ArgumentException("Cant get IMeasureFileExtracter from context");
            _fileExtracter = extracter;

            var extracterPlantPower = context.Trigger.JobDataMap.Get("PlantPowerFileExtracter") as IPlantPowerFileExtracter;
            if (extracterPlantPower == null)
                throw new ArgumentException("Cant get IPlantPowerFileExtracter from context");
            _filePlantPowerExtracter = extracterPlantPower;

            _logger.Info("Done getting Job Data from context");
        }
 public FtpValueBinder(IFtpClient client, FtpConfiguration config, FtpAttribute ftpAttribute)
 {
     _client = client;
     _config = config;
     _ftpAttribute = ftpAttribute;
 }
Ejemplo n.º 37
0
		public void Initialize()
		{
			_ftpClient = MockRepository.GenerateMock<IFtpClient>();
			_ftpWrapper = new FtpWrapper(_ftpClient, new Settings());
		}