Пример #1
0
        private async void SendAndDownload()
        {
            try
            {
                IsBusy = true;
                AddLog("Start Downloading.");
                var file = await _downloadService.DownloadFile(Url);

                AddLog("Start Sending.");
                var mailService = new MailSendService(
                    ConfigLoader.LoadConfig(),
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
                AddLog("Spliting files.");
                var tasks = await mailService.SplitTasks(file);

                ProgressViewModel = new ProgressViewModel(tasks);
                AddLog("Sending files.");
                mailService.SendEmail(tasks);
                AddLog("Send sucessed.");

                _messageService.LongAlert($"Finished.");
            }
            catch (Exception ex)
            {
                AddLog("Send fialed.");
                _messageService.LongAlert($"Error encountered:{ex.ToString()}");
            }
            finally
            {
                IsBusy = false;
            }
        }
Пример #2
0
        private void ProcessJSON(JArray array)
        {
            try
            {
                List <Comic>    collectionNoDownload = new List <Comic>();
                List <Comic>    collectionNoRename   = new List <Comic>();
                DownloadService downloadService      = new DownloadService(ApiMega);
                ReportService   reportService        = new ReportService();
                FileService     fileService          = new FileService();
                int             cont = 1;
                foreach (JObject c in array.OfType <JObject>())
                {
                    //Convert Object
                    Comic comic = new Comic(cont++, c.GetValue("name").ToString().Replace(Constantes.BarraLateral, Constantes.Ampersand), c.GetValue("link").ToString());
                    Console.WriteLine(comic.Name);
                    logger.Warn(string.Format("Inicio: {0}", comic.ToString()));
                    logger.Info(string.Format("JSON: {0}", Comic.Serializer(new List <Comic> {
                        comic
                    }, false)));

                    //Rename File
                    if (downloadService.DownloadFile(comic))
                    {
                        if (!fileService.RenameFile(comic))
                        {
                            collectionNoRename.Add(comic);
                        }
                    }
                    else
                    {
                        collectionNoDownload.Add(comic);
                    }

                    logger.Warn(string.Format("Fin: {0}", comic.ToString()));
                }

                if (collectionNoDownload.Any())
                {
                    reportService.CreateFileReport(collectionNoDownload, "NoDownload.json");
                }
                if (collectionNoRename.Any())
                {
                    reportService.CreateFileReport(collectionNoRename, "NoRename.json");
                }
            }
            catch (Exception ex)
            {
                if (logger != null)
                {
                    logger.Error(string.Format("Error en el método: '{0}', Mensaje de error: '{1}'", MethodBase.GetCurrentMethod().Name, ex.Message));
                }
            }
        }
Пример #3
0
        public void ExecuteCommand(Socket socket, ServerCommand command, Socket socketUDPWrite, Socket socketUDPRead, TripleEndPointModel endPoint)
        {
            switch (command.Type)
            {
            case CommandType.Echo:
                baseCommandService.EchoHandler(socket, command);
                return;

            case CommandType.Time:
                baseCommandService.TimeHandler(socket);
                return;

            case CommandType.Close:
                baseCommandService.CloseHandler(socket, socketUDPRead, socketUDPWrite);
                return;

            case CommandType.Download:
                downloadService.DownloadFile(socket, endPoint.EndPoint, socketUDPWrite, command, ProtocolType.Tcp);
                return;

            case CommandType.Upload:
                uploadService.UploadFile(socket, endPoint.EndPoint, socketUDPRead, command, ProtocolType.Tcp);
                return;

            case CommandType.DownloadUDP:
                downloadService.DownloadFile(socket, endPoint.EndPointUDPWrite, socketUDPWrite, command, ProtocolType.Udp);
                return;

            case CommandType.UploadUDP:
                uploadService.UploadFile(socket, endPoint.EndPointUDPRead, socketUDPRead, command, ProtocolType.Udp);
                return;

            case CommandType.Unknown:
                baseCommandService.UnknownHandler(socket);
                return;
            }
        }
Пример #4
0
        void DoWork()
        {
            try
            {
                Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyyHH:mm:ss")} Сервис запущен");
                DownloadService service = new DownloadService();
                Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Идёт скачивание файла GeoLite2-City-CSV.zip ");

                if (string.IsNullOrEmpty(ConfigurationService.DownloadFileHref))
                {
                    throw new Exception("Настройте ключ DownloadFileHref в конфиг файле App.config");
                }
                string filePath = service.DownloadFile(ConfigurationService.DownloadFileHref);


                // обновляем только в среду, так как данные на сайте обновляются только во вторник или указана AlwaysUpdate=true в конфиге
                if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || ConfigurationService.AlwaysUpdate)
                {
                    CSVService    csvServ    = new CSVService();
                    GeoRepository repository = new GeoRepository();

                    string filePathLocations = string.Format($"{filePath}\\{fileNameLocations}");

                    if (!File.Exists(filePathLocations))
                    {
                        throw new Exception($"Загруженный файл {fileNameLocations} не был найден");
                    }

                    Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Идёт считывание файла GeoLite2-City-Locations-ru.csv, подождите... ");
                    var itemsLocations = csvServ.GetDataTabletFromCSVFile(filePathLocations); // загружаем файл Locations
                    Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Запись в базу файла GeoLite2-City-Locations-ru.csv, подождите...");
                    repository.DeleteData("Stp_ClearCityLocationRu");
                    repository.InsertDataUsingSQLBulkCopy(itemsLocations, "CityLocationsRu");

                    string filePathCity = string.Format($"{filePath}\\{fileNameCity}");

                    if (!File.Exists(filePathCity))
                    {
                        throw new Exception($"Загруженный файл {fileNameCity} не был найден");
                    }

                    Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Идёт считывание файла GeoLite2-City-Blocks-IPv4.csv, подождите... ");
                    var itemsCity = csvServ.GetDataTabletFromCSVFile(filePathCity); // загружаем файл City
                    Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Запись в базу файла GeoLite2-City-Blocks-IPv4.csv, подождите...");
                    repository.DeleteData("Stp_ClearCityBlocksIPv4");
                    repository.InsertDataUsingSQLBulkCopy(itemsCity, "CityBlocksIPv4");

                    Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Данные в базе были обновлены");
                }
                else
                {
                    Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Данные не требуют обновления");
                }

                Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Работа сервиса завершена успешно ");
                Thread.Sleep(new TimeSpan(ConfigurationService.AfterDaysToRunApp, 0, 0, 0)); // настраиваем через какое время запускаться, ключ вынесен в конфиг
                DoWork();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex?.Message} {ex?.InnerException}");
                Console.ReadLine();
            }
        }
