From ea4be415586b8421679e7bcd875644c507cb254e Mon Sep 17 00:00:00 2001 From: ikswi Date: Thu, 2 May 2024 09:16:58 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B2=D0=B0=D1=8F=20=D1=87?= =?UTF-8?q?=D0=B0=D1=81=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 17 ++- .../MassiveGenericObjects.cs | 22 +-- .../StorageCollection.cs | 32 ++-- .../Exceptions/CollectionOverflowException.cs | 20 +++ .../Exceptions/ObjectNotFoundException.cs | 20 +++ .../PositionOutOfCollectionException.cs | 20 +++ .../FormMilitaryAircraftCollection.cs | 140 ++++++++++++------ AirFighter/AirFighter/Program.cs | 25 +++- .../AirFighter/ProjectAirFighter.csproj | 11 ++ AirFighter/AirFighter/nlog.config | 15 ++ 10 files changed, 241 insertions(+), 81 deletions(-) create mode 100644 AirFighter/AirFighter/Exceptions/CollectionOverflowException.cs create mode 100644 AirFighter/AirFighter/Exceptions/ObjectNotFoundException.cs create mode 100644 AirFighter/AirFighter/Exceptions/PositionOutOfCollectionException.cs create mode 100644 AirFighter/AirFighter/nlog.config diff --git a/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs b/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs index c582091..9363960 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,7 @@ -namespace ProjectAirFighter.CollectionGenericObjects; +using ProjectAirFighter.Exceptions; +using ProjectSportCar.Exceptions; + +namespace ProjectAirFighter.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -43,28 +46,28 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); 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; + if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position); T? pos = _collection[position]; _collection.RemoveAt(position); return pos; diff --git a/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index ccda1cf..a912b1a 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,7 @@ -namespace ProjectAirFighter.CollectionGenericObjects; +using ProjectAirFighter.Exceptions; +using ProjectSportCar.Exceptions; + +namespace ProjectAirFighter.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -48,8 +51,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= _collection.Length || position < 0) - { return null; } + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } @@ -66,13 +69,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects index++; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - if (position >= _collection.Length || position < 0) - { return -1; } + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { @@ -98,15 +100,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects return position; } } - return -1; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - if (position >= _collection.Length || position < 0) - { - return null; - } + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); T obj = _collection[position]; _collection[position] = null; return obj; diff --git a/AirFighter/AirFighter/CollectionGenericObjects/StorageCollection.cs b/AirFighter/AirFighter/CollectionGenericObjects/StorageCollection.cs index a3c69d7..ae5a1d5 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; using System.Text; namespace ProjectAirFighter.CollectionGenericObjects; @@ -93,13 +94,11 @@ public class StorageCollection /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -139,10 +138,7 @@ public class StorageCollection } writer.Write(sb); } - } - - return true; } /// @@ -152,11 +148,11 @@ public class StorageCollection /// true - загрузка прошла успешно, false - ошибка при загрузке данных // - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) { @@ -164,12 +160,12 @@ public class StorageCollection if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); @@ -190,7 +186,7 @@ public class StorageCollection if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -201,15 +197,21 @@ public class StorageCollection { if (elem?.CreateDrawningMilitaryAircraft() is T militaryAircraft) { - if (collection.Insert(militaryAircraft) == -1) + try { - return false; + if (collection.Insert(militaryAircraft) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } - return true; } } diff --git a/AirFighter/AirFighter/Exceptions/CollectionOverflowException.cs b/AirFighter/AirFighter/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..c8f38f7 --- /dev/null +++ b/AirFighter/AirFighter/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +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/AirFighter/AirFighter/Exceptions/ObjectNotFoundException.cs b/AirFighter/AirFighter/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..eba0aae --- /dev/null +++ b/AirFighter/AirFighter/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,20 @@ +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/AirFighter/AirFighter/Exceptions/PositionOutOfCollectionException.cs b/AirFighter/AirFighter/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..ae01475 --- /dev/null +++ b/AirFighter/AirFighter/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectSportCar.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/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs b/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs index 760c7b2..462da0d 100644 --- a/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs +++ b/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs @@ -1,5 +1,8 @@ -using ProjectAirFighter.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; namespace ProjectAirFighter; @@ -15,13 +18,19 @@ public partial class FormMilitaryAircraftCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логгер + /// + private readonly ILogger _logger; /// /// Конструктор /// - public FormMilitaryAircraftCollection() + public FormMilitaryAircraftCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// @@ -53,19 +62,25 @@ public partial class FormMilitaryAircraftCollection : Form /// private void SetMilitaryAircraft(DrawningMilitaryAircraft? militaryAircraft) { - if (_company == null || militaryAircraft == null) - { - return; - } + try + { + if (_company == null || militaryAircraft == null) + { + return; + } - if (_company + militaryAircraft != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + militaryAircraft != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + militaryAircraft.GetDataForSave()); + } } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -88,14 +103,19 @@ public partial class FormMilitaryAircraftCollection : Form } 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); } } @@ -113,26 +133,28 @@ public partial class FormMilitaryAircraftCollection : Form DrawningMilitaryAircraft? militaryAircraft = null; int counter = 100; - while (militaryAircraft == null) + try { - militaryAircraft = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (militaryAircraft == null) { - break; + militaryAircraft = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + FormAirFighter Form = new() + { + SetAir = militaryAircraft + }; + Form.ShowDialog(); } + catch (Exception ex) - if (militaryAircraft == null) { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - - FormAirFighter form = new() - { - SetAir = militaryAircraft - }; - form.ShowDialog(); } /// @@ -158,33 +180,50 @@ public partial class FormMilitaryAircraftCollection : Form 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 buttonCollectionDel_Click(object sender, EventArgs e) { - if (listBoxCollection.SelectedItem == null) + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + + 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(); } private void RerfreshListBoxItems() @@ -236,13 +275,16 @@ public partial class FormMilitaryAircraftCollection : 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); } } } @@ -256,14 +298,18 @@ public partial class FormMilitaryAircraftCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - RerfreshListBoxItems(); + 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/AirFighter/AirFighter/Program.cs b/AirFighter/AirFighter/Program.cs index 9d818ea..66634a8 100644 --- a/AirFighter/AirFighter/Program.cs +++ b/AirFighter/AirFighter/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using NLog.Extensions.Logging; + namespace ProjectAirFighter { internal static class Program @@ -11,7 +16,25 @@ 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 FormMilitaryAircraftCollection()); + + 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 => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/AirFighter/AirFighter/ProjectAirFighter.csproj b/AirFighter/AirFighter/ProjectAirFighter.csproj index 244387d..279cb02 100644 --- a/AirFighter/AirFighter/ProjectAirFighter.csproj +++ b/AirFighter/AirFighter/ProjectAirFighter.csproj @@ -8,6 +8,11 @@ enable + + + + + True @@ -23,4 +28,10 @@ + + + Always + + + \ No newline at end of file diff --git a/AirFighter/AirFighter/nlog.config b/AirFighter/AirFighter/nlog.config new file mode 100644 index 0000000..5c71e85 --- /dev/null +++ b/AirFighter/AirFighter/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file