/// <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));
                }
            }
        }
示例#4
0
        /// <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);
        }
 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("Во время создания роута произошла ошибка");
     }
 }
示例#6
0
        //Проверка задания на тему того, надо ли запускать ее еще раз
        //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);
        }
        /// <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);
        }
示例#8
0
        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();
        }
示例#9
0
        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);
                     */
                }
            }
        }