From 9f3af0505b5707863f40774a978d6206def14333 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Tue, 19 Dec 2023 01:03:37 +0400 Subject: [PATCH 1/2] =?UTF-8?q?7=20=D0=B1=D0=B0=D0=B7=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D1=8F=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D0=BD=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectWarmlyShip/FormShipCollection.cs | 85 ++++++++++++++----- .../ProjectWarmlyShip/Program.cs | 28 +++++- .../ProjectWarmlyShip.csproj | 10 +++ .../ProjectWarmlyShip/SetGeneric.cs | 14 +-- .../ShipNotFoundException.cs | 22 +++++ .../ProjectWarmlyShip/ShipsGenericStorage.cs | 35 +++++--- .../StorageOverflowException.cs | 21 +++++ .../ProjectWarmlyShip/appsettings.json | 20 +++++ 8 files changed, 195 insertions(+), 40 deletions(-) create mode 100644 ProjectWarmlyShip/ProjectWarmlyShip/ShipNotFoundException.cs create mode 100644 ProjectWarmlyShip/ProjectWarmlyShip/StorageOverflowException.cs create mode 100644 ProjectWarmlyShip/ProjectWarmlyShip/appsettings.json diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs index c79deaa..c0930e3 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs @@ -11,6 +11,9 @@ using System.Numerics; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; +using ProjectWarmlyShip.Exceptions; namespace ProjectWarmlyShip { @@ -23,12 +26,17 @@ namespace ProjectWarmlyShip /// private readonly ShipsGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormShipCollection() + public FormShipCollection(ILogger logger) { InitializeComponent(); _storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -66,6 +74,7 @@ namespace ProjectWarmlyShip } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } /// /// Выбор набора @@ -89,11 +98,13 @@ namespace ProjectWarmlyShip { return; } - if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() - ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } /// @@ -116,15 +127,24 @@ namespace ProjectWarmlyShip FormShipConfig form = new FormShipConfig(); Action? ShipDelegate = 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.ShowShips(); + _logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}"); } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } }); form.AddEvent(ShipDelegate); @@ -139,6 +159,7 @@ namespace ProjectWarmlyShip { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? @@ -152,15 +173,31 @@ namespace ProjectWarmlyShip { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowShips(); + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowShips(); + _logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}"); + } } - else + catch (ShipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show("Некорректные данные"); + _logger.LogWarning("Некорректные данные"); } } /// @@ -191,15 +228,18 @@ namespace ProjectWarmlyShip { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _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}"); } } } @@ -213,14 +253,17 @@ namespace ProjectWarmlyShip // TODO продумать логику if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); ReloadObjects(); 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/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs b/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs index 2c7e667..963c318 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs @@ -1,3 +1,5 @@ +using System; + namespace ProjectWarmlyShip { internal static class Program @@ -11,7 +13,31 @@ namespace ProjectWarmlyShip // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormShipCollection()); + 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/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj b/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj index 13ee123..3ddff53 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj +++ b/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/SetGeneric.cs b/ProjectWarmlyShip/ProjectWarmlyShip/SetGeneric.cs index e16dc24..840a8bb 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/SetGeneric.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using ProjectWarmlyShip.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Numerics; @@ -53,10 +54,10 @@ namespace ProjectWarmlyShip.Generics public bool Insert(T ship, int position) { if (position < 0 || position >= _maxCount) - return false; + throw new ShipNotFoundException(position); if (Count >= _maxCount) - return false; + throw new StorageOverflowException(Count); _places.Insert(0, ship); return true; @@ -68,10 +69,9 @@ namespace ProjectWarmlyShip.Generics /// public bool Remove(int position) { - if (position < 0 || position > _maxCount) - return false; - if (position >= Count) - return false; + if (position < 0 || position > _places.Count) + throw new ShipNotFoundException(position); + _places.RemoveAt(position); return true; } diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/ShipNotFoundException.cs b/ProjectWarmlyShip/ProjectWarmlyShip/ShipNotFoundException.cs new file mode 100644 index 0000000..2060982 --- /dev/null +++ b/ProjectWarmlyShip/ProjectWarmlyShip/ShipNotFoundException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectWarmlyShip.Exceptions +{ + [Serializable] + internal class ShipNotFoundException : ApplicationException + { + public ShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public ShipNotFoundException() : base() { } + public ShipNotFoundException(string message) : base(message) { } + public ShipNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected ShipNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/ShipsGenericStorage.cs b/ProjectWarmlyShip/ProjectWarmlyShip/ShipsGenericStorage.cs index df35baf..5f11424 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/ShipsGenericStorage.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/ShipsGenericStorage.cs @@ -6,6 +6,8 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ProjectWarmlyShip.Exceptions; +using System.Numerics; namespace ProjectWarmlyShip { @@ -93,7 +95,7 @@ namespace ProjectWarmlyShip /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -112,26 +114,24 @@ namespace ProjectWarmlyShip } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename, false)) { writer.WriteLine("ShipStorage"); writer.Write(data.ToString()); } - - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла /// 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)) @@ -139,17 +139,26 @@ namespace ProjectWarmlyShip string cheker = reader.ReadLine(); if (cheker == null) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!cheker.StartsWith("ShipStorage")) { - return false; + throw new Exception("Неверный формат данных"); } _shipStorages.Clear(); string strs; bool firstinit = true; while ((strs = reader.ReadLine()) != null) { + if (strs == null && firstinit) + { + throw new Exception("Нет данных для загрузки"); + } + if (strs == null) + { + break; + } + firstinit = false; string name = strs.Split(_separatorForKeyValue)[0]; ShipsGenericCollection collection = new(_pictureWidth, _pictureHeight); foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords)) @@ -158,15 +167,19 @@ namespace ProjectWarmlyShip data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight); if (ship != null) { - if (!(collection + ship)) + try { _ = collection + ship; } + catch (ShipNotFoundException e) { - return false; + throw e; + } + catch (StorageOverflowException e) + { + throw e; } } } _shipStorages.Add(name, collection); } - return true; } } } diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/StorageOverflowException.cs b/ProjectWarmlyShip/ProjectWarmlyShip/StorageOverflowException.cs new file mode 100644 index 0000000..8170087 --- /dev/null +++ b/ProjectWarmlyShip/ProjectWarmlyShip/StorageOverflowException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectWarmlyShip.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/ProjectWarmlyShip/ProjectWarmlyShip/appsettings.json b/ProjectWarmlyShip/ProjectWarmlyShip/appsettings.json new file mode 100644 index 0000000..20b8033 --- /dev/null +++ b/ProjectWarmlyShip/ProjectWarmlyShip/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": "WarmlyShip" + } + } +} \ No newline at end of file -- 2.25.1 From 4699d561d48f88c01036f224af50806791a0a9b0 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Tue, 19 Dec 2023 01:09:12 +0400 Subject: [PATCH 2/2] =?UTF-8?q?7=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ProjectWarmlyShip/ProjectWarmlyShip/Program.cs | 6 +++++- .../ProjectWarmlyShip/ProjectWarmlyShip.csproj | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs b/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs index 963c318..9f4d7e4 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; using System; namespace ProjectWarmlyShip @@ -37,7 +41,7 @@ namespace ProjectWarmlyShip option.SetMinimumLevel(LogLevel.Information); option.AddSerilog(logger); - }); + }); } } } \ No newline at end of file diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj b/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj index 3ddff53..e5a1d33 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj +++ b/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj @@ -15,6 +15,7 @@ + -- 2.25.1