diff --git a/AirBomber/AirBomber/AirBomber.csproj b/AirBomber/AirBomber/AirBomber.csproj index b57c89e..fb66889 100644 --- a/AirBomber/AirBomber/AirBomber.csproj +++ b/AirBomber/AirBomber/AirBomber.csproj @@ -8,4 +8,27 @@ enable + + + + + + + Always + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/AirBomber/AirBomber/AirplaneNotFoundException.cs b/AirBomber/AirBomber/AirplaneNotFoundException.cs new file mode 100644 index 0000000..727b520 --- /dev/null +++ b/AirBomber/AirBomber/AirplaneNotFoundException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace AirBomber +{ + [Serializable] + internal class AirplaneNotFoundException : ApplicationException + { + public AirplaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public AirplaneNotFoundException() : base() { } + public AirplaneNotFoundException(string message) : base(message) { } + public AirplaneNotFoundException(string message, Exception exception) : base(message, exception) { } + protected AirplaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/AirBomber/AirBomber/EntityAirBomber.cs b/AirBomber/AirBomber/EntityAirBomber.cs index 6d5b03f..c52259a 100644 --- a/AirBomber/AirBomber/EntityAirBomber.cs +++ b/AirBomber/AirBomber/EntityAirBomber.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace AirBomber { - internal class EntityAirBomber : EntityAirplane + public class EntityAirBomber : EntityAirplane { /// /// Дополнительный цвет diff --git a/AirBomber/AirBomber/FormMapWithSetAirplanes.cs b/AirBomber/AirBomber/FormMapWithSetAirplanes.cs index 536dc8a..c4f6072 100644 --- a/AirBomber/AirBomber/FormMapWithSetAirplanes.cs +++ b/AirBomber/AirBomber/FormMapWithSetAirplanes.cs @@ -1,4 +1,5 @@ -using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using System.Windows.Forms; namespace AirBomber { @@ -17,12 +18,17 @@ namespace AirBomber /// private readonly MapsCollection _mapsCollection; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormMapWithSetAirplanes() + public FormMapWithSetAirplanes(ILogger logger) { InitializeComponent(); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); + _logger = logger; comboBoxSelectorMap.Items.Clear(); foreach(var elem in _mapsDict) { @@ -61,15 +67,18 @@ namespace AirBomber if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта"); return; } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text); } /// /// Выбор карты @@ -79,6 +88,7 @@ namespace AirBomber private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation("Был осуществлен переход на карту под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } /// /// Удаление карты @@ -95,6 +105,7 @@ namespace AirBomber if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } } @@ -115,19 +126,30 @@ namespace AirBomber /// private void AddAirplane(DrawningAirplane airplane) { - if (listBoxMaps.SelectedIndex == -1) + try { - MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + if (listBoxMaps.SelectedIndex == -1) + { + MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + } + else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(airplane) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Airplane}", airplane); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить объект"); + } } - else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(airplane) != -1) + catch (StorageOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message); + MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } + } /// /// Удаление объекта @@ -142,15 +164,27 @@ namespace AirBomber return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + var deletedAirplane = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (deletedAirplane != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation("Из текущей карты удален объект {@Airplane}", deletedAirplane); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (AirplaneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); } + } /// /// Вывод набора @@ -219,13 +253,16 @@ namespace AirBomber { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if(_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); } } } @@ -238,14 +275,17 @@ namespace AirBomber { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName); ReloadMaps(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось открыть", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message); } } } diff --git a/AirBomber/AirBomber/MapsCollection.cs b/AirBomber/AirBomber/MapsCollection.cs index 8a98985..c9aaea7 100644 --- a/AirBomber/AirBomber/MapsCollection.cs +++ b/AirBomber/AirBomber/MapsCollection.cs @@ -84,8 +84,7 @@ namespace AirBomber /// Сохранение информации по самолетам в хранилище в файл /// /// Путь и имя файла - /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -99,25 +98,24 @@ namespace AirBomber fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } - return true; } /// /// Загрузка информации по самолетам в ангарах из файла /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader fs = new(filename)) { if (!fs.ReadLine().Contains("MapsCollection")) { //если нет такой записи, то это не те данные - return false; + throw new FileFormatException("Формат данных в файле не правильный"); } //очищаем записи _mapStorages.Clear(); @@ -140,7 +138,6 @@ namespace AirBomber StringSplitOptions.RemoveEmptyEntries)); } } - return true; } } } diff --git a/AirBomber/AirBomber/Program.cs b/AirBomber/AirBomber/Program.cs index 5325330..f0821c2 100644 --- a/AirBomber/AirBomber/Program.cs +++ b/AirBomber/AirBomber/Program.cs @@ -1,3 +1,10 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Extensions.Logging; +using System; + namespace AirBomber { internal static class Program @@ -11,7 +18,30 @@ namespace AirBomber // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetAirplanes()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "appsettings.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/AirBomber/AirBomber/SetAirplanesGeneric.cs b/AirBomber/AirBomber/SetAirplanesGeneric.cs index c3a054a..986ccf7 100644 --- a/AirBomber/AirBomber/SetAirplanesGeneric.cs +++ b/AirBomber/AirBomber/SetAirplanesGeneric.cs @@ -54,6 +54,8 @@ namespace AirBomber /// Возвращает позицию вставленного объекта, либо -1 если его не удалось вставить public int Insert(T airplane, int position) { + if (Count == _maxcount) + throw new StorageOverflowException(_maxcount); if (!isCorrectPosition(position)) { return -1; @@ -70,7 +72,9 @@ namespace AirBomber { if (!isCorrectPosition(position)) return null; - var result = _places[position]; + var result = this[position]; + if (result == null) + throw new AirplaneNotFoundException(position); _places.RemoveAt(position); return result; } diff --git a/AirBomber/AirBomber/StorageOverflowException.cs b/AirBomber/AirBomber/StorageOverflowException.cs new file mode 100644 index 0000000..1701690 --- /dev/null +++ b/AirBomber/AirBomber/StorageOverflowException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace AirBomber +{ + [Serializable] + internal class StorageOverflowException : ApplicationException + { + public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { } + public StorageOverflowException() : base() { } + public StorageOverflowException(string message) : base(message) { } + public StorageOverflowException(string message, Exception exception) : base(message, exception) { } + protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} \ No newline at end of file diff --git a/AirBomber/AirBomber/appsettings.json b/AirBomber/AirBomber/appsettings.json new file mode 100644 index 0000000..94031e0 --- /dev/null +++ b/AirBomber/AirBomber/appsettings.json @@ -0,0 +1,48 @@ +{ + "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" ], + "Destructure": [ + { + "Name": "ByTransforming", + "Args": { + "returnType": "AirBomber.EntityAirplane", + "transformation": "r => new { BodyColor = r.BodyColor.Name, r.Speed, r.Weight }" + } + }, + { + "Name": "ByTransforming", + "Args": { + "returnType": "AirBomber.EntityAirBomber", + "transformation": "r => new { BodyColor = r.BodyColor.Name, DopColor = r.DopColor.Name, r.HasBombs, r.HasFuelTanks, r.Speed, r.Weight }" + } + }, + { + "Name": "ToMaximumDepth", + "Args": { "maximumDestructuringDepth": 4 } + }, + { + "Name": "ToMaximumStringLength", + "Args": { "maximumStringLength": 100 } + }, + { + "Name": "ToMaximumCollectionCount", + "Args": { "maximumCollectionCount": 10 } + } + ], + "Properties": { + "Application": "AirBomber" + } + } +} \ No newline at end of file