From 745fe9e98f902b070b9789d6ee6ff89d81cfee1f Mon Sep 17 00:00:00 2001 From: katana Date: Sat, 2 Dec 2023 14:47:29 +0400 Subject: [PATCH] =?UTF-8?q?7=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectSeaplane/FormPlaneCollection.cs | 93 ++++++++++++++----- .../ProjectSeaplane/PlaneNotFoundException.cs | 19 ++++ .../PlanesGenericCollection.cs | 2 +- .../ProjectSeaplane/PlanesGenericStorage.cs | 30 +++--- ProjectSeaplane/ProjectSeaplane/Program.cs | 28 +++++- .../ProjectSeaplane/ProjectSeaplane.csproj | 10 ++ ProjectSeaplane/ProjectSeaplane/SetGeneric.cs | 18 ++-- .../StorageOverflowException.cs | 19 ++++ .../ProjectSeaplane/appsettings.json | 20 ++++ 9 files changed, 192 insertions(+), 47 deletions(-) create mode 100644 ProjectSeaplane/ProjectSeaplane/PlaneNotFoundException.cs create mode 100644 ProjectSeaplane/ProjectSeaplane/StorageOverflowException.cs create mode 100644 ProjectSeaplane/ProjectSeaplane/appsettings.json diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs index df976d8..e334d3b 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs @@ -10,6 +10,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; +using ProjectSeaplane.Exceptions; namespace ProjectSeaplane { @@ -19,13 +22,17 @@ namespace ProjectSeaplane /// Набор объектов /// private readonly PlanesGenericStorage _storage; + private readonly ILogger _logger; + /// /// Конструктор /// - public FormPlaneCollection() + public FormPlaneCollection(ILogger logger) { InitializeComponent(); _storage = new PlanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; + } /// /// Заполнение listBoxObjects @@ -60,10 +67,12 @@ namespace ProjectSeaplane { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Пустое название набора"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } /// /// Выбор набора @@ -85,15 +94,18 @@ namespace ProjectSeaplane { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление невыбранного набора"); return; } - if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } @@ -118,16 +130,26 @@ namespace ProjectSeaplane Action? planeDelegate = new((m) => { - bool q = (obj + m); - if (q) + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) { + _logger.LogWarning("Добавление пустого объекта"); + return; + } + try + { + _ = obj + m; + MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowPlanes(); + _logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}"); } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } + }); form.AddEvent(planeDelegate); form.Show(); @@ -141,6 +163,7 @@ namespace ProjectSeaplane { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; @@ -154,15 +177,33 @@ namespace ProjectSeaplane { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowPlanes(); + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowPlanes(); + _logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}"); + + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}"); + } } - else + catch (PlaneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}"); + + } + catch (Exception ex) + { + MessageBox.Show("Некорректные данные"); + _logger.LogWarning("Некорректные данные"); } } /// @@ -196,16 +237,18 @@ namespace ProjectSeaplane { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } + } } /// @@ -217,17 +260,19 @@ namespace ProjectSeaplane { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); ReloadObjects(); - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } + } } diff --git a/ProjectSeaplane/ProjectSeaplane/PlaneNotFoundException.cs b/ProjectSeaplane/ProjectSeaplane/PlaneNotFoundException.cs new file mode 100644 index 0000000..0e7a208 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/PlaneNotFoundException.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 ProjectSeaplane.Exceptions +{ + [Serializable] + internal class PlaneNotFoundException : ApplicationException + { + public PlaneNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public PlaneNotFoundException() : base() { } + public PlaneNotFoundException(string message) : base(message) { } + public PlaneNotFoundException(string message, Exception exception) : base(message, exception) { } + protected PlaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ProjectSeaplane/ProjectSeaplane/PlanesGenericCollection.cs b/ProjectSeaplane/ProjectSeaplane/PlanesGenericCollection.cs index 224e37e..9da302c 100644 --- a/ProjectSeaplane/ProjectSeaplane/PlanesGenericCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/PlanesGenericCollection.cs @@ -48,7 +48,7 @@ namespace ProjectSeaplane.Generics int height = picHeight / _placeSizeHeight; _pictureWidth = picWidth; _pictureHeight = picHeight; - _collection = new SetGeneric(width * height); + _collection = new SetGeneric(15); } /// /// Перегрузка оператора сложения diff --git a/ProjectSeaplane/ProjectSeaplane/PlanesGenericStorage.cs b/ProjectSeaplane/ProjectSeaplane/PlanesGenericStorage.cs index 36df8ed..0a1c523 100644 --- a/ProjectSeaplane/ProjectSeaplane/PlanesGenericStorage.cs +++ b/ProjectSeaplane/ProjectSeaplane/PlanesGenericStorage.cs @@ -7,6 +7,7 @@ using ProjectSeaplane.DrawningObjects; using ProjectSeaplane.MovementStrategy; using ProjectSeaplane.Generics; using System.IO; +using ProjectSeaplane.Exceptions; namespace ProjectSeaplane.Generics { @@ -30,7 +31,7 @@ namespace ProjectSeaplane.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -49,7 +50,7 @@ namespace ProjectSeaplane.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename, false)) { @@ -57,7 +58,7 @@ namespace ProjectSeaplane.Generics writer.Write(data.ToString()); } - return true; + return; } /// @@ -65,11 +66,11 @@ namespace ProjectSeaplane.Generics /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader reader = new StreamReader(filename)) @@ -77,11 +78,11 @@ namespace ProjectSeaplane.Generics string cheker = reader.ReadLine(); if (cheker == null) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!cheker.StartsWith("PlaneStorage")) { - return false; + throw new Exception("Неверный формат данных"); } _planeStorages.Clear(); string strs; @@ -90,11 +91,11 @@ namespace ProjectSeaplane.Generics { if (strs == null && firstinit) { - return false; + throw new Exception("Нет данных для загрузки"); } if (strs == null) { - return false; + break; } firstinit = false; string name = strs.Split(_separatorForKeyValue)[0]; @@ -105,15 +106,20 @@ namespace ProjectSeaplane.Generics data?.CreateDrawningPlane(_separatorForObject, _pictureWidth, _pictureHeight); if (plane != null) { - if (!(collection + plane)) + try { _ = collection + plane; } + catch (PlaneNotFoundException e) { - return false; + throw e; } + catch (StorageOverflowException e) + { + throw e; + } + } } _planeStorages.Add(name, collection); } - return true; } } diff --git a/ProjectSeaplane/ProjectSeaplane/Program.cs b/ProjectSeaplane/ProjectSeaplane/Program.cs index 0b08fb7..4f15174 100644 --- a/ProjectSeaplane/ProjectSeaplane/Program.cs +++ b/ProjectSeaplane/ProjectSeaplane/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; namespace ProjectSeaplane { internal static class Program @@ -11,7 +15,29 @@ namespace ProjectSeaplane // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormPlaneCollection()); + 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 => + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}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/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj b/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj index 13ee123..2d6a006 100644 --- a/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj +++ b/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True diff --git a/ProjectSeaplane/ProjectSeaplane/SetGeneric.cs b/ProjectSeaplane/ProjectSeaplane/SetGeneric.cs index 2ff9981..81b45b7 100644 --- a/ProjectSeaplane/ProjectSeaplane/SetGeneric.cs +++ b/ProjectSeaplane/ProjectSeaplane/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using ProjectSeaplane.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -52,13 +53,14 @@ namespace ProjectSeaplane.Generics public bool Insert(T plane, int position) { if (position < 0 || position >= _maxCount) - return false; + throw new PlaneNotFoundException(position); - if (Count >= _maxCount) - return false; + if (Count > _maxCount) + { + throw new StorageOverflowException(Count); + } _places.Insert(0, plane); return true; - } /// /// Удаление объекта из набора с конкретной позиции @@ -67,10 +69,8 @@ namespace ProjectSeaplane.Generics /// public bool Remove(int position) { - if (position < 0 || position > _maxCount) - return false; - if (position >= Count) - return false; + if (position < 0 || position > _maxCount || position >= Count) + throw new PlaneNotFoundException(position); _places.RemoveAt(position); return true; } diff --git a/ProjectSeaplane/ProjectSeaplane/StorageOverflowException.cs b/ProjectSeaplane/ProjectSeaplane/StorageOverflowException.cs new file mode 100644 index 0000000..6899c43 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/StorageOverflowException.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 ProjectSeaplane.Exceptions +{ + [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/ProjectSeaplane/ProjectSeaplane/appsettings.json b/ProjectSeaplane/ProjectSeaplane/appsettings.json new file mode 100644 index 0000000..117b959 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/appsettings.json @@ -0,0 +1,20 @@ +{ + "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}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Seaplane" + } + } + } \ No newline at end of file