diff --git a/11.txt b/11.txt deleted file mode 100644 index db43816..0000000 --- a/11.txt +++ /dev/null @@ -1,3 +0,0 @@ -CollectionsStorage -11|Massive|45|EntityMilitaryAircraft:100:100:Gray;EntityAirFighter:100:100:Gray:True:True:Gray;EntityAirFighter:100:100:Gray:True:True:Gray; -12|Massive|45|EntityAirFighter:100:100:BlueViolet:True:True:BlueViolet;EntityMilitaryAircraft:100:100:BlueViolet;EntityAirFighter:100:100:BlueViolet:True:True:BlueViolet; \ No newline at end of file diff --git a/12.txt b/12.txt deleted file mode 100644 index 80b13fc..0000000 --- a/12.txt +++ /dev/null @@ -1,3 +0,0 @@ -CollectionsStorage -11|Massive|45|EntityMilitaryAircraft:100:100:BlueViolet;EntityMilitaryAircraft:100:100:BlueViolet;EntityMilitaryAircraft:100:100:BlueViolet; -12|Massive|45|EntityMilitaryAircraft:100:100:Yellow;EntityMilitaryAircraft:100:100:Yellow;EntityMilitaryAircraft:100:100:Yellow; \ No newline at end of file diff --git a/AirFighter/AirFighter/CollectionGenericObjects/AbstractCompany.cs b/AirFighter/AirFighter/CollectionGenericObjects/AbstractCompany.cs index 1e6c381..5513f24 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/AbstractCompany.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; namespace ProjectAirFighter.CollectionGenericObjects; @@ -95,9 +96,18 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) - { + { + try + { DrawningMilitaryAircraft? obj = _collection?.Get(i); obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException e) + { } + catch (PositionOutOfCollectionException e) + { } + catch (CollectionOverflowException e) + { } } return bitmap; diff --git a/AirFighter/AirFighter/CollectionGenericObjects/Angar.cs b/AirFighter/AirFighter/CollectionGenericObjects/Angar.cs index bd921bb..029f7b5 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/Angar.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/Angar.cs @@ -1,4 +1,5 @@ using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; namespace ProjectAirFighter.CollectionGenericObjects; @@ -42,11 +43,13 @@ public class Angar : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (_collection.Get(i) != null) + try { _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10); } + catch (ObjectNotFoundException) { } + catch (PositionOutOfCollectionException e) { } if (curWidth > 0) curWidth--; @@ -55,7 +58,7 @@ public class Angar : AbstractCompany curWidth = width - 1; curHeight--; } - if (curHeight > height) + if (curHeight >= height) { return; } diff --git a/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs b/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs index 64884c3..0e8e5fa 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectAirFighter.CollectionGenericObjects; +using ProjectAirFighter.Exceptions; + +namespace ProjectAirFighter.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -46,36 +48,36 @@ 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; - T? pos = _collection[position]; + if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return pos; + return obj; } public IEnumerable GetItems() { - for (int i = 0; i < _collection.Count; ++i) + for (int i = 0; i < Count; ++i) { yield return _collection[i]; } diff --git a/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index ccda1cf..59818b3 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectAirFighter.CollectionGenericObjects; +using ProjectAirFighter.Exceptions; + +namespace ProjectAirFighter.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -48,65 +50,69 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= _collection.Length || position < 0) - { return null; } + if (position < 0 || position >= Count - 3) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj) { - int index = 0; - while (index < _collection.Length) + for (int i = 0; i < Count - 3; i++) { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[index] = obj; - return index; + _collection[i] = obj; + return i; } - - index++; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - if (position >= _collection.Length || position < 0) - { return -1; } + if (position < 0 || position >= Count - 3) throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) + if (_collection[position] != null) { - _collection[position] = obj; - return position; - } - int index; - - for (index = position + 1; index < _collection.Length; ++index) - { - if (_collection[index] == null) + bool pushed = false; + for (int index = position + 1; index < Count; index++) { - _collection[position] = obj; - return position; + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } + } + + if (!pushed) + { + for (int index = position - 1; index >= 0; index--) + { + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } + } + } + + if (!pushed) + { + throw new CollectionOverflowException(Count); } } - for (index = position - 1; index >= 0; --index) - { - if (_collection[index] == null) - { - _collection[position] = obj; - return position; - } - } - return -1; + // вставка + _collection[position] = obj; + return position; } public T? Remove(int position) { - if (position >= _collection.Length || position < 0) - { - return null; - } + if (position >= Count - 3 || 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 f457172..3ed993b 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; @@ -39,7 +40,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); //вот тут какое-то свойство + _storages = new Dictionary>(); } /// @@ -94,11 +95,11 @@ public class StorageCollection /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -141,10 +142,7 @@ public class StorageCollection } writer.Write(sb); } - } - - return true; } /// @@ -152,11 +150,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 (StreamReader fs = File.OpenText(filename)) { @@ -164,12 +162,12 @@ public class StorageCollection if (str == null || str.Length == 0) { - return false; + throw new FormatException("В файле неверные данные"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new FormatException("В файле неверные данные"); } _storages.Clear(); @@ -190,7 +188,7 @@ public class StorageCollection if (collection == null) { - return false; + throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -201,15 +199,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 InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", 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..45735a2 --- /dev/null +++ b/AirFighter/AirFighter/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectAirFighter.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +public 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..13db41a --- /dev/null +++ b/AirFighter/AirFighter/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/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs b/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs index a0dc7cd..92506fe 100644 --- a/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs +++ b/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs @@ -1,5 +1,7 @@ -using ProjectAirFighter.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings; +using ProjectAirFighter.Exceptions; namespace ProjectAirFighter; @@ -15,13 +17,20 @@ 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("Форма загрузилась"); } /// @@ -58,14 +67,18 @@ public partial class FormMilitaryAircraftCollection : Form return; } - if (_company + militaryAircraft != -1) + try { + var res = _company + militaryAircraft; MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); pictureBox.Image = _company.Show(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -88,14 +101,18 @@ public partial class FormMilitaryAircraftCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { + var res = _company - pos; MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален под индексом {pos}"); pictureBox.Image = _company.Show(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message, "Не удалось удалить объект", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -168,8 +185,17 @@ public partial class FormMilitaryAircraftCollection : Form collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); + try + { + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавление коллекции"); + RerfreshListBoxItems(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } } private void buttonCollectionDel_Click(object sender, EventArgs e) @@ -184,6 +210,7 @@ public partial class FormMilitaryAircraftCollection : Form return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } @@ -220,6 +247,7 @@ public partial class FormMilitaryAircraftCollection : Form { case "Хранилище": _company = new Angar(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Компания создана"); break; } @@ -231,13 +259,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); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -246,14 +277,17 @@ public partial class FormMilitaryAircraftCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _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); + 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..7ff1c04 100644 --- a/AirFighter/AirFighter/Program.cs +++ b/AirFighter/AirFighter/Program.cs @@ -1,17 +1,50 @@ -namespace ProjectAirFighter +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + +namespace ProjectAirFighter; + +internal static class Program { - internal static class Program + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + + var services = new ServiceCollection(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService ()); + + } + + /// + /// DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLogging(option => { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - Application.Run(new FormMilitaryAircraftCollection()); - } + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: $"{pathNeed}serilogConfig.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/AirFighter/AirFighter/ProjectAirFighter.csproj b/AirFighter/AirFighter/ProjectAirFighter.csproj index 244387d..9067329 100644 --- a/AirFighter/AirFighter/ProjectAirFighter.csproj +++ b/AirFighter/AirFighter/ProjectAirFighter.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True diff --git a/AirFighter/AirFighter/serilogConfig.json b/AirFighter/AirFighter/serilogConfig.json new file mode 100644 index 0000000..4ca9b41 --- /dev/null +++ b/AirFighter/AirFighter/serilogConfig.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": "AirFighter" + } + } +}