Пример #5
0
        private void Download_Click(object sender, RoutedEventArgs e)
        {
            string URL = paramter[3];

            if (string.IsNullOrEmpty(URL))
            {
                this.Log          = "请求的下载地址是空,请检查!";
                logTextBlock.Text = Log;
                return;
            }
            this.updataGrid.Visibility   = Visibility.Collapsed;
            this.progressGrid.Visibility = Visibility.Visible;
            string save = "./temp";

            if (!Directory.Exists(save))
            {
                Directory.CreateDirectory(save);
            }

            string fileName = System.IO.Path.GetFileName(URL);

            string savePath = System.IO.Path.Combine(save, fileName);

            Action <string, string> action = (current, total) =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    this.Log            = $"正在下载...{FormatBytes(long.Parse(current)).PadLeft(10, ' ')} / {FormatBytes(long.Parse(total))}";
                    logTextBlock.Text   = Log;
                    this.progress.Value = (int)((double.Parse(current) / double.Parse(total)) * 100);

                    if (current == total)
                    {
                        this.progress.Value = 100;

                        Task.Delay(1000).ContinueWith(l =>
                        {
                            this.Dispatcher.Invoke(() =>
                            {
                                this.Log                    = $"下载完成!";
                                logTextBlock.Text           = Log;
                                this.confirmGrid.Visibility = Visibility.Collapsed;
                                this.unzipGrid.Visibility   = Visibility.Visible;
                                ZipUtil zipUtil             = new ZipUtil();
                                zipUtil.UnZipEvent         += OnUnzip;
                                var result                  = zipUtil.UnZip("./temp/Update.zip", "./");
                                if (result)
                                {
                                    if (StartMain("SmartTools.Net"))
                                    {
                                        this.Close();
                                    }
                                }
                            });
                        });

                        this.confirmGrid.Visibility  = Visibility.Visible;
                        this.updataGrid.Visibility   = Visibility.Collapsed;
                        this.progressGrid.Visibility = Visibility.Collapsed;
                    }
                });
            };

            Task.Run(() =>
            {
                DownloadService.DownloadFile(URL, savePath, action, 1000);
            });
        }