From 96cd694efde0e0c09eeb494b200c2cbc81c960e0 Mon Sep 17 00:00:00 2001 From: zum Date: Tue, 30 Apr 2024 18:38:51 +0400 Subject: [PATCH] lab7 --- .../AbstractCompany.cs | 18 +++- .../CollectionGenericObjects/Hangar.cs | 11 ++- .../ListGenericObjects.cs | 24 +++-- .../MassiveGenericObjects.cs | 21 +++-- .../StorageCollection.cs | 42 +++++---- .../Exceptions/CollectionOverflowException.cs | 20 +++++ .../Exceptions/ObjectNotFoundException.cs | 20 +++++ .../PositionOutOfCollectionException.cs | 20 +++++ .../FormWarPlaneCollection.cs | 88 ++++++++++++++----- .../ProjectStormTrooper/Program.cs | 37 +++++++- .../ProjectStormTrooper.csproj | 18 ++++ .../ProjectStormTrooper/appsettings.json | 20 +++++ 12 files changed, 279 insertions(+), 60 deletions(-) create mode 100644 ProjectStormTrooper/ProjectStormTrooper/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectStormTrooper/ProjectStormTrooper/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectStormTrooper/ProjectStormTrooper/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectStormTrooper/ProjectStormTrooper/appsettings.json diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/AbstractCompany.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/AbstractCompany.cs index 3642e0f..5469fca 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectStormTrooper.Drawnings; +using ProjectStormTrooper.Exceptions; namespace ProjectStormTrooper.CollectionGenericObjects; @@ -8,6 +9,9 @@ namespace ProjectStormTrooper.CollectionGenericObjects; /// public abstract class AbstractCompany { + // Размер пробела + protected readonly int ColsSpace = 30; + /// /// Размер места (ширина) /// @@ -36,7 +40,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (int)Math.Floor((double)(_pictureWidth * _pictureHeight / ((_placeSizeWidth+ColsSpace) * _placeSizeHeight ))*1.1); /// /// Конструктор @@ -102,8 +106,16 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningWarPlane? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningWarPlane obj = _collection.Get(i); + obj.DrawTransport(graphics); + } + catch (ObjectNotFoundException) + { + continue; + } + } return bitmap; diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/Hangar.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/Hangar.cs index b6b9cbe..cb2b929 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/Hangar.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/Hangar.cs @@ -1,4 +1,5 @@ using ProjectStormTrooper.Drawnings; +using ProjectStormTrooper.Exceptions; namespace ProjectStormTrooper.CollectionGenericObjects; @@ -8,6 +9,7 @@ namespace ProjectStormTrooper.CollectionGenericObjects; /// public class Hangar : AbstractCompany { + /// /// Конструктор /// @@ -28,7 +30,7 @@ public class Hangar : AbstractCompany g.DrawLine(pen, posX, posY, posX, posY + _placeSizeHeight*(_pictureHeight/ _placeSizeHeight)); for(int j = 0; j <= _pictureHeight/_placeSizeHeight; j++) { - g.DrawLine(pen, posX, posY, posX + _placeSizeWidth-30, posY); + g.DrawLine(pen, posX, posY, posX + _placeSizeWidth-ColsSpace, posY); posY += _placeSizeHeight; } posX += _placeSizeWidth; @@ -41,11 +43,16 @@ public class Hangar : AbstractCompany int posY = 0; for (int i = 0; i < _collection?.Count; i++) { - if(_collection.Get(i) != null) + + try { _collection?.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i).SetPosition(posX * _placeSizeWidth, posY * _placeSizeHeight); } + catch (ObjectNotFoundException) + { + break; + } if(posX > 0) { posX--; diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs index dda0195..5720473 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -using ProjectStormTrooper.CollectionGenericObjects; +using NLog.LayoutRenderers; +using ProjectStormTrooper.CollectionGenericObjects; +using ProjectStormTrooper.Exceptions; /// /// Параметризованный набор объектов @@ -44,14 +46,21 @@ public class ListGenericObjects : ICollectionGenericObjects { if(position > _collection.Count || position < 0) { - return null; + throw new PositionOutOfCollectionException(); + } + if (_collection[position] == null) + { + throw new ObjectNotFoundException(); } return _collection[position]; } public bool Insert(T obj) { - if(_collection.Count+1 > _maxCount) { return false;} + if (Count + 1 > MaxCount) + { + throw new CollectionOverflowException(); + } _collection.Add(obj); return true; @@ -59,10 +68,13 @@ public class ListGenericObjects : ICollectionGenericObjects public bool Insert(T obj, int position) { - if (_collection.Count + 1 < _maxCount) { return false; } + if (_collection.Count + 1 < _maxCount) + { + throw new CollectionOverflowException(); + } if (position > _collection.Count || position < 0) { - return false; + throw new PositionOutOfCollectionException(); } _collection.Insert(position, obj); return true; @@ -72,7 +84,7 @@ public class ListGenericObjects : ICollectionGenericObjects { if (position > _collection.Count || position < 0) { - return null; + throw new PositionOutOfCollectionException(); } T temp = _collection[position]; _collection.RemoveAt(position); diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs index 4d41847..88ea6af 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,5 +1,5 @@  - +using ProjectStormTrooper.Exceptions; namespace ProjectStormTrooper.CollectionGenericObjects; /// @@ -53,21 +53,26 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (position<0 || position > _collection.Length - 1) { - return null; + throw new PositionOutOfCollectionException(); + } + if(_collection[position] == null) + { + throw new ObjectNotFoundException(); } return _collection[position]; } public bool Insert(T obj) { - + int index = Array.IndexOf(_collection, null); if(index >= 0) { _collection[index] = obj; return true; } - return false; + throw new CollectionOverflowException(); + } public bool Insert(T obj, int position) @@ -75,7 +80,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects if(position < 0 || position > _collection.Length -1) { - return false; + throw new PositionOutOfCollectionException(); } for(int i = position; i < _collection.Length; i++) { @@ -101,7 +106,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (position < 0 || position > _collection.Length - 1) { - return null; + throw new PositionOutOfCollectionException(); + } + if (_collection[position] == null) + { + throw new ObjectNotFoundException(); } T temp = _collection[position]; _collection[position] = null; diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs index 69f9051..df03328 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using ProjectStormTrooper.CollectionGenericObjects; using ProjectStormTrooper.Drawnings; +using ProjectStormTrooper.Exceptions; using System.Text; /// @@ -93,11 +94,12 @@ public class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); + } if (File.Exists(filename)) @@ -137,7 +139,6 @@ public class StorageCollection streamWriter.Write(_separatorItems); } } - return true; } /// @@ -145,11 +146,11 @@ 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 (FileStream fs = new(filename, FileMode.Open)) @@ -158,14 +159,14 @@ public class StorageCollection string firstString = streamReader.ReadLine(); if(firstString == null || firstString.Length == 0) { - return false; + throw new ArgumentException("В файле нет данных"); } if (!firstString.Equals(_collectionKey)) { //если нет такой записи, то это не те данные - return false; + throw new InvalidDataException("В файле неверные данные"); } - + _storages.Clear(); while (!streamReader.EndOfStream) { @@ -175,11 +176,9 @@ public class StorageCollection { continue; } - 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]); @@ -188,10 +187,17 @@ public class StorageCollection { if (elem?.CreateDrawningWarPlane() is T warPlane) { - if (!collection.Insert(warPlane)) - { - return false; - } + try + { + if (!collection.Insert(warPlane)) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } } } @@ -199,8 +205,6 @@ public class StorageCollection } } - - return true; } /// diff --git a/ProjectStormTrooper/ProjectStormTrooper/Exceptions/CollectionOverflowException.cs b/ProjectStormTrooper/ProjectStormTrooper/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..27b1245 --- /dev/null +++ b/ProjectStormTrooper/ProjectStormTrooper/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectStormTrooper.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) { } +} \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/Exceptions/ObjectNotFoundException.cs b/ProjectStormTrooper/ProjectStormTrooper/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..5d5abba --- /dev/null +++ b/ProjectStormTrooper/ProjectStormTrooper/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectStormTrooper.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) { } +} \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/Exceptions/PositionOutOfCollectionException.cs b/ProjectStormTrooper/ProjectStormTrooper/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..e171f02 --- /dev/null +++ b/ProjectStormTrooper/ProjectStormTrooper/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectStormTrooper.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) { } +} \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs index cd2a3aa..794b89a 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs @@ -1,6 +1,8 @@ using ProjectStormTrooper.CollectionGenericObjects; using ProjectStormTrooper.Drawnings; - +using Microsoft.Extensions.Logging; +using ProjectStormTrooper.Exceptions; +using System.Xml.Linq; namespace ProjectStormTrooper { @@ -8,11 +10,15 @@ namespace ProjectStormTrooper { private AbstractCompany? _company = null; private readonly StorageCollection _storageCollection; - public FormWarPlaneCollection() + /// + /// Логер + /// + private readonly ILogger _logger; + public FormWarPlaneCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); - + _logger = logger; } /// /// Выбор компании @@ -45,16 +51,20 @@ namespace ProjectStormTrooper { return; } - - if (_company + warPlane == 1) + try { + int addingObject = (_company + warPlane); MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект {warPlane.GetDataForSave()}"); pictureBox.Image = _company.Show(); } - else + catch(CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); + } + } /// @@ -82,6 +92,7 @@ namespace ProjectStormTrooper { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { + _logger.LogWarning("Удаление объекта из несуществующей коллекции"); return; } @@ -91,14 +102,24 @@ namespace ProjectStormTrooper } 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} "); } } /// @@ -117,12 +138,19 @@ namespace ProjectStormTrooper int counter = 100; while (warPlane == null) { - warPlane = _company.GetRandomObject(); - counter--; - if (counter <= 0) + try { - break; + warPlane = _company.GetRandomObject(); } + catch (ObjectNotFoundException) + { + counter--; + if (counter <= 0) + { + break; + } + } + } if (warPlane == null) @@ -161,6 +189,7 @@ namespace ProjectStormTrooper if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не заполненная коллекция"); return; } @@ -175,6 +204,7 @@ namespace ProjectStormTrooper } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}"); RerfreshListBoxItems(); } @@ -188,13 +218,17 @@ namespace ProjectStormTrooper if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Удаление невыбранной коллекции"); return; } + string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation($"Удалена коллекция: {name}"); RerfreshListBoxItems(); } @@ -225,6 +259,7 @@ namespace ProjectStormTrooper if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Создание компании невыбранной коллекции"); return; } @@ -232,6 +267,7 @@ namespace ProjectStormTrooper if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); + _logger.LogWarning("Не удалось инициализировать коллекцию"); return; } @@ -251,13 +287,16 @@ namespace ProjectStormTrooper { 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); } } } @@ -266,15 +305,22 @@ namespace ProjectStormTrooper { if(openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Реузльтат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storageCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName); RerfreshListBoxItems(); } - else - { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + catch(Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } + + + + } } } diff --git a/ProjectStormTrooper/ProjectStormTrooper/Program.cs b/ProjectStormTrooper/ProjectStormTrooper/Program.cs index 97ac81a..da6d972 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/Program.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; +using Serilog; namespace ProjectStormTrooper { internal static class Program @@ -12,7 +16,34 @@ namespace ProjectStormTrooper { ApplicationConfiguration.Initialize(); - Application.Run(new FormWarPlaneCollection()); - } - } + 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: "appsettings.json", optional: false, reloadOnChange: true) + .Build(); + + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + + }); + } + } } diff --git a/ProjectStormTrooper/ProjectStormTrooper/ProjectStormTrooper.csproj b/ProjectStormTrooper/ProjectStormTrooper/ProjectStormTrooper.csproj index 244387d..b5438ea 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/ProjectStormTrooper.csproj +++ b/ProjectStormTrooper/ProjectStormTrooper/ProjectStormTrooper.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True @@ -23,4 +35,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/appsettings.json b/ProjectStormTrooper/ProjectStormTrooper/appsettings.json new file mode 100644 index 0000000..26e96ff --- /dev/null +++ b/ProjectStormTrooper/ProjectStormTrooper/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": "StormTrooper" + } + } +}