From 9ac1ae9ee2dd21ab89c3707c320f6733abcf8d67 Mon Sep 17 00:00:00 2001 From: H0llowVoid Date: Mon, 10 Jun 2024 09:45:45 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=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=20=E2=84=967?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CollectionGenericObjects/Garage.cs | 3 +- .../ListGenericObjects.cs | 35 +++----- .../MassiveGenericObjects.cs | 40 ++++----- .../StorageCollection.cs | 29 +++--- .../Exceptions/CollectionOverflowException.cs | 23 +++++ .../Exceptions/ObjectNotFoundException.cs | 19 ++++ .../PositionOutOfCollectionException.cs | 19 ++++ .../FormCraneCollection.cs | 89 +++++++++++++------ .../ProjectHoistingCrane/FormHoistingCrane.cs | 2 +- .../ProjectHoistingCrane/Program.cs | 24 ++++- .../ProjectHoistingCrane.csproj | 12 +++ .../ProjectHoistingCrane/nlog.config | 13 +++ .../ProjectHoistingCrane/serilogConfig.json | 21 +++++ 13 files changed, 244 insertions(+), 85 deletions(-) create mode 100644 ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectHoistingCrane/ProjectHoistingCrane/nlog.config create mode 100644 ProjectHoistingCrane/ProjectHoistingCrane/serilogConfig.json diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/Garage.cs b/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/Garage.cs index 9dd7184..c9262ea 100644 --- a/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/Garage.cs +++ b/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/Garage.cs @@ -37,11 +37,12 @@ public class Garage : AbstractCompany int startY = _placeSizeHeight * ((_pictureHeight / _placeSizeHeight)-1); for (int i = 0; i < (_pictureWidth / _placeSizeWidth) * (_pictureHeight /_placeSizeHeight); i++) { - if (_collection?.Get(i) != null) + try { _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i)?.SetPosition(startX+2, startY+2); } + catch { } startX -= _placeSizeWidth; if (startX < 0) { diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/ListGenericObjects.cs b/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/ListGenericObjects.cs index b7a565d..b188810 100644 --- a/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,7 @@ -namespace ProjectHoistingCrane.CollectionGenericObjects; +using ProjectHoistingCrane.Exceptions; + +namespace ProjectHoistingCrane.CollectionGenericObjects; + /// /// Параметризованный набор объектов @@ -48,41 +51,31 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { // TODO проверка позиции - if (position < Count && position >= 0) { return _collection[position]; } + if (position < 0 || position >= Count) throw new PositionOutOfRangeException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return null; } public int Insert(T obj) { - // TODO проверка, что не превышено максимальное количество элементов - if(Count + 1 > _maxCount) - { - return -1; - } - - // TODO вставка в конец набора + if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); - return _collection.Count-1; + return 1; } public int Insert(T obj, int position) { - // TODO проверка, что не превышено максимальное количество элементов + if (position < 0 || position > Count) + { + throw new PositionOutOfRangeException(position); + } if (Count + 1 > _maxCount) { - return -1; + throw new CollectionOverflowException(Count); } - - // TODO проверка позиции - if (position < 0 && position >= 0) - { - return -1; - } - - // TODO вставка по позиции _collection.Insert(position, obj); return 1; } @@ -91,7 +84,7 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка позиции if (position < 0 || position >= Count) { - return null; + throw new PositionOutOfRangeException(position); } // TODO удаление объекта из списка diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/MassiveGenericObjects.cs index d8a58f8..3055d82 100644 --- a/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/MassiveGenericObjects.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ProjectHoistingCrane.Exceptions; namespace ProjectHoistingCrane.CollectionGenericObjects; /// @@ -59,7 +60,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - return null; + throw new PositionOutOfRangeException(position); } public int Insert(T obj) @@ -74,7 +75,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) @@ -85,27 +86,23 @@ public class MassiveGenericObjects : ICollectionGenericObjects // если нет после, ищем до // TODO вставка - if (0 <= position && position < Count) + if (position > Count || position < 0) + { + throw new PositionOutOfRangeException(position); + } + if (_collection[position] == null) { - if (_collection[position] == null) { _collection[position] = obj; return position; - } - else { - for (int i = position+1; i < Count; i++) + } + else + { + for (int i = 0; i < Count; i++) + { + if (_collection[i] == null) { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } - } - for (int i = position-1;i >= 0;i--) { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } + _collection[i] = obj; + return i; } } } @@ -116,14 +113,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects { // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значени null - + if (_collection[position] == null) throw new ObjectNotFoundException(); if (0 <= position && position <= Count && _collection[position] != null) { T? obj = _collection[position]; _collection[position] = null; return obj; } - return null; + throw new PositionOutOfRangeException(position); + } public IEnumerable GetItems() diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/StorageCollection.cs b/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/StorageCollection.cs index 1842f53..0dd9738 100644 --- a/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectHoistingCrane/ProjectHoistingCrane/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using Microsoft.VisualBasic; using ProjectHoistingCrane.Drawnings; +using ProjectHoistingCrane.Exceptions; using System.Collections.ObjectModel; using System.Text; @@ -86,11 +87,11 @@ 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)) @@ -130,26 +131,25 @@ public class StorageCollection } writer.Close(); } - return true; } - 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(); @@ -165,7 +165,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]); } @@ -176,16 +176,23 @@ public class StorageCollection { if (elem?.CreateDrawningCrane() is T crane) { - if (collection.Insert(crane) < 0) + try { - return false; + if (collection.Insert(crane) < 0) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + + } + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } } - return true; } private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/CollectionOverflowException.cs b/ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..2c24a64 --- /dev/null +++ b/ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectHoistingCrane.Exceptions +{ + [Serializable] + internal class CollectionOverflowException : ApplicationException + { + public CollectionOverflowException(int count) : base("Превышено количество элементов коллекции: count" + count) { } + + public CollectionOverflowException() { } + + public CollectionOverflowException(string message) : base(message) { } + + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + + protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/ObjectNotFoundException.cs b/ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..c95ebda --- /dev/null +++ b/ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectHoistingCrane.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 context) : base(info, context) { } + } +} diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/PositionOutOfCollectionException.cs b/ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..1d00ffc --- /dev/null +++ b/ProjectHoistingCrane/ProjectHoistingCrane/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectHoistingCrane.Exceptions +{ + [Serializable] + internal class PositionOutOfRangeException : ApplicationException + { + public PositionOutOfRangeException(int i) : base("Не найден объект по позиции " + i) { } + public PositionOutOfRangeException() : base() { } + public PositionOutOfRangeException(string message) : base(message) { } + public PositionOutOfRangeException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/FormCraneCollection.cs b/ProjectHoistingCrane/ProjectHoistingCrane/FormCraneCollection.cs index b32113b..0345015 100644 --- a/ProjectHoistingCrane/ProjectHoistingCrane/FormCraneCollection.cs +++ b/ProjectHoistingCrane/ProjectHoistingCrane/FormCraneCollection.cs @@ -1,5 +1,8 @@ using ProjectHoistingCrane.CollectionGenericObjects; using ProjectHoistingCrane.Drawnings; +using ProjectHoistingCrane.Exceptions; +using Microsoft.Extensions.Logging; +using System.CodeDom; using System; using System.Collections.Generic; using System.ComponentModel; @@ -28,13 +31,14 @@ public partial class FormCraneCollection : Form /// private AbstractCompany? _company = null; - /// - /// Конструктор - /// - public FormCraneCollection() + + private readonly ILogger _logger; + + public FormCraneCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -76,14 +80,17 @@ public partial class FormCraneCollection : Form return; } - if (_company + crane > -1) + try { + int addingObj = _company + crane; MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект {crane.GetDataForSave()}"); pictureBox.Image = _company.Show(); } - else + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Не удалось добавить объект {ex.Message}"); } } @@ -104,16 +111,23 @@ public partial class FormCraneCollection : Form return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { + object delObj = _company - pos; MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект по позиции {pos}"); pictureBox.Image = _company.Show(); } - else + catch (ObjectNotFoundException ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект по позиции {pos}"); + } + catch (PositionOutOfRangeException) + { + MessageBox.Show("Удаление вне рамкок коллекции"); + _logger.LogWarning($"Не удалось удалить объект по позиции {pos} - вне коллекции"); } - } /// @@ -127,26 +141,30 @@ public partial class FormCraneCollection : Form { return; } - DrawningCrane? crane = null; - int counter = 100; - while (crane == null) + try { - crane = _company.GetRandomObject(); - counter--; - if (counter <= 0) + DrawningCrane? crane = null; + int counter = 100; + while (crane == null) { - break; + crane = _company.GetRandomObject(); + counter--; + if (counter <= 0) break; } + if (crane == null) + { + throw new ObjectNotFoundException(); + } + FormHoistingCrane form = new() + { + SetCrane = crane + }; + form.ShowDialog(); } - if (crane == null) + catch (ObjectNotFoundException) { - return; + _logger.LogWarning($"Не удалось найти объект для отправки на тест"); } - FormHoistingCrane form = new() - { - SetCar = crane - }; - form.ShowDialog(); } /// @@ -173,6 +191,7 @@ public partial class FormCraneCollection : Form if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Неверно введены данные для создания коллекции"); return; } CollectionType collectionType = CollectionType.None; @@ -185,6 +204,7 @@ public partial class FormCraneCollection : Form collectionType = CollectionType.List; } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation($"Добавлена коллекция - {textBoxCollectionName.Text}"); RerfreshListBoxItems(); } @@ -203,13 +223,16 @@ public partial class FormCraneCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Ошибка удаления коллекции - коллекция не выбрана"); return; } + string temp = listBoxCollection.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show("Вы действительно хотите удалить коллекцию?", "Да", MessageBoxButtons.YesNo) == DialogResult.No) { return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation($"Удалена коллекция - {temp}"); RerfreshListBoxItems(); } @@ -223,12 +246,14 @@ public partial class FormCraneCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Ошибка создания компании - она не выбрана"); return; } ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); + _logger.LogWarning("Ошибка инициализации коллекции"); return; } switch (comboBoxSelectorCompany.Text) @@ -262,13 +287,16 @@ public partial class FormCraneCollection : 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); } } @@ -278,14 +306,17 @@ public partial class FormCraneCollection : 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}", openFileDialog.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/ProjectHoistingCrane/ProjectHoistingCrane/FormHoistingCrane.cs b/ProjectHoistingCrane/ProjectHoistingCrane/FormHoistingCrane.cs index 9ae3633..df2d78f 100644 --- a/ProjectHoistingCrane/ProjectHoistingCrane/FormHoistingCrane.cs +++ b/ProjectHoistingCrane/ProjectHoistingCrane/FormHoistingCrane.cs @@ -20,7 +20,7 @@ public partial class FormHoistingCrane : Form /// /// /// - public DrawningCrane SetCar + public DrawningCrane SetCrane { set { diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/Program.cs b/ProjectHoistingCrane/ProjectHoistingCrane/Program.cs index 17a84d1..ed09f44 100644 --- a/ProjectHoistingCrane/ProjectHoistingCrane/Program.cs +++ b/ProjectHoistingCrane/ProjectHoistingCrane/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using System; namespace ProjectHoistingCrane { internal static class Program @@ -11,7 +16,24 @@ namespace ProjectHoistingCrane // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormCraneCollection()); + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + public static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile("serilogConfig.json") + .Build()) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/ProjectHoistingCrane.csproj b/ProjectHoistingCrane/ProjectHoistingCrane/ProjectHoistingCrane.csproj index af03d74..bc646f7 100644 --- a/ProjectHoistingCrane/ProjectHoistingCrane/ProjectHoistingCrane.csproj +++ b/ProjectHoistingCrane/ProjectHoistingCrane/ProjectHoistingCrane.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/nlog.config b/ProjectHoistingCrane/ProjectHoistingCrane/nlog.config new file mode 100644 index 0000000..54e4ba6 --- /dev/null +++ b/ProjectHoistingCrane/ProjectHoistingCrane/nlog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/ProjectHoistingCrane/ProjectHoistingCrane/serilogConfig.json b/ProjectHoistingCrane/ProjectHoistingCrane/serilogConfig.json new file mode 100644 index 0000000..410fcf4 --- /dev/null +++ b/ProjectHoistingCrane/ProjectHoistingCrane/serilogConfig.json @@ -0,0 +1,21 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "{Level:u4}: [{Timestamp:HH:mm:ss.fff}] - {Message:lj}{Exception}{NewLine}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "ProjectHoistingCrane" + } + } + +} \ No newline at end of file