/// <summary> /// Проверка, подходит ли файл для передачи с помощью текущей стратегии добавления /// </summary> /// <param name="filename">Имя файла</param> /// <param name="creationTime">Дата создания файла</param> /// <returns>true - подходит для передачи, false - не подходит</returns> public bool FileVerification(string filename, DateTime creationTime) { this.output = ControllerOfOutput.Instance; if (this.useCreationDate) { DateTime cCreatTime = this.CutDateTime(creationTime.ToUniversalTime()); DateTime cWorkDateTime = this.CutDateTime(this.GetUtcWorkDate()); if (cCreatTime != cWorkDateTime) { output.WriteProgress( String.Format("Файл {0} не передавался. Не подходящая дата создания {1}. Искали с датой {2}", filename, cCreatTime.ToString("yyyy:MM:dd"), cWorkDateTime.ToString("yyyy:MM:dd"))); return(false); } } if (this.fileNameUsage == "Masked") { bool regRes = RegexpParsing.FilenameVerification(filename, this.CalculatedFileMask); if (!regRes) { output.WriteAverageMessage(String.Format("Файл {0} не подходит под маску {1}.", filename, this.CalculatedFileMask)); } return(regRes); } return(true); }
/// <summary> /// Тест сети /// </summary> /// <param name="logs">Файл логов</param> /// <param name="ftpIP">адрес сервера</param> /// <returns></returns> public static bool NetworkTest(ControllerOfOutput logs, string ftpIP) { string[] str = new string[] { ftpIP }; logs.WriteAverageMessage("Пингуем FTP..."); if (Pinging(logs, str) == false) { logs.WriteCritMessage("FTP недоступен"); } str = new string[] { "8.8.8.8.", "google.com", "yandex.ru", "facebook.com", "twitter.com" }; logs.WriteAverageMessage("Пингуем глобальную сеть..."); if (Pinging(logs, str) == false) { logs.WriteCritMessage("Ни один из адресов глобальной сети недоступен"); } str = new string[] { "10.10.0.100", "10.10.0.150", "10.10.0.151", "10.10.0.125" }; logs.WriteAverageMessage("Пингуем локальную сеть..."); if (Pinging(logs, str) == false) { logs.WriteCritMessage("Ни один из адресов локальной сети недоступен"); } return(true); }
//копируем в нужную папку все файлы из временной директории public override void ActionAsDestination() { ControllerOfOutput output = ControllerOfOutput.Instance; DirectoryInfo di = new DirectoryInfo(SettingsClass.Instance.GetTmpDirName()); if (!this.checkDirectory(di)) { return; } foreach (FileInfo file in di.GetFiles()) { try { if (!Directory.Exists(this.CalculatedFilePath)) { Directory.CreateDirectory(this.CalculatedFilePath); } if (File.Exists(this.CalculatedFilePath + file.Name)) { string msg = String.Format("Файл {0} уже существует в папке {1}.", file.FullName, this.CalculatedFilePath + file.Name); output.WriteAverageMessage(msg); this.statistics.addMessage(msg); continue; } File.Copy(file.FullName, this.CalculatedFilePath + file.Name); output.WriteAverageMessage(String.Format("Файл {0} успешно передан в папку-назначение {1}", file.FullName, this.CalculatedFilePath + file.Name)); //throw new Exception(); this.statistics.incrementFiles(1); this.statistics.incrementBytesWithCut(file.Length); this.statistics.addResult(WorkResult.Success); } catch (Exception ex) { string errMsg = String.Format( "Ошибка при передаче файла {0} В папку {1}. Текст ошибки: {2}", file.Name, this.CalculatedFilePath, ex.Message); output.WriteErrors(errMsg); this.statistics.addError(errMsg); //пока не понятно нужен ли errorCount или нет //localErrorCount++; /* * if (localErrorCount > this.errorCount) * { * throw new FileExchangeException(errMsg); * } * Thread.Sleep(this.sleepBeforeNext); */ } } }
public override void ActionAsSource() { string tmpDirName = SettingsClass.Instance.GetTmpDirName(); ControllerOfOutput output = ControllerOfOutput.Instance; //string[] filenames = Directory.GetFiles(this.CalculatedFilePath); DirectoryInfo di = new DirectoryInfo(this.CalculatedFilePath); if (!this.checkDirectory(di)) { return; } foreach (FileInfo file in di.GetFiles()) { try { //проверка, подходит ли данный файл для передачи if (!this.addStrategy.FileVerification(file.Name, File.GetLastWriteTime(file.FullName).ToUniversalTime())) { continue; } output.WriteAverageMessage(String.Format("Передаем файл {0} во временную папку {1}.", file.FullName, tmpDirName + file.Name)); if (File.Exists(tmpDirName + file.Name)) { string errMsg2 = String.Format("Файл {0} уже передавался из других источников.", file.Name); output.WriteAverageMessage(errMsg2); this.statistics.addMessage(errMsg2); File.Delete(tmpDirName + file.Name); } File.Copy(file.FullName, tmpDirName + file.Name); output.WriteAverageMessage(String.Format("Файл {0} успешно передан.", file.FullName, tmpDirName + file.Name)); this.statistics.incrementFiles(1); this.statistics.incrementBytesWithCut(file.Length); this.statistics.addResult(WorkResult.Success); } catch (Exception ex) { string msg = String.Format( "Ошибка при передаче файла {0} Во временную папку. Текст ошибки: {1}", file.Name, ex.Message); output.WriteErrors(msg); this.statistics.addError(msg); //throw new FileExchangeException(String.Format("Ошибка при передачи файла {0} Во временную папку. Текст ошибки: {1}", file.Name, ex.Message)); } } }
public static void AddRoute(string add, string mask1, string mask2) { try { ExecuteBatchCommand(String.Format("route add {0} mask {1} {2}", add, mask1, mask2)); } catch (Exception) { ControllerOfOutput coo = ControllerOfOutput.Instance; coo.WriteAverageMessage("Во время создания роута произошла ошибка"); } }
private void Init() { string[] sepFields = new string[] { " " }; string[] sepDate = new string[] { "." }; string[] sepTime = new string[] { ":" }; StreamReader myStream = null; try { myStream = new StreamReader(this.lastLogPath); } catch (Exception ex) { this.checkStatus = false; ControllerOfOutput coo = ControllerOfOutput.Instance; coo.WriteErrors("Ошибка при попытке открыть файл логов работы. Текст ошибки" + ex.Message); return; } while (!myStream.EndOfStream) { string strToParse = myStream.ReadLine(); string[] parsingStr = strToParse.Split(sepFields, StringSplitOptions.RemoveEmptyEntries); try { List <int> parsingStrDate = StrArrToIntArr(parsingStr[1].Split(sepDate, StringSplitOptions.RemoveEmptyEntries)); List <int> parsingStrTime = StrArrToIntArr(parsingStr[2].Split(sepTime, StringSplitOptions.RemoveEmptyEntries)); SavedTaskResults tmpTsk = new SavedTaskResults(); tmpTsk.id = int.Parse(parsingStr[0]); tmpTsk.lastRun = new DateTime(parsingStrDate[2], parsingStrDate[1], parsingStrDate[0], parsingStrTime[0], parsingStrTime[1], parsingStrTime[2]); tmpTsk.isSuccess = bool.Parse(parsingStr[3]); this.prevRes.Add(tmpTsk); } catch (Exception) { continue; } } myStream.Close(); this.checkStatus = true; }
/// <summary> /// Выполняет команду ping /// </summary> /// <param name="logs">файл логов</param> /// <param name="str">адреса для пингования</param> /// <returns></returns> public static bool Pinging(ControllerOfOutput logs, string[] str) { System.Net.NetworkInformation.Ping ping = null; System.Net.NetworkInformation.PingReply pingReply = null; List <string> adresses = new List <string>(str); foreach (var item in adresses) { try { ping = new System.Net.NetworkInformation.Ping(); pingReply = ping.Send(item); if (pingReply.Status == System.Net.NetworkInformation.IPStatus.Success) { logs.WriteAverageMessage(String.Format("Адрес {0} успешно пропингован! RoundtripTime: {1}. Status: {2}", item, pingReply.RoundtripTime, pingReply.Status)); } else { logs.WriteCritMessage(String.Format("Ответ от адреса {0} отличается от успешного! RoundtripTime: {1}. Status: {2}", item, pingReply.RoundtripTime, pingReply.Status)); continue; } return(true); } catch (Exception ex) { if (pingReply != null) { logs.WriteCritMessage(String.Format("Адрес {0} недоступен. RoundtripTime: {1}. Status: {2}. Error: {3}", item, pingReply.RoundtripTime, pingReply.Status, ex.Message)); } else { logs.WriteCritMessage(String.Format("Во время получения ответа от адреса {0} произошла ошибка {1}", item, ex.Message)); } continue; } } return(false); }
public bool checkDirectory(DirectoryInfo di) { ControllerOfOutput output = ControllerOfOutput.Instance; try { di.GetFiles(); } catch (Exception ex) { string errMsg = String.Format( "Ошибка при подключении к директории {0}. Текст ошибки: {1}", di.FullName, ex.Message); output.WriteErrors(errMsg); this.statistics.addError(errMsg); return(false); } return(true); }
//все задания могут содержать несколько источников и назначений //сначала на локальный компьютер передаются файлы из источников, а затем //они передаются в назначения public ResultController TaskStartsExchange(MyProxy prx, ResultController sessionResultController) { ResultController taskResultController = new ResultController("Выполнение задачи " + this.id); ControllerOfOutput outputs = ControllerOfOutput.Instance; //LogOfSuccession los = LogOfSuccession.Instance; //bool success = true; try { this.ClearTmpDir(); //Если есть роуты, добавляем их foreach (CmdRoute rt in taskRouts) { BatchRunner.AddRoute(rt.destination, rt.subnetMask, rt.gateway); } List <FileSupertype> downloadFiles = uploadDownload.FindAll(x => x.source_dest == ActionType.Source); List <FileSupertype> uploadFiles = uploadDownload.FindAll(x => x.source_dest == ActionType.Destination); foreach (FileSupertype dfile in downloadFiles) { ActionResult tmpRes = dfile.StartFileAction(prx); taskResultController.AddAction(tmpRes); } foreach (FileSupertype ufile in uploadFiles) { ActionResult tmpRes = ufile.StartFileAction(prx); taskResultController.AddAction(tmpRes); } this.ClearTmpDir(); } catch (Exception ex) { outputs.WriteErrors(ex.Message); } return(taskResultController); }
//Проверка задания на тему того, надо ли запускать ее еще раз //false, если задачу надо запустить еще раз public virtual bool CheckTaskExecute(int taskID, string taskPeriod) { ControllerOfOutput output = ControllerOfOutput.Instance; //находим нужное задание по id SavedTaskResults workRes = prevRes.Find(x => x.id == taskID); if (workRes == null) { output.WriteAverageMessage("Задание " + taskID + " отсутствует в списке. Начинаем выполнение."); return(false); } //исключительная ситуация, требующая дополнительного внимания: когда задание выполнилось, //затем пропало из планировщика, затем снова появилось в планировщике. //оно будет выполнено еще раз, как и задания с изменившимся id //добавление этого таска нужно чтобы переносить уже сделанные задачи на следующую проверку resToSave.Add(workRes); if (!workRes.isSuccess) { output.WriteAverageMessage("Предыдущее выполнение задания " + taskID + " завершилось ошибкой. Начинаем выполнение."); return(false); } bool periodRes = PeriodFitting(workRes, taskPeriod); if (periodRes) { output.WriteAverageMessage("Задача " + taskID + " уже успешно выполнялась в периоде " + taskPeriod + ". Последнее время выполнения: " + workRes.lastRun.ToString() + "."); } else { output.WriteAverageMessage("Задача " + taskID + " будет выполнена."); } return(periodRes); }
public override void ActionAsSource() { string tmpDirName = SettingsClass.Instance.GetTmpDirName(); ControllerOfOutput output = ControllerOfOutput.Instance; string ftpUriStr = "ftp://" + this.ftpUri + this.CalculatedFilePath; Dictionary <int, string> filesDict = new Dictionary <int, string>(); Dictionary <int, DateTime> filesModifDict = new Dictionary <int, DateTime>(); FtpWebResponse response = null; try { //здесь мы считываем список файлов, находящихся на ftp FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(ftpUriStr); ftpReq = this.FtpSet(ftpReq); ftpReq.Method = WebRequestMethods.Ftp.ListDirectory; response = (FtpWebResponse)ftpReq.GetResponse(); StreamReader streamReader = new StreamReader(response.GetResponseStream()); int ind = 0; string line = streamReader.ReadLine(); while (!string.IsNullOrEmpty(line)) { filesDict.Add(ind++, line); line = streamReader.ReadLine(); } } catch (Exception ex) { string errMsg = String.Format("Ошибка при считывании списка файлов c Uri {0}. Текст ошибки: {1}", ftpUriStr, ex.Message); output.WriteErrors(errMsg); this.statistics.addError(errMsg); return; } //если используется дата создания, сперва нужно опросить каждый файл о дате его последней модификации foreach (KeyValuePair <int, string> fileName in filesDict) { FtpWebRequest request = null; try { request = (FtpWebRequest)WebRequest.Create(ftpUriStr + fileName.Value); request.Method = WebRequestMethods.Ftp.GetDateTimestamp; request = this.FtpSet(request); response = (FtpWebResponse)request.GetResponse(); filesModifDict.Add(fileName.Key, response.LastModified.ToUniversalTime()); //проверка, подходит ли данный файл для передачи if (!this.addStrategy.FileVerification(fileName.Value, filesModifDict[fileName.Key])) { continue; } } catch (Exception ex) { string errMsg = String.Format( "Ошибка при определении даты последней модификации файла {0}. Текст ошибки: {1}", fileName, ex.Message); output.WriteErrors(errMsg); this.statistics.addError(errMsg); return; } try { //при успешной проверке мы передаем файл во временную папку output.WriteAverageMessage(String.Format("Передаем файл {0} во временную папку", fileName.Value)); //если передаваемый файл существует во временной папке if (File.Exists(tmpDirName + fileName.Value)) { string errMsg2 = String.Format("Файл {0} уже передавался из других источников.", fileName.Value); output.WriteAverageMessage(errMsg2); this.statistics.addMessage(errMsg2); File.Delete(tmpDirName + fileName.Value); } FtpWebRequest request2 = (FtpWebRequest)WebRequest.Create(ftpUriStr + fileName.Value); request2.Method = WebRequestMethods.Ftp.DownloadFile; request = this.FtpSet(request2); response = (FtpWebResponse)request2.GetResponse(); Stream stream = response.GetResponseStream(); List <byte> streamByteList = new List <byte>(); int b; long allBytesCount = 0; while ((b = stream.ReadByte()) != -1) { streamByteList.Add((byte)b); allBytesCount += b; } File.WriteAllBytes(tmpDirName + fileName.Value, streamByteList.ToArray()); this.statistics.incrementFiles(1); this.statistics.incrementBytesWithCut(new System.IO.FileInfo(tmpDirName + fileName.Value).Length); this.statistics.addResult(WorkResult.Success); } //ToDo: А что если такой файл уже будет существовать? catch (Exception ex) { //this.statistics.addResult(WorkResult.Error); string errMsg = String.Format( "Ошибка при передаче файла {0} во временную папку. Текст ошибки: {1}", fileName, ex.Message); output.WriteErrors(errMsg); this.statistics.addError(errMsg); return; //throw new FileExchangeException(errMsg); } output.WriteAverageMessage(String.Format("Файл {0} успешно передан во временную папку {1}", fileName.Value, tmpDirName + fileName.Value)); } Console.WriteLine(); }
public override void ActionAsDestination() { ControllerOfOutput output = ControllerOfOutput.Instance; DirectoryInfo di = new DirectoryInfo(SettingsClass.Instance.GetTmpDirName()); //int localErrorCount = 0; foreach (FileInfo file in di.GetFiles()) { string ftpUriStr = ""; try { ftpUriStr = @"ftp://" + this.ftpUri + "/" + file.Name; FtpWebRequest request = WebRequest.Create(new Uri(string.Format(ftpUriStr))) as FtpWebRequest; request.Method = WebRequestMethods.Ftp.UploadFile; request = this.FtpSet(request); //здесь непосредственно передача int totalReadBytesCount = 0; using (FileStream inputStream = File.OpenRead(file.FullName)) using (Stream outputStream = request.GetRequestStream()) { byte[] buffer = new byte[16384]; int prevByteCount = 0; int readBytesCount; while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0) { outputStream.Write(buffer, 0, readBytesCount); totalReadBytesCount += readBytesCount; double progress = totalReadBytesCount * 100.0 / inputStream.Length; double totalKBytes = Math.Round((double)totalReadBytesCount / 1000, 0); double allKBytes = Math.Round((double)inputStream.Length / 1000, 0); prevByteCount = totalReadBytesCount; output.WriteProgress(String.Format("Progress: {0}% {1} Кб из {2} Кб.", Math.Round(progress, 2).ToString("##0.00"), totalKBytes, allKBytes)); } } this.statistics.incrementFiles(1); this.statistics.incrementBytesWithCut(file.Length); this.statistics.addResult(WorkResult.Success); } catch (Exception ex) { //сперва проверяем, не вылезла ли ошибка только потому, что такой файл уже существует FtpWebRequest request = WebRequest.Create(new Uri(string.Format(ftpUriStr))) as FtpWebRequest; request.Method = WebRequestMethods.Ftp.GetFileSize; request = this.FtpSet(request); try { FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch (WebException wex) { FtpWebResponse response = (FtpWebResponse)wex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { string errMsg2 = String.Format("Файл {0} уже существует на ftp-сервере {1}.", file.FullName, ftpUriStr); output.WriteAverageMessage(errMsg2); this.statistics.addMessage(errMsg2); continue; } } string errMsg = String.Format( "Ошибка при передачи файла {0} На сервер {1}. Текст ошибки: {2}", file.Name, ftpUriStr, ex.Message); output.WriteErrors(errMsg); this.statistics.addError(errMsg); return; //localErrorCount++; /* * if (localErrorCount > this.errorCount) * { * throw new FileExchangeException(errMsg); * } * Thread.Sleep(this.sleepBeforeNext); */ } } }
public AddStrategyClass(ControllerOfOutput _output) { this.output = _output; }
/// <summary> /// Парсинг XML-файла /// </summary> /// <returns> </returns> public PlannerText(string _plannerPath, ControllerOfOutput _outputs, LogOfSuccession _los) { this.outputs = _outputs; this.los = _los; this.BackupPlannerXml(); PlannerTask tmpTask = new PlannerTask(); FtpFile tmpFtpFile = new FtpFile(); WinFSFile tmpWinFSFile = new WinFSFile(); FileSupertype tmpFileSupertype = tmpFtpFile; AddStrategyClass tmpStrategy = new AddStrategyClass(); CmdRoute tmpCmdRoute = new CmdRoute(); ActionType source_dest = ActionType.Source; PrivateData pd = PrivateData.Instance; string nodeName = String.Empty; XmlTextReader reader = new XmlTextReader(_plannerPath); while (reader.Read()) { string readerValPriv = pd.GetValueFromTemplate(reader.Value); switch (reader.NodeType) { case XmlNodeType.Element: // Узел является элементом. nodeName = reader.Name; switch (nodeName) { case "task": tmpTask = new PlannerTask(); this.tasks.Add(tmpTask); break; case "route": tmpCmdRoute = new CmdRoute(); tmpTask.taskRouts.Add(tmpCmdRoute); break; case "sourceFile": source_dest = ActionType.Source; break; case "destinationFile": source_dest = ActionType.Destination; break; } break; //ToDo: добавить отлавливание оршибок при ошибочном преобразовании case XmlNodeType.Text: // Вывести текст в каждом элементе. switch (nodeName) { //исключительно Planner case "proxyAddress": this.prx.address = readerValPriv; break; case "proxyUser": this.prx.user = readerValPriv; break; case "proxyPass": this.prx.pass = readerValPriv; break; case "proxyAddressesToBypass": this.prx.addressesToBypas = readerValPriv; break; //пошли задания case "id": tmpTask.id = int.Parse(readerValPriv); break; case "isFake": tmpTask.isFake = bool.Parse(readerValPriv); break; case "taskDiscription": tmpTask.taskDiscription = readerValPriv; break; case "deleteTmp": tmpTask.deleteTmp = bool.Parse(readerValPriv); break; case "taskPeriod": tmpTask.period = readerValPriv; break; //добавление IP route'ов case "routeDestination": tmpCmdRoute.destination = readerValPriv; break; case "routeSubnetmask": tmpCmdRoute.subnetMask = readerValPriv; break; case "routeGateway": tmpCmdRoute.gateway = readerValPriv; break; //стратегия добавления case "addStrategyUseMask": tmpStrategy.usemask = bool.Parse(readerValPriv); break; case "addStrategyFileMask": tmpStrategy.fileMask = readerValPriv; break; case "addStrategyFileNameUsage": tmpStrategy.fileNameUsage = readerValPriv; break; case "addStrategyWorkInterval": tmpStrategy.workInterval = GlobalUtils.ParseWorkIntervalEnum(readerValPriv); break; case "addStrategyCheckDateCondition": tmpStrategy.checkDateCondition = readerValPriv; break; case "addStrategyUseCreationDate": tmpStrategy.useCreationDate = bool.Parse(readerValPriv); break; case "addStrategyDateRange": tmpStrategy.dateRange = GlobalUtils.ParseDateRangeEnum(readerValPriv); break; //пошли файлы-источники и файлы-назначения case "type": if (readerValPriv == "FTP") { tmpFtpFile = new FtpFile(tmpFtpFile, tmpTask.id); tmpFileSupertype = tmpFtpFile; tmpTask.uploadDownload.Add(tmpFileSupertype); } else { tmpWinFSFile = new WinFSFile(tmpWinFSFile, tmpTask.id); tmpFileSupertype = tmpWinFSFile; tmpTask.uploadDownload.Add(tmpFileSupertype); } tmpStrategy = new AddStrategyClass(tmpStrategy); tmpFileSupertype.addStrategy = tmpStrategy; tmpFileSupertype.source_dest = source_dest; break; case "ftpUsername": tmpFtpFile.ftpUsername = readerValPriv; break; case "ftpPass": tmpFtpFile.ftpPass = readerValPriv; break; case "ftpUri": tmpFtpFile.ftpUri = readerValPriv; break; case "ftpPort": tmpFtpFile.ftpPort = int.Parse(readerValPriv); break; case "isPassive": tmpFtpFile.isPassive = bool.Parse(readerValPriv); break; case "ftpTimeout": tmpFtpFile.ftpTimeout = int.Parse(readerValPriv); break; case "ftpUseBinary": tmpFtpFile.ftpUseBinary = bool.Parse(readerValPriv); break; case "ftpKeepAlive": tmpFtpFile.ftpKeepAlive = bool.Parse(readerValPriv); break; case "ftpProxyType": tmpFtpFile.ftpProxyType = readerValPriv; break; case "filePath": tmpFileSupertype.filePath = readerValPriv; break; case "maxErrorCout": tmpFileSupertype.errorCount = int.Parse(readerValPriv); break; case "sleepAfterError": tmpFileSupertype.sleepBeforeNext = int.Parse(readerValPriv); break; default: break; } break; case XmlNodeType.EndElement: /* * switch (reader.Name) * { * case "route": * tmpTask.taskRouts.Add(tmpCmdRoute); * break; * }*/ break; } } reader.Close(); }
//private string plannerPath = "Planner.xml"; /// Конструткор для тестов public PlannerText(ControllerOfOutput _outputs, LogOfSuccession _los) { this.outputs = _outputs; this.los = _los; }