diff --git a/AntiAircraftGun/AntiAircraftGun.csproj b/AntiAircraftGun/AntiAircraftGun.csproj index 13ee123..001d3e0 100644 --- a/AntiAircraftGun/AntiAircraftGun.csproj +++ b/AntiAircraftGun/AntiAircraftGun.csproj @@ -8,6 +8,11 @@ enable + + + + + True @@ -23,4 +28,10 @@ + + + Always + + + \ No newline at end of file diff --git a/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs index 3c2a312..c4356cd 100644 --- a/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ using AntiAircraftGun.CollectionGenereticObject; +using AntiAircraftGun.Exceptions; namespace AntiAircraftGun.CollectionGenericObjects; /// @@ -47,28 +48,29 @@ public class ListGenericObjects : ICollectionGenericObjects public T Get(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + if (_collection[position] == 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 (Count == _maxCount) return -1; - if (position >= Count || position < 0) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); _collection.Insert(position, obj); return position; } public T Remove(int position) { - if (position >= _collection.Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); T obj = _collection[position]; _collection.RemoveAt(position); return obj; diff --git a/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs index 21c30d8..25f6692 100644 --- a/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,5 +1,6 @@ using AntiAircraftGun.CollectionGenericObjects; using AntiAircraftGun.Drawnings; +using AntiAircraftGun.Exceptions; namespace AntiAircraftGun.CollectionGenereticObject; @@ -51,17 +52,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - - return null; + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); + return _collection[position]; + } public int Insert(T obj) { - // вставка в свободное место набора + for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -71,70 +69,48 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(); } public int Insert(T obj, int position) { - // проверка позиции - if (position < 0 || position >= Count) + + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + if (_collection[position] == null) { - return -1; + _collection[position] = obj; + return position; } - - // проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до - if (_collection[position] != null) + int temp = position + 1; + while (temp < Count) { - bool pushed = false; - for (int index = position + 1; index < Count; index++) + if (_collection[temp] == null) { - 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) - { - return position; + _collection[temp] = obj; + return temp; } + ++temp; } - - // вставка - _collection[position] = obj; - return position; + temp = position - 1; + while (temp >= 0) + { + if (_collection[temp] == null) + { + _collection[temp] = obj; + return temp; + } + --temp; + } + throw new CollectionOverflowException(); } public T? Remove(int position) { - // проверка позиции - if (position < 0 || position >= Count) - { - return null; - } - - if (_collection[position] == null) return null; - - T? temp = _collection[position]; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + T? myObject = _collection[position]; + if (myObject == null) throw new ObjectNotFoundException(); _collection[position] = null; - return temp; + return myObject; } public IEnumerable GetItems() diff --git a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs index 2dba4ab..aea8ab5 100644 --- a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs +++ b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using AntiAircraftGun.CollectionGenereticObject; using AntiAircraftGun.Drawnings; +using AntiAircraftGun.Exceptions; using System.Text; namespace AntiAircraftGun.CollectionGenericObjects; @@ -87,12 +88,11 @@ public class StorageCollection /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла - /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -108,7 +108,6 @@ public class StorageCollection foreach (KeyValuePair> value in _storages) { writer.Write(Environment.NewLine); - // не сохраняем пустые коллекции if (value.Value.Count == 0) { continue; @@ -134,31 +133,28 @@ public class StorageCollection } } } - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException($"{filename} не существует"); } using (StreamReader reader = new(filename)) { string line = reader.ReadLine(); if (line == null || line.Length == 0) { - return false; + throw new Exception("Файл не подходит"); } if (!line.Equals(_collectionKey)) { - //если нет такой записи, то это не те данные - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); while ((line = reader.ReadLine()) != null) @@ -173,7 +169,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, @@ -182,16 +178,22 @@ public class StorageCollection { if (elem?.CreateDrawningArmoredCar() is T truck) { - if (collection.Insert(truck) == -1) + try { - return false; + if (collection.Insert(truck) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: "); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } } - return true; } /// diff --git a/AntiAircraftGun/Exceptions/CollectionOverflowException.cs b/AntiAircraftGun/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..c35f717 --- /dev/null +++ b/AntiAircraftGun/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Exceptions; +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +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) { } +} diff --git a/AntiAircraftGun/Exceptions/ObjectNotFoundException.cs b/AntiAircraftGun/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..e34301d --- /dev/null +++ b/AntiAircraftGun/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Exceptions; +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +public 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) { } +} diff --git a/AntiAircraftGun/Exceptions/PositionOutOfCollectionException.cs b/AntiAircraftGun/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..d9a60ff --- /dev/null +++ b/AntiAircraftGun/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Exceptions; +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[Serializable] +public class PositionOutOfCollectionException +{ + 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) { } +} diff --git a/AntiAircraftGun/FormArmoredCarCollection.cs b/AntiAircraftGun/FormArmoredCarCollection.cs index d1517bd..e934844 100644 --- a/AntiAircraftGun/FormArmoredCarCollection.cs +++ b/AntiAircraftGun/FormArmoredCarCollection.cs @@ -2,7 +2,7 @@ using AntiAircraftGun.CollectionGenereticObjects; using AntiAircraftGun.CollectionGenericObjects; using AntiAircraftGun.Drawnings; - +using Microsoft.Extensions.Logging; namespace AntiAircraftGun; /// @@ -18,14 +18,19 @@ public partial class FormArmoredCarCollection : Form /// Компания /// private AbstractCompany? _company = null; + /// + /// Логгер + /// + private readonly ILogger _logger; /// /// Конструктор /// - public FormArmoredCarCollection() + public FormArmoredCarCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -251,13 +256,16 @@ public partial class FormArmoredCarCollection : 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); } } } @@ -270,14 +278,20 @@ public partial class FormArmoredCarCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + foreach (var collection in _storageCollection.Keys) + { + listBoxCollection.Items.Add(collection); + } RerfreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } diff --git a/AntiAircraftGun/Program.cs b/AntiAircraftGun/Program.cs index 09b34fb..b1afc1d 100644 --- a/AntiAircraftGun/Program.cs +++ b/AntiAircraftGun/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + namespace AntiAircraftGun { internal static class Program @@ -11,7 +15,29 @@ namespace AntiAircraftGun // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormArmoredCarCollection()); + ServiceCollection services = new(); + ConfigureService(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + /// + /// DI + /// + /// + private static void ConfigureService(ServiceCollection services) + { + services + .AddSingleton() + .AddLogging(option => { + option.SetMinimumLevel(LogLevel.Information); + //option.AddSerilog(new LoggerConfiguration() + // //.WriteTo + + // .CreateLogger()); + option.AddNLog("serilog.config"); + }); + + } } } \ No newline at end of file diff --git a/AntiAircraftGun/serilog.config b/AntiAircraftGun/serilog.config new file mode 100644 index 0000000..54e4ba6 --- /dev/null +++ b/AntiAircraftGun/serilog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file