using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace SmartFTP.Logic { public static class FTPProcessSeparated { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); private static int BackupFiles(List fileNames, string zipFolder, string backupFolder) { int res = -1; try { foreach (string s in fileNames) { (new FileInfo(zipFolder + s)).MoveTo(backupFolder + s); } } catch { res = -1; } return res; } private static int BackupFile(string fileName, string zipFolder, string backupFolder) { int res = -1; try { (new FileInfo(zipFolder + fileName)).MoveTo(backupFolder + fileName); } catch (Exception ex) { logger.Error(ex.Message); res = -1; } return res; } public static int UploadTrimestraleFiles(string zipFolder, string ftpServer, string ftpPath, string ftpUser, string ftpPassword, string backupFolder, Action ftpProcessEnded = null, string fileName = "") { int res = -1; IWebProxy proxy = WebRequest.GetSystemWebProxy(); try { logger.Debug("Starting ftp process"); int useZ = Int32.Parse(ConfigurationManager.AppSettings["use7zip"]); string extension = (useZ == 1) ? "*.7z" : "*.zip"; logger.Debug("FTP process is using: " + extension + " extension"); WebRequest.DefaultWebProxy = null; logger.Debug("zip folder is " + zipFolder); DirectoryInfo di = new DirectoryInfo(zipFolder); List toMove = new List(); List errorFiles = new List(); List availableZips = GetFilesToSendListFromDB(); IOrderedEnumerable fi = null; if (fileName != "") fi = di.GetFiles(fileName).OrderBy(x => x.Name); else fi = di.GetFiles(extension).OrderBy(x => x.Name); foreach (FileInfo f in fi) { foreach (var v in availableZips) { if(f.Name.Contains(v.fileName) && f.Name.Contains(string.Concat("_", v.id.ToString()))) { v.localFileName = f.Name; toMove.Add(f.Name); } } } //foreach (FileInfo fi in di.GetFiles(extension).OrderBy(x => x.Name)) //{ // if ((fi.Name.Contains(fileName) && fileName != "") || (fileName == "")) // { // logger.Debug("trying to send " + fi.FullName); // foreach (var v in availableZips) // { // //logger.Info(String.Concat(v.fileName, " ", "_" + v.id.ToString())); // if (fi.Name.StartsWith(v.fileName) && fi.Name.Contains("_" + v.id.ToString())) // { // logger.Debug(String.Concat(fi.FullName, v.fileName)); // v.localFileName = fi.Name; // toMove.Add(fi.Name); // } // } // } //} logger.Debug("searching through availableZips"); foreach (var s in availableZips) { logger.Debug(s.localFileName); if (s.localFileName == String.Empty) continue; logger.Debug("file found, starting upload"); if (FTPTransferUtil.UploadFile(zipFolder, s.localFileName, ftpServer, ftpPath, ftpUser, ftpPassword) == 1) { if (UpdateFileStatusInDB(s) >= 0) { logger.Debug("file uploaded, moving to send folder"); BackupFile(s.localFileName, zipFolder, backupFolder); } else { errorFiles.Add(s); } } else { errorFiles.Add(s); Console.WriteLine("File {0} was not transfered due to an error", s.localFileName); } } //if (backupFolder != null) //{ // BackupFiles(toMove, zipFolder, backupFolder); //} if (errorFiles.Count() > 0) res = -2; else res = 1; } catch (Exception ex) { res = -1; logger.Error(ex.Message); if (ex.InnerException != null) logger.Equals(ex.InnerException.Message); Console.WriteLine(ex.Message); } finally { WebRequest.DefaultWebProxy = proxy; ftpProcessEnded?.Invoke(); } return res; } public static List GetFilesToUpload(string zipFolder, string ftpServer, string ftpPath, string ftpUser, string ftpPassword, string backupFolder, bool isFirstLotto, string suffixApproval) { List filesToUpload = new List(); try { IWebProxy proxy = WebRequest.GetSystemWebProxy(); int useZ = Int32.Parse(ConfigurationManager.AppSettings["use7zip"]); string extension = (useZ == 1) ? "*.7z" : "*.zip"; WebRequest.DefaultWebProxy = null; DirectoryInfo di = new DirectoryInfo(zipFolder); List toMove = new List(); List errorFiles = new List(); List availableZips = GetFilesToSendListFromDB(); List files = null; if (isFirstLotto) { files = di.GetFiles(extension).Where(x => x.Name.Contains(suffixApproval)).ToList(); if(files.Count() == 0) files = di.GetFiles(extension).OrderBy(x => x.Name).ToList(); } else { files = di.GetFiles(extension).OrderBy(x => x.Name).ToList(); } foreach (FileInfo fi in files) { foreach (var v in availableZips) { if (fi.Name.StartsWith(v.fileName) && fi.Name.Contains("_" + v.id.ToString())) { v.localFileName = fi.Name; toMove.Add(fi.Name); } } } foreach (var s in availableZips) { if (!string.IsNullOrEmpty(s.localFileName)) { filesToUpload.Add(s.localFileName); } } } catch { } return filesToUpload; } public static bool UploadFirstApprovalLottoPackage(string suffixApproval, string zipFolder, string ftpServer, string ftpPath, string ftpUser, string ftpPassword, string backupFolder, string fileName) { suffixApproval = string.Format("[{0}]", suffixApproval); bool res = false; IWebProxy proxy = WebRequest.GetSystemWebProxy(); try { logger.Debug("Starting ftp process - first lotto approval package sending"); int useZ = Int32.Parse(ConfigurationManager.AppSettings["use7zip"]); string extension = (useZ == 1) ? "*.7z" : "*.zip"; logger.Debug("FTP process is using: " + extension + " extension"); WebRequest.DefaultWebProxy = null; logger.Debug("zip folder is " + zipFolder); DirectoryInfo di = new DirectoryInfo(zipFolder); List toMove = new List(); List errorFiles = new List(); List availableZips = GetFilesToSendListFromDB(); IEnumerable files; if (fileName == "") { files = di.GetFiles(extension).Where(x => x.Name.Contains(suffixApproval)); if (files.Count() > 1) { logger.Debug("folder contains too many files with approval sufix"); return false; } if (files.Count() < 1) { logger.Debug("folder does not containt approval file"); return false; } } else { files = di.GetFiles().Where(x => x.Name.Contains(fileName)); if (files.Count() < 1) { logger.Debug("folder does not containt approval file"); return false; } } string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(files.FirstOrDefault().Name); string strId = fileNameWithoutExtension.Replace(suffixApproval, "").Split('_').Last(); int id = int.Parse(strId); availableZips = availableZips.Where(x => x.id == id).ToList(); if (availableZips.Count() > 1) { logger.Debug(string.Format("procedure [C6MartPeriodico].[GetFilesForSendingByFTP] returns too many records with id: {0}", id.ToString())); return false; } if (availableZips.Count() < 1) { logger.Debug(string.Format("procedure [C6MartPeriodico].[GetFilesForSendingByFTP] returns 0 records with id: {0}", id.ToString())); return false; } FileInfo fi = files.FirstOrDefault(); var v = availableZips.FirstOrDefault(); logger.Debug("trying to send " + fi.FullName); logger.Info(String.Concat(v.fileName, " ", "_" + v.id.ToString())); if (fi.Name.StartsWith(v.fileName) && fi.Name.Contains("_" + v.id.ToString())) { logger.Debug(String.Concat(fi.FullName, v.fileName)); v.localFileName = fi.Name; toMove.Add(fi.Name); } var s = v; logger.Debug(s.localFileName); if (s.localFileName == String.Empty) { return false; } else { if (FTPTransferUtil.UploadFile(zipFolder, s.localFileName, ftpServer, ftpPath, ftpUser, ftpPassword) == 1) { if (UpdateFileStatusInDB(s) >= 0) { logger.Debug("file uploaded, moving to send folder"); BackupFile(s.localFileName, zipFolder, backupFolder); res = true; } else { errorFiles.Add(s); } } else { errorFiles.Add(s); Console.WriteLine("File {0} was not transfered due to an error", s.localFileName); } } logger.Debug("file found, starting upload"); if (errorFiles.Count() > 0) return false; } catch (Exception ex) { res = false; logger.Error(ex.Message); if (ex.InnerException != null) logger.Equals(ex.InnerException.Message); Console.WriteLine(ex.Message); } finally { WebRequest.DefaultWebProxy = proxy; } return res; } private static int UpdateFileStatusInDB(FTPDataStruct file) { List pp = new List(); string procName = "[C6MartPeriodico].[GESTIONE_UPDATE_ZIP_COPY]"; pp.Add(new Parametro() { ParameterName = "Id", Value = file.id }); DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServerStampeC6, procName, pp); pp.Clear(); procName = "[C6MartPeriodico].[GESTIONE_UPDATE_ZIP]"; pp.Add(new Parametro() { ParameterName = "Id", Value = file.id }); DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServerStampeC6, procName, pp); return 1; } private static List GetFilesToSendListFromDB(string suffixApproval = null) { logger.Debug("GetFilesToSendListFromDB"); List res = new List(); try { var parameters = new List(); if (suffixApproval != null) { parameters.Add(new Parametro() { ParameterName = "ApprovalSuffix", Value = suffixApproval.Replace("[", "\\[") // procedure uses \ character to escape in LIKE statement }); } string sqlAvailableFiles = "C6MartPeriodico.GetFilesForSendingByFTP"; IDataReader r = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, sqlAvailableFiles, parameters); while (r.Read()) { res.Add(new FTPDataStruct() { fileName = r["nomefile"].ToString(), id = (int)r["id"] }); } } catch (Exception ex) { logger.Error(ex.InnerException.Message); } return res; } } }