From ee1f6c16374ab68a12d300bb371e66dd80ba6aca Mon Sep 17 00:00:00 2001 From: Semka Date: Mon, 5 Dec 2022 13:39:50 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D0=93=D0=B5=D0=BD=D0=B5=D1=80=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../GasolineTanker/FormMapWithSetTankers.cs | 37 +++++++++++++------ .../GasolineTanker/MapsCollection.cs | 10 ++--- .../GasolineTanker/SetTankersGeneric.cs | 9 +++++ .../StorageOverflowException.cs | 19 ++++++++++ .../GasolineTanker/TankerNotFoundException.cs | 19 ++++++++++ 5 files changed, 77 insertions(+), 17 deletions(-) create mode 100644 GasolineTanker/GasolineTanker/StorageOverflowException.cs create mode 100644 GasolineTanker/GasolineTanker/TankerNotFoundException.cs diff --git a/GasolineTanker/GasolineTanker/FormMapWithSetTankers.cs b/GasolineTanker/GasolineTanker/FormMapWithSetTankers.cs index b49c652..be08b0b 100644 --- a/GasolineTanker/GasolineTanker/FormMapWithSetTankers.cs +++ b/GasolineTanker/GasolineTanker/FormMapWithSetTankers.cs @@ -126,14 +126,26 @@ namespace GasolineTanker return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + var deletedTanker = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (deletedTanker != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (TankerNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } @@ -184,13 +196,15 @@ namespace GasolineTanker { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } @@ -203,14 +217,15 @@ namespace GasolineTanker { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); ReloadMaps(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/GasolineTanker/GasolineTanker/MapsCollection.cs b/GasolineTanker/GasolineTanker/MapsCollection.cs index 2056157..d01ffec 100644 --- a/GasolineTanker/GasolineTanker/MapsCollection.cs +++ b/GasolineTanker/GasolineTanker/MapsCollection.cs @@ -54,7 +54,7 @@ namespace GasolineTanker /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -68,7 +68,6 @@ namespace GasolineTanker sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } - return true; } /// @@ -76,18 +75,18 @@ namespace GasolineTanker /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader sr = new(filename)) { string str = ""; if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { - return false; + throw new FileFormatException("Формат данных в файле не правильный"); } _mapStorages.Clear(); while ((str = sr.ReadLine()) != null) @@ -111,7 +110,6 @@ namespace GasolineTanker _mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } - return true; } } } diff --git a/GasolineTanker/GasolineTanker/SetTankersGeneric.cs b/GasolineTanker/GasolineTanker/SetTankersGeneric.cs index e49a163..b575010 100644 --- a/GasolineTanker/GasolineTanker/SetTankersGeneric.cs +++ b/GasolineTanker/GasolineTanker/SetTankersGeneric.cs @@ -18,7 +18,12 @@ return Insert(tanker, 0); } public int Insert(T tanker, int position) + { + if (Count == _maxCount) + { + throw new StorageOverflowException(_maxCount); + } if (position <= _places.Count && _places.Count < _maxCount && position >= 0) { _places.Insert(position, tanker); @@ -29,6 +34,10 @@ } public T Remove(int position) { + if (position >= Count || position < 0) + { + throw new TankerNotFoundException(position); + } if (position < _places.Count && position >= 0) { var tanker = _places[position]; diff --git a/GasolineTanker/GasolineTanker/StorageOverflowException.cs b/GasolineTanker/GasolineTanker/StorageOverflowException.cs new file mode 100644 index 0000000..2fff93b --- /dev/null +++ b/GasolineTanker/GasolineTanker/StorageOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GasolineTanker +{ + [Serializable] + internal class StorageOverflowException : ApplicationException + { + public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { } + public StorageOverflowException() : base() { } + public StorageOverflowException(string message) : base(message) { } + public StorageOverflowException(string message, Exception exception) : base(message, exception) { } + protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/GasolineTanker/GasolineTanker/TankerNotFoundException.cs b/GasolineTanker/GasolineTanker/TankerNotFoundException.cs new file mode 100644 index 0000000..525c84f --- /dev/null +++ b/GasolineTanker/GasolineTanker/TankerNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace GasolineTanker +{ + [Serializable] + internal class TankerNotFoundException : ApplicationException + { + public TankerNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public TankerNotFoundException() : base() { } + public TankerNotFoundException(string message) : base(message) { } + public TankerNotFoundException(string message, Exception exception) : base(message, exception) { } + protected TankerNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} -- 2.25.1 From 858eabc855b5a0019155c972e6404670e94a49fb Mon Sep 17 00:00:00 2001 From: Semka Date: Mon, 12 Dec 2022 23:05:02 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9B=D0=BE=D0=B3=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../GasolineTanker/FormMapWithSetTankers.cs | 54 ++++++++++++++----- .../GasolineTanker/GasolineTanker.csproj | 24 +++++++++ GasolineTanker/GasolineTanker/Program.cs | 48 ++++++++++++++++- .../GasolineTanker/appsettings.json | 19 +++++++ GasolineTanker/GasolineTanker/nlog.config | 13 +++++ 5 files changed, 142 insertions(+), 16 deletions(-) create mode 100644 GasolineTanker/GasolineTanker/appsettings.json create mode 100644 GasolineTanker/GasolineTanker/nlog.config diff --git a/GasolineTanker/GasolineTanker/FormMapWithSetTankers.cs b/GasolineTanker/GasolineTanker/FormMapWithSetTankers.cs index be08b0b..65fdef8 100644 --- a/GasolineTanker/GasolineTanker/FormMapWithSetTankers.cs +++ b/GasolineTanker/GasolineTanker/FormMapWithSetTankers.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -20,10 +21,11 @@ namespace GasolineTanker { "Лужайка", new FormLawn() } }; private readonly MapsCollection _mapsCollection; - - public FormMapWithSetTankers() + private ILogger _logger; + public FormMapWithSetTankers(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -57,20 +59,24 @@ namespace GasolineTanker if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта"); return; } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}"); } private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } private void ButtonDeleteMap_Click(object sender, EventArgs e) @@ -82,6 +88,7 @@ namespace GasolineTanker if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } @@ -95,19 +102,29 @@ namespace GasolineTanker } private void InsertTankerCheck(DrawningTanker _tanker) { - if (listBoxMaps.SelectedIndex == -1) + try { - return; + if (listBoxMaps.SelectedIndex == -1) + { + return; + } + DrawningObjectTanker tanker = new(_tanker); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + tanker >= 0) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Tanker}", _tanker); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Не удалось добавить объект"); + } } - DrawningObjectTanker tanker = new(_tanker); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + tanker >= 0) + catch (StorageOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message); + MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -132,19 +149,23 @@ namespace GasolineTanker if (deletedTanker != null) { MessageBox.Show("Объект удален"); + _logger.LogInformation("Из текущей карты удалён объект {@Tanker}", deletedTanker); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); } else { + _logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos); MessageBox.Show("Не удалось удалить объект"); } } catch (TankerNotFoundException ex) { + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); MessageBox.Show($"Ошибка удаления: {ex.Message}"); } catch (Exception ex) { + _logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message); MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } @@ -199,12 +220,15 @@ namespace GasolineTanker try { _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } catch (Exception ex) { - MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); } } } @@ -220,11 +244,13 @@ namespace GasolineTanker try { _mapsCollection.LoadData(openFileDialog.FileName); + _logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName); ReloadMaps(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { + _logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message); MessageBox.Show($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/GasolineTanker/GasolineTanker/GasolineTanker.csproj b/GasolineTanker/GasolineTanker/GasolineTanker.csproj index 13ee123..f55425c 100644 --- a/GasolineTanker/GasolineTanker/GasolineTanker.csproj +++ b/GasolineTanker/GasolineTanker/GasolineTanker.csproj @@ -8,6 +8,30 @@ enable + + + + + + + Always + + + + + + + + + + + + + + + + + True diff --git a/GasolineTanker/GasolineTanker/Program.cs b/GasolineTanker/GasolineTanker/Program.cs index 968b3dd..208169c 100644 --- a/GasolineTanker/GasolineTanker/Program.cs +++ b/GasolineTanker/GasolineTanker/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Microsoft.Extensions.Configuration; namespace GasolineTanker { internal static class Program @@ -11,7 +15,47 @@ namespace GasolineTanker // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetTankers()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } } + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "appsettings.json") + .Build(); + + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); + } +/* private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton(); + + var serilogLogger = new LoggerConfiguration() + .WriteTo.RollingFile("Logs\\log.txt") + .CreateLogger(); + + services.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger: serilogLogger, dispose: true); + }); + + }*/ } -} \ No newline at end of file + +} + diff --git a/GasolineTanker/GasolineTanker/appsettings.json b/GasolineTanker/GasolineTanker/appsettings.json new file mode 100644 index 0000000..52d9b60 --- /dev/null +++ b/GasolineTanker/GasolineTanker/appsettings.json @@ -0,0 +1,19 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "outputTemplate": "{Timestamp:HH:mm:ss. zzz} [{Level}] {Message} {Exception} {NewLine}", + "path": "D:/log.txt", + "fileSizeLimitBytes": 2147483648 + } + } + ], + "Properties": { + "Application": "Serilog-Demo" + } + } +} \ No newline at end of file diff --git a/GasolineTanker/GasolineTanker/nlog.config b/GasolineTanker/GasolineTanker/nlog.config new file mode 100644 index 0000000..5303f93 --- /dev/null +++ b/GasolineTanker/GasolineTanker/nlog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file -- 2.25.1 From 7e5c3bbec22ad0f057195cdc108b3a1a980dec93 Mon Sep 17 00:00:00 2001 From: Semka Date: Mon, 12 Dec 2022 23:06:31 +0400 Subject: [PATCH 3/3] fix --- GasolineTanker/GasolineTanker/Program.cs | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/GasolineTanker/GasolineTanker/Program.cs b/GasolineTanker/GasolineTanker/Program.cs index 208169c..bb29d1d 100644 --- a/GasolineTanker/GasolineTanker/Program.cs +++ b/GasolineTanker/GasolineTanker/Program.cs @@ -40,21 +40,6 @@ namespace GasolineTanker option.AddSerilog(logger); }); } -/* private static void ConfigureServices(ServiceCollection services) - { - services.AddSingleton(); - - var serilogLogger = new LoggerConfiguration() - .WriteTo.RollingFile("Logs\\log.txt") - .CreateLogger(); - - services.AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddSerilog(logger: serilogLogger, dispose: true); - }); - - }*/ } } -- 2.25.1