From dd87d4fba8fe20b6706961110baf89b15ee29758 Mon Sep 17 00:00:00 2001 From: "Pyatkin I.A" <4234.sunrise.234@gmail.com> Date: Fri, 8 Dec 2023 18:06:25 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=B5=D0=B4=D1=8C=D0=BC=D0=B0=D1=8F=20?= =?UTF-8?q?=D0=B1=D0=B0=D0=B7=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=BB=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ExcavatorGenericStorage.cs | 30 ++++--- .../ExcavatorNotFoundException.cs | 16 ++++ .../FormExcavatorCollection.cs | 83 +++++++++++++------ ProjectExcavator/ProjectExcavator/Program.cs | 30 ++++++- .../ProjectExcavator/ProjectExcavator.csproj | 11 +++ .../ProjectExcavator/SetGeneric.cs | 19 ++--- .../StorageOverflowException.cs | 15 ++++ .../ProjectExcavator/appsettings.json | 20 +++++ 8 files changed, 173 insertions(+), 51 deletions(-) create mode 100644 ProjectExcavator/ProjectExcavator/ExcavatorNotFoundException.cs create mode 100644 ProjectExcavator/ProjectExcavator/StorageOverflowException.cs create mode 100644 ProjectExcavator/ProjectExcavator/appsettings.json diff --git a/ProjectExcavator/ProjectExcavator/ExcavatorGenericStorage.cs b/ProjectExcavator/ProjectExcavator/ExcavatorGenericStorage.cs index 5e66d0e..5fca65b 100644 --- a/ProjectExcavator/ProjectExcavator/ExcavatorGenericStorage.cs +++ b/ProjectExcavator/ProjectExcavator/ExcavatorGenericStorage.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using ProjectExcavator.DrawingObjects; +using ProjectExcavator.Exceptions; using ProjectExcavator.Generics; using ProjectExcavator.MovementStrategy; @@ -101,7 +102,7 @@ namespace ProjectExcavator.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -120,13 +121,12 @@ namespace ProjectExcavator.Generics } if (data.Length == 0) { - return false; + throw new ArgumentException("Нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { writer.WriteLine("excavatorStorages"); writer.Write(data.ToString()); - return true; } } /// @@ -134,19 +134,23 @@ namespace ProjectExcavator.Generics /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader reader = new StreamReader(filename)) { string proverkaline = reader.ReadLine(); - if (proverkaline == null || !proverkaline.StartsWith("excavatorStorages")) + if (proverkaline == null) { - return false; + throw new ArgumentException("Нет данных для загрузки"); + } + if (!proverkaline.StartsWith("excavatorStorages")) + { + throw new InvalidDataException("Неверный формат ввода файла"); } _excavatorStorages.Clear(); @@ -157,7 +161,7 @@ namespace ProjectExcavator.Generics string[] parts = line.Split('|'); if (parts.Length != 2) { - return false; + continue; } string namestorage = parts[0]; @@ -168,16 +172,20 @@ namespace ProjectExcavator.Generics DrawingExcavator? excavator = data?.CreateDrawingExcavator(_separatorForObject, _pictureWidth, _pictureHeight); if (excavator != null) { - if (!(collection + excavator)) + try { _ = collection + excavator; } + catch (ExcavatorNotFoundException ex) { - return false; + throw ex; + } + catch (StorageOverflowException ex) + { + throw ex; } } } _excavatorStorages.Add(namestorage, collection); } - return true; } } } diff --git a/ProjectExcavator/ProjectExcavator/ExcavatorNotFoundException.cs b/ProjectExcavator/ProjectExcavator/ExcavatorNotFoundException.cs new file mode 100644 index 0000000..905d2c3 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/ExcavatorNotFoundException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; +namespace ProjectExcavator.Exceptions +{ + [Serializable] + internal class ExcavatorNotFoundException : ApplicationException + { + public ExcavatorNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public ExcavatorNotFoundException() : base() { } + public ExcavatorNotFoundException(string message) : base(message) { } + public ExcavatorNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected ExcavatorNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs index 828aa94..a519856 100644 --- a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs +++ b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs @@ -1,8 +1,12 @@ using ProjectExcavator.DrawingObjects; using ProjectExcavator.Generics; +using ProjectExcavator.Exceptions; +using Microsoft.Extensions.Logging; using ProjectExcavator.MovementStrategy; using ProjectExcavator.Excavators; -using System.Windows.Forms; +using System.Linq.Expressions; +using System.Xml.Linq; + namespace ProjectExcavator { @@ -16,12 +20,17 @@ namespace ProjectExcavator /// private readonly ExcavatorGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormExcavatorCollection() + public FormExcavatorCollection(ILogger logger) { InitializeComponent(); _storage = new ExcavatorGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -63,10 +72,12 @@ namespace ProjectExcavator { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Пустое название набора"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } /// /// Выбор набора @@ -88,14 +99,16 @@ namespace ProjectExcavator { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление невыбранного набора"); return; } - if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, + 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}"); } } /// @@ -109,26 +122,28 @@ namespace ProjectExcavator { return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning("Добавление пустого объекта"); return; } FormExcavatorConfig form = new FormExcavatorConfig(); - Action? ExcavatorDelegate = (excavator) => + Action ExcavatorDelegate = new Action((excavator) => { - bool SelectedExcavator = obj + excavator; - if (SelectedExcavator) + try { + bool selectedexcavator = obj + excavator; MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowExcavator(); + _logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}"); } - else + catch (StorageOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } - }; + }); form.AddEvent(ExcavatorDelegate); form.Show(); } @@ -141,6 +156,7 @@ namespace ProjectExcavator { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? @@ -155,14 +171,24 @@ namespace ProjectExcavator return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowExcavator(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowExcavator(); + _logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}"); + } } - else + catch (ExcavatorNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}"); } } /// @@ -193,15 +219,16 @@ namespace ProjectExcavator { 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("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } } } @@ -215,10 +242,11 @@ namespace ProjectExcavator // TODO продумать логику if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}"); ReloadObjects(); if (listBoxStorages.SelectedIndex == -1) { @@ -232,10 +260,11 @@ namespace ProjectExcavator } pictureBoxCollection.Image = obj.ShowExcavator(); } - else + catch (Exception ex) { MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } } } diff --git a/ProjectExcavator/ProjectExcavator/Program.cs b/ProjectExcavator/ProjectExcavator/Program.cs index 15b7126..43ce31d 100644 --- a/ProjectExcavator/ProjectExcavator/Program.cs +++ b/ProjectExcavator/ProjectExcavator/Program.cs @@ -1,3 +1,10 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; + namespace ProjectExcavator { internal static class Program @@ -11,8 +18,29 @@ namespace ProjectExcavator // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormExcavatorCollection()); + 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/ProjectExcavator/ProjectExcavator/ProjectExcavator.csproj b/ProjectExcavator/ProjectExcavator/ProjectExcavator.csproj index 13ee123..e5a1d33 100644 --- a/ProjectExcavator/ProjectExcavator/ProjectExcavator.csproj +++ b/ProjectExcavator/ProjectExcavator/ProjectExcavator.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True diff --git a/ProjectExcavator/ProjectExcavator/SetGeneric.cs b/ProjectExcavator/ProjectExcavator/SetGeneric.cs index 4e2bfba..de9a58d 100644 --- a/ProjectExcavator/ProjectExcavator/SetGeneric.cs +++ b/ProjectExcavator/ProjectExcavator/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using ProjectExcavator.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -41,13 +42,7 @@ namespace ProjectExcavator.Generics /// public bool Insert(T excavator) { - // TODO вставка в начало набора - if (_places.Count >= _maxCount) - { - return false; - } - _places.Insert(0, excavator); - return true; + return Insert(excavator, 0); } /// /// Добавление объекта в набор на конкретную позицию @@ -58,14 +53,14 @@ namespace ProjectExcavator.Generics public bool Insert(T excavator, int position) { // TODO проверка позиции - if (position < 0 || position >= _places.Count) + if (position < 0 || position >= _maxCount) { - return false; + throw new ExcavatorNotFoundException(position); } // TODO проверка, что есть место для вставки if (_places.Count >= _maxCount) { - return false; + throw new StorageOverflowException(_places.Count); } // TODO вставка по позиции _places.Insert(position, excavator); @@ -81,7 +76,7 @@ namespace ProjectExcavator.Generics // TODO проверка позиции if (position < 0 || position >= _places.Count) { - return false; + throw new ExcavatorNotFoundException(position); } // TODO удаление объекта из списка _places.RemoveAt(position); diff --git a/ProjectExcavator/ProjectExcavator/StorageOverflowException.cs b/ProjectExcavator/ProjectExcavator/StorageOverflowException.cs new file mode 100644 index 0000000..f1589eb --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/StorageOverflowException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; +namespace ProjectExcavator.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/ProjectExcavator/ProjectExcavator/appsettings.json b/ProjectExcavator/ProjectExcavator/appsettings.json new file mode 100644 index 0000000..3da3040 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/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": "Excavator" + } + } +}