From 971fa53780385dd1ea8b13dd84b02064d2cb0229 Mon Sep 17 00:00:00 2001 From: Danil Malin Date: Thu, 17 Nov 2022 21:07:16 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=BC=D0=B5=D0=B6=D1=83?= =?UTF-8?q?=D1=82=D0=BE=D1=87=D0=BD=D1=8B=D0=B9=20=D0=BA=D0=BE=D0=BC=D0=BC?= =?UTF-8?q?=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FormMapWithSetLocomotives.cs | 85 +++++++++++++++---- .../LocomotiveNotFoundException.cs | 19 +++++ .../WarmlyLocomotive/MapsCollection.cs | 10 +-- WarmlyLocomotive/WarmlyLocomotive/Program.cs | 25 +++++- .../WarmlyLocomotive/SetLocomotivesGeneric.cs | 4 +- .../StorageOverflowException.cs | 19 +++++ .../WarmlyLocomotive/WarmlyLocomotive.csproj | 9 ++ 7 files changed, 144 insertions(+), 27 deletions(-) create mode 100644 WarmlyLocomotive/WarmlyLocomotive/LocomotiveNotFoundException.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/StorageOverflowException.cs diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs index 870cd4f..69815da 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -27,11 +28,16 @@ namespace WarmlyLocomotive /// private readonly MapsCollection _mapsCollection; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormMapWithSetLocomotives() + public FormMapWithSetLocomotives(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -77,14 +83,29 @@ namespace WarmlyLocomotive return; } DrawningObjectLocomotive locomotive = new(drawningLocomotive); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive != -1) + { + _logger.LogInformation($"Добавление объекта {locomotive}"); + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogInformation("Не удалось добавить объект"); + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}"); + MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + catch (Exception ex) + { + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } /// @@ -107,14 +128,30 @@ namespace WarmlyLocomotive 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 deletedLocomotive = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (deletedLocomotive != null) + { + _logger.LogInformation($"Объект {deletedLocomotive} удалён"); + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogInformation($"Не удалось удалить объект по позиции {pos}"); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (LocomotiveNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Ошибка удаления: {ex.Message}"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } /// @@ -183,21 +220,25 @@ namespace WarmlyLocomotive { if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { + _logger.LogInformation("Не все данные заполнены при попытке создании карты"); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { + _logger.LogWarning($"Нет карты с названием {comboBoxSelectorMap.Text}"); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if(textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';')) { + _logger.LogInformation("Присутствуют символы, недопустимые для имени карты"); MessageBox.Show("Присутствуют символы, недопустимые для имени карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } /// /// Выбор карты @@ -207,6 +248,7 @@ namespace WarmlyLocomotive private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Текущая карта сменена на {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } /// /// Удаление карты @@ -224,6 +266,7 @@ namespace WarmlyLocomotive { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } } /// @@ -235,13 +278,16 @@ namespace WarmlyLocomotive { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.LogInformation($"Успешное сохранение по пути {saveFileDialog.FileName}"); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить данные. Ошибка - {ex.Message}"); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -254,14 +300,17 @@ namespace WarmlyLocomotive { if(openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); ReloadMaps(); + _logger.LogInformation($"Успешная загрузка по пути {openFileDialog.FileName}"); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось загрузить данные. Ошибка - {ex.Message}"); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/WarmlyLocomotive/WarmlyLocomotive/LocomotiveNotFoundException.cs b/WarmlyLocomotive/WarmlyLocomotive/LocomotiveNotFoundException.cs new file mode 100644 index 0000000..20e2daa --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/LocomotiveNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace WarmlyLocomotive +{ + [Serializable] + internal class LocomotiveNotFoundException : ApplicationException + { + public LocomotiveNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public LocomotiveNotFoundException() : base() { } + public LocomotiveNotFoundException(string message) : base(message) { } + public LocomotiveNotFoundException(string message, Exception exception) : base(message, exception) { } + protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs b/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs index 54991f0..7ca3dbb 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs @@ -94,7 +94,7 @@ namespace WarmlyLocomotive /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -108,18 +108,17 @@ namespace WarmlyLocomotive sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } - return true; } /// /// Загрузка информации по локомотивам в депо из файла /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader sr = new(filename)) { @@ -127,7 +126,7 @@ namespace WarmlyLocomotive if (!str.Contains("MapsCollection")) { //если нет такой записи, то это не те данные - return false; + throw new FileFormatException("Формат данных в файле не правильный"); } _mapStorages.Clear(); while ((str = sr.ReadLine()) != null) @@ -150,7 +149,6 @@ namespace WarmlyLocomotive _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } - return true; } } } diff --git a/WarmlyLocomotive/WarmlyLocomotive/Program.cs b/WarmlyLocomotive/WarmlyLocomotive/Program.cs index 5334215..5b23774 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/Program.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; namespace WarmlyLocomotive { internal static class Program @@ -11,7 +16,25 @@ namespace WarmlyLocomotive // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetLocomotives()); + 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 serilogLogger = new LoggerConfiguration() + .WriteTo.File("LogOfProgram.txt") + .CreateLogger(); + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(serilogLogger, true); + }); } } } \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs b/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs index 28765de..050f49a 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs @@ -46,7 +46,7 @@ namespace WarmlyLocomotive { if (position < 0 || position > Count || _maxCount == Count) { - return -1; + throw new StorageOverflowException(Count); } _places.Insert(position, locomotive); return position; @@ -60,7 +60,7 @@ namespace WarmlyLocomotive { if (position < 0 || position >= Count) { - return null; + throw new LocomotiveNotFoundException(position); } T memoryObj = _places[position]; _places.RemoveAt(position); diff --git a/WarmlyLocomotive/WarmlyLocomotive/StorageOverflowException.cs b/WarmlyLocomotive/WarmlyLocomotive/StorageOverflowException.cs new file mode 100644 index 0000000..444fefd --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/StorageOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace WarmlyLocomotive +{ + [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 contex) : base(info, contex) { } + } +} diff --git a/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj b/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj index 13ee123..af6aa60 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj +++ b/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj @@ -8,6 +8,15 @@ enable + + + + + + + + + True -- 2.25.1 From eb23baf4905031c11f97f82ef55f711242d3f654 Mon Sep 17 00:00:00 2001 From: Danil Malin Date: Mon, 21 Nov 2022 20:48:57 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9D=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C=D1=88?= =?UTF-8?q?=D0=BE=D0=B5=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs index 69815da..933cd2a 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs @@ -226,7 +226,7 @@ namespace WarmlyLocomotive } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { - _logger.LogWarning($"Нет карты с названием {comboBoxSelectorMap.Text}"); + _logger.LogInformation($"Нет карты с названием {comboBoxSelectorMap.Text}"); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } -- 2.25.1 From d83609741b9b226b5b3a06b80d7c943bbc336097 Mon Sep 17 00:00:00 2001 From: Danil Malin Date: Thu, 24 Nov 2022 20:18:22 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D0=9C=D0=B0=D0=BB=D0=B5=D0=BD=D1=8C=D0=BA?= =?UTF-8?q?=D0=B8=D0=B9=20=D1=84=D0=B8=D0=BA=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs b/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs index 050f49a..b579117 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs @@ -46,7 +46,7 @@ namespace WarmlyLocomotive { if (position < 0 || position > Count || _maxCount == Count) { - throw new StorageOverflowException(Count); + throw new StorageOverflowException(_maxCount); } _places.Insert(position, locomotive); return position; -- 2.25.1