diff --git a/AntiAircraftGun/AntiAircraftGun.csproj b/AntiAircraftGun/AntiAircraftGun.csproj index 13ee123..101791e 100644 --- a/AntiAircraftGun/AntiAircraftGun.csproj +++ b/AntiAircraftGun/AntiAircraftGun.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True @@ -23,4 +34,10 @@ + + + Always + + + \ No newline at end of file diff --git a/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs b/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs index af9fd2a..702b156 100644 --- a/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs +++ b/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs @@ -98,8 +98,12 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningArmoredCar? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningArmoredCar? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (Exception) { } } return bitmap; diff --git a/AntiAircraftGun/CollectionGenericObjects/CarBase.cs b/AntiAircraftGun/CollectionGenericObjects/CarBase.cs index 4fe96ec..74abdcd 100644 --- a/AntiAircraftGun/CollectionGenericObjects/CarBase.cs +++ b/AntiAircraftGun/CollectionGenericObjects/CarBase.cs @@ -1,6 +1,6 @@ using AntiAircraftGun.CollectionGenereticObject; using AntiAircraftGun.Drawnings; - +using AntiAircraftGun.Exceptions; namespace AntiAircraftGun.CollectionGenereticObjects; /// @@ -48,11 +48,15 @@ public class CarBase : AbstractCompany { return; } - if (_collection?.Get(i) != null) + try { - _collection?.Get(i)?.SetPictureSize(_pictureWidth , _pictureHeight); - _collection?.Get(i)?.SetPosition(_placeSizeWidth * nowWidth + 10, nowHeight * _placeSizeHeight * 2 ); - } + if (_collection?.Get(i) != null) + { + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(_placeSizeWidth * nowWidth + 10, nowHeight * _placeSizeHeight * 2); + } + } catch (ObjectNotFoundException) { } + if (nowWidth < _pictureWidth / _placeSizeWidth - 1) nowWidth++; else diff --git a/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs index 3c2a312..ee171c0 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,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 == _maxCount) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); _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(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _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(position); T obj = _collection[position]; _collection.RemoveAt(position); return obj; diff --git a/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs index 21c30d8..f86f961 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,15 @@ 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(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); + return _collection[position]; + } public int Insert(T obj) { - // вставка в свободное место набора + for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -71,66 +70,46 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - // проверка позиции - if (position < 0 || position >= Count) + + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) { - return -1; + _collection[position] = obj; + return position; } - - // проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до - if (_collection[position] != null) + int index = position + 1; + while (index < _collection.Length) { - bool pushed = false; - for (int index = position + 1; index < Count; index++) + if (_collection[index] == 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[index] = obj; + return index; } + ++index; } - - // вставка - _collection[position] = obj; - return position; + 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) { - // проверка позиции - if (position < 0 || position >= Count) - { - return null; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) return null; + if (_collection[position] == null) throw new ObjectNotFoundException(position); T? temp = _collection[position]; _collection[position] = null; diff --git a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs index 2dba4ab..3274c35 100644 --- a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs +++ b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs @@ -1,7 +1,10 @@ -using AntiAircraftGun.CollectionGenereticObject; +using NLog.LayoutRenderers.Wrappers; +using AntiAircraftGun.CollectionGenereticObject; using AntiAircraftGun.Drawnings; +using AntiAircraftGun.Exceptions; using System.Text; + namespace AntiAircraftGun.CollectionGenericObjects; /// @@ -87,33 +90,28 @@ 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)) { File.Delete(filename); } - - StringBuilder sb = new(); - using (StreamWriter writer = new(filename)) { writer.Write(_collectionKey); foreach (KeyValuePair> value in _storages) { writer.Write(Environment.NewLine); - // не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } - writer.Write(value.Key); writer.Write(_separatorForKeyValue); writer.Write(value.Value.GetCollectionType); @@ -128,37 +126,34 @@ public class StorageCollection { continue; } - writer.Write(data); writer.Write(_separatorItems); } } } - 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 IOException("Файл не подходит"); } if (!line.Equals(_collectionKey)) { - //если нет такой записи, то это не те данные - return false; + + throw new IOException("В файле неверные данные"); } _storages.Clear(); while ((line = reader.ReadLine()) != null) @@ -173,25 +168,32 @@ 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); foreach (string elem in set) { - if (elem?.CreateDrawningArmoredCar() is T truck) + if (elem?.CreateDrawningArmoredCar() is T armoredCar) { - if (collection.Insert(truck) == -1) + try { - return false; + if (collection.Insert(armoredCar) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + 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..11a7ec3 --- /dev/null +++ b/AntiAircraftGun/Exceptions/CollectionOverflowException.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 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..65cb98d --- /dev/null +++ b/AntiAircraftGun/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,21 @@ +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 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..2e05b50 --- /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 : 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) { } +} diff --git a/AntiAircraftGun/FormArmoredCarCollection.cs b/AntiAircraftGun/FormArmoredCarCollection.cs index d1517bd..cb74481 100644 --- a/AntiAircraftGun/FormArmoredCarCollection.cs +++ b/AntiAircraftGun/FormArmoredCarCollection.cs @@ -2,7 +2,8 @@ using AntiAircraftGun.CollectionGenereticObjects; using AntiAircraftGun.CollectionGenericObjects; using AntiAircraftGun.Drawnings; - +using AntiAircraftGun.Exceptions; +using Microsoft.Extensions.Logging; namespace AntiAircraftGun; /// @@ -18,14 +19,20 @@ public partial class FormArmoredCarCollection : Form /// Компания /// private AbstractCompany? _company = null; + /// + /// Логгер + /// + private readonly ILogger _logger; /// /// Конструктор /// - public FormArmoredCarCollection() + public FormArmoredCarCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// @@ -46,28 +53,35 @@ public partial class FormArmoredCarCollection : Form private void buttonAddArmoredCar_Click(object sender, EventArgs e) { FormCarConfig form = new(); - // TODO передать метод + form.Show(); form.AddEvent(SetCar); } /// - /// Добавление машины в коллеуции + /// Добавление машины в коллекции /// /// private void SetCar(DrawningArmoredCar? armoredCar) { - if (_company == null || armoredCar == null) + try { - return; + if (_company == null || armoredCar == null) + { + return; + } + if (_company + armoredCar != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: {0}", armoredCar.GetDataForSave()); + } + } - if (_company + armoredCar != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else + + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -83,20 +97,32 @@ public partial class FormArmoredCarCollection : Form { return; } + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } + int pos = Convert.ToInt32(maskedTextBox.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 + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } + } /// @@ -128,27 +154,35 @@ public partial class FormArmoredCarCollection : Form DrawningArmoredCar? armoredcar = null; int counter = 100; - while (armoredcar == null) + try { - armoredcar = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (armoredcar == null) { - break; + armoredcar = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + + if (armoredcar == null) + { + return; + } + + FormAntiAircraftGun form = new() + { + SetArmoredCar = armoredcar + }; + + form.ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - if (armoredcar == null) - { - return; - } - - FormAntiAircraftGun form = new() - { - SetArmoredCar = armoredcar - }; - - form.ShowDialog(); } /// /// Обновление списка в listBoxCollection @@ -179,18 +213,25 @@ public partial class FormArmoredCarCollection : 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(); } /// /// Удаление коллекции @@ -204,13 +245,20 @@ public partial class FormArmoredCarCollection : 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(); } /// /// Создание комании @@ -231,12 +279,19 @@ public partial class FormArmoredCarCollection : Form MessageBox.Show("Коллекция не проинициализирована"); return; } - - switch (comboBoxSelectorCompany.Text) + try { - case "Хранилище": - _company = new CarBase(pictureBox.Width, pictureBox.Height, collection); - break; + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new CarBase(pictureBox.Width, pictureBox.Height, collection); + break; + } + + } + catch (ObjectNotFoundException) + { + } panelCompanyTools.Enabled = true; @@ -251,13 +306,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 +328,18 @@ 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); 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/AntiAircraftGun/Program.cs b/AntiAircraftGun/Program.cs index 09b34fb..92b6150 100644 --- a/AntiAircraftGun/Program.cs +++ b/AntiAircraftGun/Program.cs @@ -1,17 +1,43 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; + namespace AntiAircraftGun { internal static class Program { - /// - /// 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(); - Application.Run(new FormArmoredCarCollection()); + + 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); + var config = new ConfigurationBuilder() + .AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true) + .Build(); + option.AddSerilog(Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(config) + .CreateLogger()); + }); } } -} \ No newline at end of file +} diff --git a/AntiAircraftGun/serilogConfig.json b/AntiAircraftGun/serilogConfig.json new file mode 100644 index 0000000..489c218 --- /dev/null +++ b/AntiAircraftGun/serilogConfig.json @@ -0,0 +1,24 @@ +{ + "AllowedHosts": "*", + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": { + "Default": "Information", + "Override": { + "Microsoft": "Warning", + "System": "Warning" + } + }, + "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ], + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs\\log.txt", + "rollingInterval": "Day", + "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff}|{Level:u}|{SourceContext}|{Message:lj}{NewLine}{Exception}" + } + } + ] + } +}