From 60da240f7abf0ebf8575a60f0c0e9986eefa2f12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=B8=D1=82=D0=B0=20=D0=A7=D0=B5=D1=80?= =?UTF-8?q?=D0=BD=D1=8B=D1=88=D0=BE=D0=B2?= Date: Thu, 22 Dec 2022 21:20:43 +0400 Subject: [PATCH] =?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.=20=D0=9B?= =?UTF-8?q?=D0=BE=D0=B3=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5.?= =?UTF-8?q?=20Serilog.=20=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=B2=20MapsCollection.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Warship/Warship/AircraftCarrier.csproj | 21 +++++ Warship/Warship/FormMapWithSetWarship.cs | 91 +++++++++++++++------ Warship/Warship/MapsCollection.cs | 10 +-- Warship/Warship/Program.cs | 30 ++++++- Warship/Warship/SetWarshipGeneric.cs | 21 +++-- Warship/Warship/StorageOverflowException.cs | 19 +++++ Warship/Warship/WarshipNotFoundException.cs | 19 +++++ Warship/Warship/appsettings.json | 16 ++++ 8 files changed, 190 insertions(+), 37 deletions(-) create mode 100644 Warship/Warship/StorageOverflowException.cs create mode 100644 Warship/Warship/WarshipNotFoundException.cs create mode 100644 Warship/Warship/appsettings.json diff --git a/Warship/Warship/AircraftCarrier.csproj b/Warship/Warship/AircraftCarrier.csproj index 13ee123..7fa8b82 100644 --- a/Warship/Warship/AircraftCarrier.csproj +++ b/Warship/Warship/AircraftCarrier.csproj @@ -8,6 +8,27 @@ enable + + + + + + + Always + + + + + + + + + + + + + + True diff --git a/Warship/Warship/FormMapWithSetWarship.cs b/Warship/Warship/FormMapWithSetWarship.cs index 8d20824..2f22969 100644 --- a/Warship/Warship/FormMapWithSetWarship.cs +++ b/Warship/Warship/FormMapWithSetWarship.cs @@ -9,6 +9,8 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static System.Windows.Forms.DataFormats; +using Microsoft.Extensions.Logging; +using Serilog.Core; namespace AircraftCarrier { @@ -27,12 +29,17 @@ namespace AircraftCarrier /// private readonly MapsCollection _mapsCollection; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormMapWithSetWarship() + public FormMapWithSetWarship(ILogger logger) { InitializeComponent(); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); + _logger = logger; comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) { @@ -71,15 +78,18 @@ namespace AircraftCarrier if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Какое-то поле пустое", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта"); return; } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Карта отсутсвует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text); } /// /// Выбор карты @@ -89,6 +99,7 @@ namespace AircraftCarrier 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); } /// /// Удаление карты @@ -104,6 +115,7 @@ namespace AircraftCarrier if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } } @@ -125,22 +137,29 @@ namespace AircraftCarrier /// private void AddWarshipOnForm(DrawingWarship drawningWarship) { - if (listBoxMaps.SelectedIndex == -1) + try { - return; + if (listBoxMaps.SelectedIndex == -1) + { + return; + } + else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectWarship(drawningWarship) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Warship}", drawningWarship); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить объект"); + } } - - DrawingObjectWarship warship = new(drawningWarship); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + warship >= 0) + catch (StorageOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message); + MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } /// /// Удаление объекта @@ -159,14 +178,30 @@ namespace AircraftCarrier 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 deletedWarship = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (deletedWarship != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation("Из текущей карты удален объект {@Warship}", deletedWarship); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (WarshipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning("Неизвестная ошибка", ex.Message); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } /// @@ -235,13 +270,16 @@ namespace AircraftCarrier { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); } } } @@ -254,14 +292,17 @@ namespace AircraftCarrier { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _mapsCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName); ReloadMaps(); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message); } } } diff --git a/Warship/Warship/MapsCollection.cs b/Warship/Warship/MapsCollection.cs index 4cd0d4f..e56fd71 100644 --- a/Warship/Warship/MapsCollection.cs +++ b/Warship/Warship/MapsCollection.cs @@ -78,7 +78,7 @@ namespace AircraftCarrier /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -92,25 +92,24 @@ namespace AircraftCarrier 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 Exception("Файл не найден"); } using (StreamReader sr = new(filename)) { string str = ""; if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { - return false; + throw new Exception("Формат данных в файле неправильный"); } _mapStorages.Clear(); while ((str = sr.ReadLine()) != null) @@ -129,7 +128,6 @@ namespace AircraftCarrier _mapStorages.Add(elem[0], new MapWithSetWarshipsGeneric(_pictureWidth, _pictureHeight, map)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } - return true; } } } diff --git a/Warship/Warship/Program.cs b/Warship/Warship/Program.cs index 6a804d0..498a801 100644 --- a/Warship/Warship/Program.cs +++ b/Warship/Warship/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace AircraftCarrier { internal static class Program @@ -11,7 +16,30 @@ namespace AircraftCarrier // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetWarship()); + 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", optional: false, reloadOnChange: true) + .Build(); + + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); } } } \ No newline at end of file diff --git a/Warship/Warship/SetWarshipGeneric.cs b/Warship/Warship/SetWarshipGeneric.cs index df2462c..e52c7d7 100644 --- a/Warship/Warship/SetWarshipGeneric.cs +++ b/Warship/Warship/SetWarshipGeneric.cs @@ -41,6 +41,10 @@ namespace AircraftCarrier { return Insert(ship, 0); } + private bool isCorrectPosition(int position) + { + return 0 <= position && position < _maxCount; + } /// /// Добавление объекта в набор на конкретную позицию /// @@ -49,8 +53,14 @@ namespace AircraftCarrier /// public int Insert(T ship, int position) { - if (position >= _maxCount || position < 0) return -1; _places.Insert(position, ship); - return 1; + if (Count == _maxCount) + throw new StorageOverflowException(_maxCount); + if (!isCorrectPosition(position)) + { + return -1; + } + _places.Insert(position, ship); + return position; } /// /// Удаление объекта из набора с конкретной позиции @@ -59,10 +69,11 @@ namespace AircraftCarrier /// public T Remove(int position) { - if (position >= _maxCount || position < 0) + if (!isCorrectPosition(position)) return null; - - var result = _places[position]; + var result = this[position]; + if (result == null) + throw new WarshipNotFoundException(position); _places.RemoveAt(position); return result; } diff --git a/Warship/Warship/StorageOverflowException.cs b/Warship/Warship/StorageOverflowException.cs new file mode 100644 index 0000000..d6f6a32 --- /dev/null +++ b/Warship/Warship/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 AircraftCarrier +{ + [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/Warship/Warship/WarshipNotFoundException.cs b/Warship/Warship/WarshipNotFoundException.cs new file mode 100644 index 0000000..40638c3 --- /dev/null +++ b/Warship/Warship/WarshipNotFoundException.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 AircraftCarrier +{ + [Serializable] + internal class WarshipNotFoundException : ApplicationException + { + public WarshipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public WarshipNotFoundException() : base() { } + public WarshipNotFoundException(string message) : base(message) { } + public WarshipNotFoundException(string message, Exception exception) : base(message, exception) { } + protected WarshipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/Warship/Warship/appsettings.json b/Warship/Warship/appsettings.json new file mode 100644 index 0000000..6e66299 --- /dev/null +++ b/Warship/Warship/appsettings.json @@ -0,0 +1,16 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ] + } +} \ No newline at end of file -- 2.25.1