From 497eb540fd2fbb90c521936aed57280fe0c93662 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=B7=D0=B0=D0=BC=D0=B0=D1=82=20=D0=98=D1=88=D1=82?= =?UTF-8?q?=D1=83=D0=B3=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Tue, 7 May 2024 02:08:20 +0400 Subject: [PATCH] =?UTF-8?q?7=20=D0=BB=D0=B0=D0=B1.=20=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=20(=D0=BD=D0=B5=20=D0=B4=D0=BE=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0=D0=BD=D0=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 24 +++--- .../MassiveGenericObjects.cs | 15 +++- .../StorageCollection.cs | 38 +++++----- .../Exceptions/CollectionOverflowException.cs | 21 +++++ .../Exceptions/ObjectNotFoundException.cs | 21 +++++ .../PositionOutOfCollectionException.cs | 21 +++++ MotorBoat/MotorBoat/FormBoatCollection.cs | 76 +++++++++++++------ MotorBoat/MotorBoat/MotorBoat.csproj | 6 ++ MotorBoat/MotorBoat/Program.cs | 34 ++++++++- MotorBoat/MotorBoat/serilog.json | 20 +++++ 10 files changed, 217 insertions(+), 59 deletions(-) create mode 100644 MotorBoat/MotorBoat/Exceptions/CollectionOverflowException.cs create mode 100644 MotorBoat/MotorBoat/Exceptions/ObjectNotFoundException.cs create mode 100644 MotorBoat/MotorBoat/Exceptions/PositionOutOfCollectionException.cs create mode 100644 MotorBoat/MotorBoat/serilog.json diff --git a/MotorBoat/MotorBoat/CollectionGenericObjects/ListGenericObjects.cs b/MotorBoat/MotorBoat/CollectionGenericObjects/ListGenericObjects.cs index 586a1d1..c2511c2 100644 --- a/MotorBoat/MotorBoat/CollectionGenericObjects/ListGenericObjects.cs +++ b/MotorBoat/MotorBoat/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@  +using MotorBoat.Exceptions; + namespace MotorBoat.CollectionGenericObjects; /// @@ -45,34 +47,30 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - if (position < 0 || position >= Count) - { - return null; - } - + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(); return _collection[position]; - } public int Insert(T obj) { - if (Count + 1 > _maxCount) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - if (Count + 1 > _maxCount) return -1; - if (position < 0 || position > Count) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); - return 1; + return position; } public T? Remove(int position) { - if (position < 0 || position > Count) return null; - T? temp = _collection[position]; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + T? obj = _collection[position]; _collection.RemoveAt(position); - return temp; + return obj; } public IEnumerable GetItems() diff --git a/MotorBoat/MotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs b/MotorBoat/MotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs index 6469559..dcf7e29 100644 --- a/MotorBoat/MotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/MotorBoat/MotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@  +using MotorBoat.Exceptions; + namespace MotorBoat.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects @@ -39,7 +41,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - if (position < 0 || position >= Count) return null; + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); return _collection[position]; } public int Insert(T obj) @@ -52,15 +54,19 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; + throw new CollectionOverflowException(); } public int Insert(T obj, int position) { - if (position >= Count || position < 0) return -1; + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(); + } if (_collection[position] == null) { _collection[position] = obj; return position; + } int temp = position + 1; while (temp < Count) @@ -86,7 +92,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } public T? Remove(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + if (_collection[position] == null) throw new ObjectNotFoundException(); T? myObject = _collection[position]; _collection[position] = null; return myObject; diff --git a/MotorBoat/MotorBoat/CollectionGenericObjects/StorageCollection.cs b/MotorBoat/MotorBoat/CollectionGenericObjects/StorageCollection.cs index ca01a3d..dd0f08f 100644 --- a/MotorBoat/MotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/MotorBoat/MotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using MotorBoat.Drawnings; +using MotorBoat.Exceptions; namespace MotorBoat.CollectionGenericObjects; @@ -90,15 +91,15 @@ public class StorageCollection } /// - /// Сохранение информации по автомобилям в хранилище в файл + /// Сохранение информации по лодкам в хранилище в файл /// /// /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -134,31 +135,29 @@ public class StorageCollection } } } - return true; } /// - /// Загрузка информации по автомобилям в хранилище из файла + /// Загрузка информации по лодкам в хранилище из файла /// /// >Путь и имя файла /// 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(filename)) { string line = reader.ReadLine(); if (line == null || line.Length == 0) { - return false; + throw new ArgumentException("В файле нет данных"); } if (!line.Equals(_collectionKey)) { - //если нет такой записи, то это не те данные - return false; + throw new InvalidDataException("В файле неверные данные"); } _storages.Clear(); while ((line = reader.ReadLine()) != null) @@ -170,11 +169,8 @@ public class StorageCollection continue; } CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - return false; - } + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? + throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ; collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -182,16 +178,22 @@ public class StorageCollection { if (elem?.CreateDrawningBoat() is T boat) { - if (collection.Insert(boat) == -1) + try { - return false; + if (collection.Insert(boat) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } } - return true; } /// diff --git a/MotorBoat/MotorBoat/Exceptions/CollectionOverflowException.cs b/MotorBoat/MotorBoat/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..b92a34b --- /dev/null +++ b/MotorBoat/MotorBoat/Exceptions/CollectionOverflowException.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 MotorBoat.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/MotorBoat/MotorBoat/Exceptions/ObjectNotFoundException.cs b/MotorBoat/MotorBoat/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..c0f1a9d --- /dev/null +++ b/MotorBoat/MotorBoat/Exceptions/ObjectNotFoundException.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 MotorBoat.Exceptions; + +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/MotorBoat/MotorBoat/Exceptions/PositionOutOfCollectionException.cs b/MotorBoat/MotorBoat/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..a40e4d0 --- /dev/null +++ b/MotorBoat/MotorBoat/Exceptions/PositionOutOfCollectionException.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 MotorBoat.Exceptions; + +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/MotorBoat/MotorBoat/FormBoatCollection.cs b/MotorBoat/MotorBoat/FormBoatCollection.cs index 9160d85..a2b7521 100644 --- a/MotorBoat/MotorBoat/FormBoatCollection.cs +++ b/MotorBoat/MotorBoat/FormBoatCollection.cs @@ -1,5 +1,7 @@ -using MotorBoat.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using MotorBoat.CollectionGenericObjects; using MotorBoat.Drawnings; +using MotorBoat.Exceptions; namespace MotorBoat; @@ -16,13 +18,16 @@ public partial class FormBoatCollection : Form /// Компания /// private AbstractCompany? _company = null; + + private readonly ILogger _logger; /// /// Конструктор /// - public FormBoatCollection() + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// /// Выбор компании @@ -60,15 +65,17 @@ public partial class FormBoatCollection : Form { return; } - - if (_company + boat != -1) + try { + int addingObject = (_company + boat); MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект {boat.GetDataForSave()}"); pictureBox.Image = _company.Show(); } - else + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } } /// @@ -80,6 +87,7 @@ public partial class FormBoatCollection : Form { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { + _logger.LogWarning("Удаление объекта из несуществующей коллекции"); return; } if (MessageBox.Show("Удалить объект?", "Удаление", @@ -88,14 +96,22 @@ public partial class FormBoatCollection : Form return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { + object decrementObject = _company - pos; MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален по позиции {pos}"); pictureBox.Image = _company.Show(); } - else + catch (ObjectNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Объект не найден "); + _logger.LogWarning($"Удаление не найденного объекта в позиции {pos} "); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show("Удаление вне рамках коллекции"); + _logger.LogWarning($"Удаление объекта за пределами коллекции {pos} "); } } /// @@ -113,11 +129,17 @@ public partial class FormBoatCollection : Form int counter = 100; while (boat == null) { - boat = _company.GetRandomObject(); - counter--; - if (counter <= 0) + try { - break; + boat = _company.GetRandomObject(); + } + catch (ObjectNotFoundException) + { + counter--; + if (counter <= 0) + { + break; + } } } if (boat == null) @@ -154,6 +176,7 @@ public partial class FormBoatCollection : Form { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не заполненная коллекция"); return; } CollectionType collectionType = CollectionType.None; @@ -166,6 +189,7 @@ public partial class FormBoatCollection : Form collectionType = CollectionType.List; } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}"); RerfreshListBoxItems(); } /// @@ -182,15 +206,17 @@ public partial class FormBoatCollection : Form if (listBoxCollection.SelectedIndex < 0) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Удаление невыбранной коллекции"); return; } - + string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation($"Удалена коллекция: {name}"); RerfreshListBoxItems(); } /// @@ -218,6 +244,7 @@ public partial class FormBoatCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Создание компании невыбранной коллекции"); return; } ICollectionGenericObjects? collection = @@ -225,6 +252,7 @@ public partial class FormBoatCollection : Form if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); + _logger.LogWarning("Не удалось инициализировать коллекцию"); return; } switch (comboBoxSelectorCompany.Text) @@ -246,15 +274,16 @@ public partial class FormBoatCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -268,14 +297,17 @@ public partial class FormBoatCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName); RerfreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось сохранить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/MotorBoat/MotorBoat/MotorBoat.csproj b/MotorBoat/MotorBoat/MotorBoat.csproj index af03d74..f60d5d4 100644 --- a/MotorBoat/MotorBoat/MotorBoat.csproj +++ b/MotorBoat/MotorBoat/MotorBoat.csproj @@ -8,6 +8,12 @@ enable + + + + + + True diff --git a/MotorBoat/MotorBoat/Program.cs b/MotorBoat/MotorBoat/Program.cs index 4052ad6..8428796 100644 --- a/MotorBoat/MotorBoat/Program.cs +++ b/MotorBoat/MotorBoat/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; +using Serilog; + namespace MotorBoat { internal static class Program @@ -8,8 +13,33 @@ namespace MotorBoat [STAThread] static void Main() { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormBoatCollection()); + ServiceCollection services = new(); + 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: "serilog.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 +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/serilog.json b/MotorBoat/MotorBoat/serilog.json new file mode 100644 index 0000000..31229f2 --- /dev/null +++ b/MotorBoat/MotorBoat/serilog.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": "MotorBoat" + } + } +} \ No newline at end of file