From 542c68a68f343229b1429927d0961b1ab938d7bf Mon Sep 17 00:00:00 2001 From: Danil Kargin Date: Sun, 27 Nov 2022 16:17:52 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D0=93=D0=B5=D0=BD=D0=B5=D1=80=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AirFighter/AirFighterNotFoundException.cs | 20 +++++++ .../AirFighter/FormMapWithSetAirFighters.cs | 59 +++++++++++++------ AirFighter/AirFighter/MapsCollection.cs | 7 +-- .../AirFighter/SetAirFightersGeneric.cs | 10 +++- .../AirFighter/StorageOverflowException.cs | 21 +++++++ 5 files changed, 93 insertions(+), 24 deletions(-) create mode 100644 AirFighter/AirFighter/AirFighterNotFoundException.cs create mode 100644 AirFighter/AirFighter/StorageOverflowException.cs diff --git a/AirFighter/AirFighter/AirFighterNotFoundException.cs b/AirFighter/AirFighter/AirFighterNotFoundException.cs new file mode 100644 index 0000000..a79b9b4 --- /dev/null +++ b/AirFighter/AirFighter/AirFighterNotFoundException.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 AirFighter +{ + internal class AirFighterNotFoundException : ApplicationException + { + public AirFighterNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public AirFighterNotFoundException() : base() { } + public AirFighterNotFoundException(string message) : base(message) { } + public AirFighterNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected AirFighterNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/AirFighter/AirFighter/FormMapWithSetAirFighters.cs b/AirFighter/AirFighter/FormMapWithSetAirFighters.cs index 83514e4..20b5593 100644 --- a/AirFighter/AirFighter/FormMapWithSetAirFighters.cs +++ b/AirFighter/AirFighter/FormMapWithSetAirFighters.cs @@ -68,14 +68,25 @@ namespace AirFighter if (_airFighter != null) { DrawningObjectAirFighter airFighter = new(_airFighter); - if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + airFighter) == 0) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + airFighter) == 0) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show($"Ошибка добавления: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } } @@ -113,14 +124,24 @@ namespace AirFighter 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(); + if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos) != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } + }catch(AirFighterNotFoundException ex) + { + MessageBox.Show($"Ошибка удаления: {ex.Message}"); } - else + catch(Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } /// @@ -237,14 +258,15 @@ namespace AirFighter { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch(Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -258,15 +280,16 @@ namespace AirFighter { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); } - else + catch(Exception ex) { - MessageBox.Show("Загрузка не удалась", "Результат", + MessageBox.Show($"Загрузка не удалась: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/AirFighter/AirFighter/MapsCollection.cs b/AirFighter/AirFighter/MapsCollection.cs index 9f35ac0..7a27c1e 100644 --- a/AirFighter/AirFighter/MapsCollection.cs +++ b/AirFighter/AirFighter/MapsCollection.cs @@ -114,11 +114,11 @@ namespace AirFighter /// /// /// < returns > - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } string bufferTextFromFile = ""; using (StreamReader sr = new(filename)) @@ -126,7 +126,7 @@ namespace AirFighter string checkMap = sr.ReadLine(); if (!checkMap.Contains("MapsCollection")) { - return false; + throw new FileFormatException("Формат данных в файле не правильный"); } bufferTextFromFile = sr.ReadLine(); _mapStorages.Clear(); @@ -148,7 +148,6 @@ namespace AirFighter bufferTextFromFile = sr.ReadLine(); } } - return true; } } } diff --git a/AirFighter/AirFighter/SetAirFightersGeneric.cs b/AirFighter/AirFighter/SetAirFightersGeneric.cs index 2800138..fbc5f64 100644 --- a/AirFighter/AirFighter/SetAirFightersGeneric.cs +++ b/AirFighter/AirFighter/SetAirFightersGeneric.cs @@ -52,6 +52,10 @@ namespace AirFighter /// public int Insert(T airFighter, int position) { + if (Count >= _maxCount) + { + throw new StorageOverflowException(); + } if (position < 0 && position > _maxCount) { return -1; @@ -69,14 +73,16 @@ namespace AirFighter /// public T Remove(int position) { - if (position >= 0 && position < _maxCount && _places[position] != null) + if (position >= 0 && position < Count) { T temp = _places[position]; _places.RemoveAt(position); return temp; } else - return null; + { + throw new AirFighterNotFoundException(position); + } } /// /// Получение объекта из набора по позиции diff --git a/AirFighter/AirFighter/StorageOverflowException.cs b/AirFighter/AirFighter/StorageOverflowException.cs new file mode 100644 index 0000000..b3e2378 --- /dev/null +++ b/AirFighter/AirFighter/StorageOverflowException.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 AirFighter +{ + [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) { } + } +} -- 2.25.1 From 1a2f836bdf9c63db196ef31003e9df2f1adf98fe Mon Sep 17 00:00:00 2001 From: Danil Kargin Date: Sun, 27 Nov 2022 22:50:06 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9B=D0=BE=D0=B3=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AirFighter/AirFighter/AirFighter.csproj | 21 +++++++++++++ .../AirFighter/FormMapWithSetAirFighters.cs | 27 ++++++++++++++-- AirFighter/AirFighter/Program.cs | 31 ++++++++++++++++++- AirFighter/AirFighter/serilogconfig.json | 16 ++++++++++ 4 files changed, 91 insertions(+), 4 deletions(-) create mode 100644 AirFighter/AirFighter/serilogconfig.json diff --git a/AirFighter/AirFighter/AirFighter.csproj b/AirFighter/AirFighter/AirFighter.csproj index 13ee123..6578c4c 100644 --- a/AirFighter/AirFighter/AirFighter.csproj +++ b/AirFighter/AirFighter/AirFighter.csproj @@ -8,6 +8,27 @@ enable + + + + + + + Always + + + + + + + + + + + + + + True diff --git a/AirFighter/AirFighter/FormMapWithSetAirFighters.cs b/AirFighter/AirFighter/FormMapWithSetAirFighters.cs index 20b5593..7ffd860 100644 --- a/AirFighter/AirFighter/FormMapWithSetAirFighters.cs +++ b/AirFighter/AirFighter/FormMapWithSetAirFighters.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -26,10 +27,15 @@ namespace AirFighter /// private readonly MapsCollection _mapsCollection; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор - public FormMapWithSetAirFighters() + public FormMapWithSetAirFighters(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -74,19 +80,23 @@ namespace AirFighter { MessageBox.Show("Объект добавлен"); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Добавлен объект {airFighter}"); } else { MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation($"Не удалось добавить объект {airFighter}"); } } catch (StorageOverflowException ex) { MessageBox.Show($"Ошибка добавления: {ex.Message}"); + _logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}"); } catch (Exception ex) { MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); } } } @@ -126,22 +136,27 @@ namespace AirFighter int pos = Convert.ToInt32(maskedTextBoxPosition.Text); try { - if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos) != null) + var deletedObject = (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos); + if (deletedObject != null) { MessageBox.Show("Объект удален"); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Удаление объекта {deletedObject}"); } else { MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation($"Не удалось удалить объект {deletedObject}"); } }catch(AirFighterNotFoundException ex) { MessageBox.Show($"Ошибка удаления: {ex.Message}"); + _logger.LogWarning($"Ошибка, объект не найден: {ex.Message}"); } catch(Exception ex) { MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); } } /// @@ -222,6 +237,7 @@ namespace AirFighter } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); + _logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}"); ReloadMaps(); } /// @@ -248,6 +264,7 @@ namespace AirFighter { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem}"); } } /// @@ -263,11 +280,13 @@ namespace AirFighter _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранение в файл {saveFileDialog.FileName} прошло успешно"); } catch(Exception ex) { MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить в файл. Ошибка: {ex.Message}"); } } } @@ -285,12 +304,14 @@ namespace AirFighter _mapsCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузка из файла {openFileDialog.FileName} прошла успешна"); ReloadMaps(); } catch(Exception ex) { MessageBox.Show($"Загрузка не удалась: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось загрузить из файла. Ошибка: {ex.Message}"); } } } diff --git a/AirFighter/AirFighter/Program.cs b/AirFighter/AirFighter/Program.cs index f61e6a6..e83da85 100644 --- a/AirFighter/AirFighter/Program.cs +++ b/AirFighter/AirFighter/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace AirFighter { internal static class Program @@ -11,7 +16,31 @@ namespace AirFighter // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetAirFighters()); + 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: "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/serilogconfig.json b/AirFighter/AirFighter/serilogconfig.json new file mode 100644 index 0000000..8bf6872 --- /dev/null +++ b/AirFighter/AirFighter/serilogconfig.json @@ -0,0 +1,16 @@ +{ + "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}" + } + } + ] + } +} -- 2.25.1 From 60bbe79b41ebb3fb74b44bc413846b542093d8f4 Mon Sep 17 00:00:00 2001 From: Danil Kargin Date: Sun, 27 Nov 2022 23:29:14 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=BB=D0=B0=D0=B17?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AirFighter/AirFighter/FormMapWithSetAirFighters.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/AirFighter/AirFighter/FormMapWithSetAirFighters.cs b/AirFighter/AirFighter/FormMapWithSetAirFighters.cs index 7ffd860..fb68958 100644 --- a/AirFighter/AirFighter/FormMapWithSetAirFighters.cs +++ b/AirFighter/AirFighter/FormMapWithSetAirFighters.cs @@ -248,6 +248,7 @@ namespace AirFighter private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Осуществлен переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } /// /// Удаление карты -- 2.25.1