diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs index 866e50e..28e355c 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; namespace ProjectAirFighter.CollectionGenericObjects; @@ -101,8 +102,13 @@ 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) { }; + } return bitmap; diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/Hangar.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/Hangar.cs index 5cf9605..f9c1bf0 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/Hangar.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/Hangar.cs @@ -1,4 +1,5 @@ using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; namespace ProjectAirFighter.CollectionGenericObjects; @@ -43,8 +44,13 @@ public class Hangar : AbstractCompany { for (int x = ((valPlaceX - 1) * _placeSizeWidth) + 10; x >= 0; x -= _placeSizeWidth) { - _collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(counter)?.SetPosition(x, y); + try + { + _collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(counter)?.SetPosition(x, y); + } + catch (ObjectNotFoundException) { } + counter++; } } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs index fbd070d..0915ca5 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectAirFighter.Exceptions; + namespace ProjectAirFighter.CollectionGenericObjects; /// @@ -44,40 +46,44 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) + if (position < 0 && position > Count) { - return _collection[position]; + throw new PositionOutOfCollectionException(); } - else + if (_collection[position] == null) { - return null; + throw new ObjectNotFoundException(); } + return _collection[position]; } public int Insert(T obj) { - if (Count == _maxCount) { return -1; } + if (Count == _maxCount) { throw new CollectionOverflowException(); } _collection.Add(obj); + return Count; } public int Insert(T obj, int position) { - if (position < 0 || position >= Count || Count == _maxCount) - { - return -1; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); + if (Count == _maxCount) throw new CollectionOverflowException(); _collection.Insert(position, obj); + return position; } public T Remove(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); T obj = _collection[position]; _collection.RemoveAt(position); + + if (obj == null) throw new ObjectNotFoundException(); + return obj; } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index 9120cd0..23065e7 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectAirFighter.Exceptions; + namespace ProjectAirFighter.CollectionGenericObjects; /// @@ -50,12 +52,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) + if (position < 0 && position >= Count) { - return _collection[position]; + throw new PositionOutOfCollectionException(); } - return null; + if (_collection[position] == null) + { + throw new ObjectNotFoundException(); + } + + return _collection[position]; } @@ -68,8 +75,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects { if (position < 0 || position >= Count) { - return -1; + throw new PositionOutOfCollectionException(position); } + if (_collection[position] == null) { _collection[position] = obj; @@ -93,17 +101,26 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(_collection.Length); } public T Remove(int position) { if (position < 0 || position >= Count) { - return null; + throw new PositionOutOfCollectionException(); } + + if (_collection[position] == null) + { + throw new ObjectNotFoundException(); + } + T obj = _collection[position]; _collection[position] = null; + + if (obj == null) { throw new ObjectNotFoundException(); } + return obj; } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs index 3768850..e622292 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; using System.Text; namespace ProjectAirFighter.CollectionGenericObjects; @@ -94,13 +95,12 @@ public class StorageCollection /// /// Сохранение информации по кораблям в хранилище в файл /// - /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + /// Путь и имя файла sb.Clear(); } } - return true; } @@ -144,20 +143,18 @@ 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 sr = new StreamReader(filename)) { string? str; str = sr.ReadLine(); - if (str != _collectionKey.ToString()) - return false; + if (str != _collectionKey.ToString()) throw new FormatException("В файле неверные данные"); _storages.Clear(); while ((str = sr.ReadLine()) != null) { @@ -170,7 +167,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -180,14 +177,20 @@ public class StorageCollection { if (elem?.CreateDrawningPlane() is T ship) { - if (collection.Insert(ship) == -1) - return false; + try + { + if (collection.Insert(ship) == -1) throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } + } } _storages.Add(record[0], collection); } } - return true; } /// diff --git a/ProjectAirFighter/ProjectAirFighter/Exceptions/CollectionOverflowException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..c8f38f7 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/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/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotFoundException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..eba0aae --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/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/ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..13db41a --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,20 @@ +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/FormWarPlaneCollection.cs b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs index b221ff5..ab754ba 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs @@ -1,5 +1,7 @@ -using ProjectAirFighter.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; using System.Windows.Forms; namespace ProjectAirFighter; @@ -19,13 +21,19 @@ public partial class FormWarPlaneCollection : Form /// private AbstractCompany? _company; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormWarPlaneCollection() + public FormWarPlaneCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -49,14 +57,22 @@ public partial class FormWarPlaneCollection : Form return; } - if (_company + plane != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + plane != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (CollectionOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show("Ошибка переполнения коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -84,15 +100,30 @@ public partial class FormWarPlaneCollection : Form return; } - int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + int pos = Convert.ToInt32(maskedTextBox.Text); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удаление объекта по индексу {pos}", pos); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation("Не удалось удалить объект из коллекции по индексу {pos}", pos); + } } - else + catch (ObjectNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Ошибка: отсутствует объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show("Ошибка: неправильная позиция"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -157,6 +188,7 @@ public partial class FormWarPlaneCollection : Form if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); return; } @@ -171,6 +203,7 @@ public partial class FormWarPlaneCollection : Form } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text); RerfreshListBoxItems(); } @@ -191,6 +224,7 @@ public partial class FormWarPlaneCollection : Form return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); } @@ -251,13 +285,16 @@ public partial class FormWarPlaneCollection : 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); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -272,14 +309,17 @@ public partial class FormWarPlaneCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); RerfreshListBoxItems(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx index 3865651..ca20953 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx @@ -127,6 +127,6 @@ 261, 17 - 77 + 25 \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/Program.cs b/ProjectAirFighter/ProjectAirFighter/Program.cs index 9361ddf..0e45f32 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 @@ -10,8 +15,30 @@ namespace ProjectAirFighter { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. + ServiceCollection serviceCollection = new(); + ConfigureService(serviceCollection); ApplicationConfiguration.Initialize(); - Application.Run(new FormWarPlaneCollection()); + using ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + private static void ConfigureService(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "appSetting.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/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj b/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj index 244387d..274e502 100644 --- a/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj +++ b/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True @@ -23,4 +33,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/appSetting.json b/ProjectAirFighter/ProjectAirFighter/appSetting.json new file mode 100644 index 0000000..39bf043 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/appSetting.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": "ProjectAirFighter" + } + } +}