From bd3d6be6783306fa38f0ec374987c5e8a67dc83e Mon Sep 17 00:00:00 2001 From: VirBiuM Date: Mon, 20 May 2024 14:45:17 +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 --- ProjectAirFighter/.editorconfig | 4 + .../ListGenericObjects.cs | 16 +- .../MassiveGenericObjects.cs | 49 ++++--- .../StorageCollection.cs | 22 ++- .../Exceptions/CollectionOverflowException.cs | 16 ++ .../Exceptions/ObjectNotFoundException.cs | 16 ++ .../PositionOutOfCollectionException.cs | 16 ++ .../ProjectAirFighter/FormPlaneCollection.cs | 138 ++++++++++++------ .../ProjectAirFighter/Program.cs | 31 +++- .../ProjectAirFighter.csproj | 18 +++ .../ProjectAirFighter/serilog.json | 18 +++ ProjectAirFighter/log.txt | 10 ++ 12 files changed, 274 insertions(+), 80 deletions(-) create mode 100644 ProjectAirFighter/.editorconfig create mode 100644 ProjectAirFighter/ProjectAirFighter/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/serilog.json create mode 100644 ProjectAirFighter/log.txt diff --git a/ProjectAirFighter/.editorconfig b/ProjectAirFighter/.editorconfig new file mode 100644 index 0000000..388df96 --- /dev/null +++ b/ProjectAirFighter/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# CS8622: Допустимость значений NULL для ссылочных типов в типе параметра не соответствует целевому объекту делегирования (возможно, из-за атрибутов допустимости значений NULL). +dotnet_diagnostic.CS8622.severity = none diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs index 5b9f0e5..4cff67e 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectAirFighter.Exceptions; + namespace ProjectAirFighter.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects @@ -40,29 +42,29 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { // TODO проверка позиции - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { // TODO проверка, что не превышено максимальное количество элементов и вставка в конец набора - if (Count == _maxCount) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - // TODO проверка, что не превышено максимальное количество элементов - if (Count == _maxCount) return -1; - // TODO проверка позиции и вставка по позиции - if (position >= Count || position < 0) return -1; + // TODO выброс ошибки если переполнение + if (Count == _maxCount) throw new CollectionOverflowException(Count); + // TODO выброс ошибки если за границу + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); return position; } public T Remove(int position) { // TODO проверка позиции - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); // TODO удаление объекта из списка T obj = _collection[position]; _collection.RemoveAt(position); diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index f3a753a..ab6fcc6 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectAirFighter.Exceptions; + namespace ProjectAirFighter.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects @@ -45,8 +47,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - // TODO проверка позиции - if (position >= Count || position < 0) return null; + // TODO выброс ошибки если выход за границу + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + // TODO выброс ошибки если объект пустой return _collection[position]; } @@ -61,38 +64,44 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - // TODO проверка позиции - for (int i = position; i < Count; i++) + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } + _collection[position] = obj; + return position; } - // TODO проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до - for (int i = position - 1; i >= 0; i--) + int index = position + 1; + while (index < _collection.Length) { - if (_collection[i] == null) + if (_collection[index] == null) { - _collection[i] = obj; - return i; + _collection[index] = obj; + return index; } + ++index; } - return -1; + index = position - 1; + while (index >= 0) + { + if (_collection[index] == null) + { + _collection[index] = obj; + return index; + } + --index; + } + throw new CollectionOverflowException(Count); } public T Remove(int position) { // TODO проверка позиции - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); // TODO удаление объекта из массива, присвоив элементу массива значение null if (_collection[position] != null) { @@ -100,7 +109,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return obj; } - return null; + throw new ObjectNotFoundException(position); } public IEnumerable GetItems() diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs index c31cad0..cead2e1 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; namespace ProjectAirFighter.CollectionGenericObjects; @@ -87,7 +88,7 @@ public class StorageCollection { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -134,18 +135,18 @@ public class StorageCollection { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); string strs = ""; @@ -160,7 +161,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -168,9 +169,16 @@ public class StorageCollection { if (elem?.CreateDrawningWarPlane() is T plane) { - if (collection.Insert(plane) == -1) + try { - return false; + if (collection.Insert(plane) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } diff --git a/ProjectAirFighter/ProjectAirFighter/Exceptions/CollectionOverflowException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..f6d6d0f --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectAirFighter.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/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotFoundException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..64f50f5 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectAirFighter.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/ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..3a36bfb --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectAirFighter.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/ProjectAirFighter/ProjectAirFighter/FormPlaneCollection.cs b/ProjectAirFighter/ProjectAirFighter/FormPlaneCollection.cs index 95bb750..e5207bc 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormPlaneCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormPlaneCollection.cs @@ -1,5 +1,7 @@ -using ProjectAirFighter.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; namespace ProjectAirFighter; @@ -17,12 +19,18 @@ public partial class FormPlaneCollection : Form /// private readonly StorageCollection _storageCollection; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormPlaneCollection() + public FormPlaneCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// /// Выбор комапнии @@ -47,18 +55,24 @@ public partial class FormPlaneCollection : Form } private void SetPlane(DrawningWarPlane? plane) { - if (_company == null || plane == null) + try { - return; + if (_company == null || plane == null) + { + return; + } + if (_company + plane != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + plane.GetDataForSave()); + } } - if (_company + plane != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } private void ButtonRemovePlane_Click(object sender, EventArgs e) @@ -66,14 +80,19 @@ public partial class FormPlaneCollection : Form if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) return; if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) 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 (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -82,16 +101,27 @@ public partial class FormPlaneCollection : Form if (_company == null) return; DrawningWarPlane? plane = null; int counter = 100; - while (plane == null) + try { - plane = _company.GetRandomObjects(); - counter--; - if (counter <= 0) break; + while (plane == null) + { + plane = _company.GetRandomObjects(); + counter--; + if (counter <= 0) + { + break; + } + } + FormAirFighter form = new() + { + SetPlane = plane + }; + form.ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - if (plane == null) return; - FormAirFighter form = new FormAirFighter(); - form.SetPlane = plane; - form.ShowDialog(); } private void ButtonRefresh_Click(object sender, EventArgs e) @@ -113,17 +143,25 @@ public partial class FormPlaneCollection : Form 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; + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); } private void RerfreshListBoxItems() { @@ -150,12 +188,20 @@ public partial class FormPlaneCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + try { - return; + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + 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(); } /// @@ -196,15 +242,16 @@ public partial class FormPlaneCollection : 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); } } } @@ -218,16 +265,17 @@ public partial class FormPlaneCollection : Form { 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); RerfreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectAirFighter/ProjectAirFighter/Program.cs b/ProjectAirFighter/ProjectAirFighter/Program.cs index edac9cc..a1c8489 100644 --- a/ProjectAirFighter/ProjectAirFighter/Program.cs +++ b/ProjectAirFighter/ProjectAirFighter/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectAirFighter { internal static class Program @@ -11,7 +16,31 @@ namespace ProjectAirFighter // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormPlaneCollection()); + + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + + } + private static void ConfigureServices(ServiceCollection services) + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile("P:\\VS 2019\\\\OOP\\Simple\\ProjectAirFighter\\ProjectAirFighter\\serilog.json") + .Build()) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj b/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj index 244387d..56067ce 100644 --- a/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj +++ b/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True @@ -23,4 +35,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/serilog.json b/ProjectAirFighter/ProjectAirFighter/serilog.json new file mode 100644 index 0000000..7a7bfdf --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/serilog.json @@ -0,0 +1,18 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "P:\\VS 2019\\проекты\\OOP\\Simple\\ProjectAirFighter\\log.txt", + "outputTemplate": "[{Level:u}] [{Timestamp:yyyy-MM-dd HH:mm:ss.ffff}] {Message:1j}{NewLine}{Exception}" + } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file diff --git a/ProjectAirFighter/log.txt b/ProjectAirFighter/log.txt new file mode 100644 index 0000000..678d9ce --- /dev/null +++ b/ProjectAirFighter/log.txt @@ -0,0 +1,10 @@ +[INFORMATION] [2024-05-20 14:35:47.1937] Форма загрузилась +[INFORMATION] [2024-05-20 14:35:52.6152] Загрузка из файла: "C:\\Users\\VirBiuM\\Documents\\12.txt" +[ERROR] [2024-05-20 14:36:00.0553] Ошибка: "В коллекции превышено допустимое количество: 15" +[INFORMATION] [2024-05-20 14:37:16.5561] Удален объект по позиции 1 +[ERROR] [2024-05-20 14:37:18.9106] Ошибка: "Не найден объект по позиции 1" +[INFORMATION] [2024-05-20 14:38:06.1646] Форма загрузилась +[INFORMATION] [2024-05-20 14:38:17.6854] Загрузка из файла: "C:\\Users\\VirBiuM\\Documents\\12.txt" +[ERROR] [2024-05-20 14:39:08.8637] Ошибка: "В коллекции превышено допустимое количество: 15" +[INFORMATION] [2024-05-20 14:39:16.4465] Удален объект по позиции 2 +[ERROR] [2024-05-20 14:39:20.0041] Ошибка: "Не найден объект по позиции 2"