From 1545959a0e2120cdf0db61315e4c749eb9e8054d Mon Sep 17 00:00:00 2001 From: vkobi Date: Mon, 6 May 2024 23:50:18 +0400 Subject: [PATCH] =?UTF-8?q?=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=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 21 +-- .../MassiveGenericObjects.cs | 31 ++-- .../StorageCollection.cs | 33 +++-- .../Exceptions/CollectionOverflowException.cs | 16 ++ .../Exceptions/ObjectNotFoundException.cs | 16 ++ .../PositionOutOfCollectionException.cs | 16 ++ .../FormLocomotiveCollection.cs | 139 +++++++++++++----- WarmlyLocomotive/WarmlyLocomotive/Program.cs | 33 ++++- .../WarmlyLocomotive/WarmlyLocomotive.csproj | 19 +++ .../WarmlyLocomotive/serilog.json | 20 +++ 10 files changed, 269 insertions(+), 75 deletions(-) create mode 100644 WarmlyLocomotive/WarmlyLocomotive/Exceptions/CollectionOverflowException.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/Exceptions/ObjectNotFoundException.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/Exceptions/PositionOutOfCollectionException.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/serilog.json diff --git a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ListGenericObjects.cs index 0d6673d..8270f6f 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ListGenericObjects.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace WarmlyLocomotive.CollectionGenericObjects; +using WarmlyLocomotive.Exceptions; + +namespace WarmlyLocomotive.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -19,12 +21,13 @@ public class ListGenericObjects : ICollectionGenericObjects public int Count => _collection.Count; - public int MaxCount { - get + public int MaxCount + { + get { return _collection.Count; } - set + set { if (value > 0) { @@ -49,7 +52,7 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка позиции if (position >= Count || position < 0) { - return null; + throw new PositionOutOfCollectionException(position); } return _collection[position]; } @@ -59,7 +62,7 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка, что не превышено максимальное количество элементов if (Count == _maxCount) { - return -1; + throw new CollectionOverflowException(Count); } // TODO вставка в конец набора _collection.Add(obj); @@ -70,12 +73,12 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка, что не превышено максимальное количество элементов if (Count == _maxCount) { - return -1; + throw new CollectionOverflowException(Count); } // TODO проверка позиции if (position >= Count || position < 0) { - return -1; + throw new PositionOutOfCollectionException(position); } // TODO вставка по позиции _collection.Insert(position, obj); @@ -86,7 +89,7 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка позиции if (position >= Count || position < 0) { - return null; + throw new PositionOutOfCollectionException(position); } // TODO удаление объекта из списка T? obj = _collection[position]; diff --git a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs index 3bca1fe..30a909e 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace WarmlyLocomotive.CollectionGenericObjects; +using WarmlyLocomotive.Exceptions; + +namespace WarmlyLocomotive.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -49,8 +51,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { // TODO проверка позиции - if (position < 0 || position > _collection.Length) { - return null; + if (position < 0 || position > _collection.Length) + { + throw new PositionOutOfCollectionException(position); + } + if (position >= Count && _collection[position] == null) + { + throw new ObjectNotFoundException(position); } return _collection[position]; } @@ -58,14 +65,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Insert(T obj) { // TODO вставка в свободное место набора - for (int i=0; i < _collection.Length; i++) + for (int i = 0; i < _collection.Length; i++) { - if (_collection[i] == null) { + if (_collection[i] == null) + { _collection[i] = obj; return i; } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) @@ -73,7 +81,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects // TODO проверка позиции if (position > _collection.Length || position < 0) { - return -1; + throw new PositionOutOfCollectionException(position); } // TODO проверка, что элемент массива по этой позиции пустой, если нет, то // ищется свободное место после этой позиции и идет вставка туда @@ -102,19 +110,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { // TODO проверка позиции - if (position < 0 || position > _collection.Length) { - return null; + if (position < 0 || position > _collection.Length) + { + throw new PositionOutOfCollectionException(position); } if (_collection[position] == null) { - return null; + throw new ObjectNotFoundException(position); } T? tmp = _collection[position]; _collection[position] = null; diff --git a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/StorageCollection.cs b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/StorageCollection.cs index 90440ed..7b0d2da 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using System.Text; using WarmlyLocomotive.Drawnings; +using WarmlyLocomotive.Exceptions; namespace WarmlyLocomotive.CollectionGenericObjects; @@ -103,11 +104,11 @@ public class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -115,11 +116,9 @@ public class StorageCollection File.Delete(filename); } - //StringBuilder sb = new(); using FileStream fs = new(filename, FileMode.Create); using StreamWriter sw = new StreamWriter(fs); sw.WriteLine(_collectionKey); - //sb.Append(_collectionKey); foreach (KeyValuePair> value in _storages) { sw.Write(Environment.NewLine); @@ -148,7 +147,6 @@ public class StorageCollection sw.Write(_separatorItems); } } - return true; } /// @@ -156,25 +154,23 @@ public class StorageCollection /// /// Путь и имя файла /// 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 InvalidDataException("В файле нет данных"); } if (!line.Equals(_collectionKey)) { - return false; + throw new InvalidOperationException("В файле неверные данные"); } _storages.Clear(); while ((line = reader.ReadLine()) != null) @@ -189,7 +185,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new InvalidOperationException("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -199,9 +195,16 @@ public class StorageCollection { if (elem?.CreateDrawningLocomotive() is T locomotive) { - if (collection.Insert(locomotive) == -1) + try { - return false; + if (collection.Insert(locomotive) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new ArgumentOutOfRangeException("Коллекция переполнена", ex); } } @@ -209,7 +212,7 @@ public class StorageCollection _storages.Add(record[0], collection); } } - return true; + //return true; } /// diff --git a/WarmlyLocomotive/WarmlyLocomotive/Exceptions/CollectionOverflowException.cs b/WarmlyLocomotive/WarmlyLocomotive/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..ebb4426 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace WarmlyLocomotive.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/WarmlyLocomotive/WarmlyLocomotive/Exceptions/ObjectNotFoundException.cs b/WarmlyLocomotive/WarmlyLocomotive/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..586a5ff --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace WarmlyLocomotive.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/WarmlyLocomotive/WarmlyLocomotive/Exceptions/PositionOutOfCollectionException.cs b/WarmlyLocomotive/WarmlyLocomotive/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..c22cf69 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace WarmlyLocomotive.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/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.cs b/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.cs index 4574a58..cfe4d50 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.cs @@ -1,5 +1,7 @@ -using WarmlyLocomotive.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using WarmlyLocomotive.CollectionGenericObjects; using WarmlyLocomotive.Drawnings; +using WarmlyLocomotive.Exceptions; namespace WarmlyLocomotive; @@ -18,13 +20,20 @@ public partial class FormLocomotiveCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormLocomotiveCollection() + public FormLocomotiveCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// @@ -44,7 +53,7 @@ public partial class FormLocomotiveCollection : Form /// private void ButtonAddLocomotive_Click(object sender, EventArgs e) { - if(_company == null) + if (_company == null) { return; } @@ -64,14 +73,24 @@ public partial class FormLocomotiveCollection : Form { return; } - if (_company + locomotive >= 0) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + locomotive >= 0) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Объект добавлен: " + locomotive.GetDataForSave()); + } } - else + catch (CollectionOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (ObjectNotFoundException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -92,14 +111,24 @@ public partial class FormLocomotiveCollection : Form return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Объект удален, позиция: " + pos); + } } - else + catch (ObjectNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -113,11 +142,24 @@ public partial class FormLocomotiveCollection : Form int counter = 100; while (locomotive == null) { - locomotive = _company.GetRandomObject(); - counter--; - if (counter <= 0) + try { - break; + locomotive = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + catch (ObjectNotFoundException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } } if (locomotive == null) @@ -129,7 +171,6 @@ public partial class FormLocomotiveCollection : Form SetLocomotive = locomotive }; form.ShowDialog(); - } /// @@ -159,18 +200,26 @@ public partial class FormLocomotiveCollection : Form MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - CollectionType collectionType = CollectionType.None; - - if (radioButtonMassive.Checked) + try { - collectionType = CollectionType.Massive; + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция добавлена: " + textBoxCollectionName.Text); } - else if (radioButtonList.Checked) + catch (Exception ex) { - collectionType = CollectionType.List; + //MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); } /// @@ -188,14 +237,20 @@ public partial class FormLocomotiveCollection : Form { return; } - - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + try { - return; + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция удалена: " + listBoxCollection.SelectedItem.ToString()); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); } /// @@ -251,13 +306,17 @@ public partial class FormLocomotiveCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _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); } } } @@ -271,15 +330,17 @@ public partial class FormLocomotiveCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - 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/WarmlyLocomotive/WarmlyLocomotive/Program.cs b/WarmlyLocomotive/WarmlyLocomotive/Program.cs index 12147e2..8b2c808 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/Program.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; + namespace WarmlyLocomotive { internal static class Program @@ -11,7 +16,33 @@ namespace WarmlyLocomotive // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormLocomotiveCollection()); + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// + /// DI + /// + /// + 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 diff --git a/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj b/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj index 244387d..f3a2d5c 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj +++ b/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj @@ -8,6 +8,19 @@ enable + + + + + + + + + + + + + True @@ -23,4 +36,10 @@ + + + Always + + + \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/serilog.json b/WarmlyLocomotive/WarmlyLocomotive/serilog.json new file mode 100644 index 0000000..8476091 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/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": "Locomotive" + } + } +}