From edeb29cb7668d4dffbe50f21a1143a2792071aed Mon Sep 17 00:00:00 2001 From: abazov73 <92822431+abazov73@users.noreply.github.com> Date: Tue, 29 Nov 2022 12:18:03 +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=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AirBomber/AirBomberNotFoundException.cs | 19 +++++++ .../AirBomber/FormMapWithSetAirBombers.cs | 56 ++++++++++++++----- AirBomber/AirBomber/MapsCollection.cs | 10 ++-- AirBomber/AirBomber/SetAirBombersGeneric.cs | 15 ++++- .../AirBomber/StorageOverflowException.cs | 19 +++++++ 5 files changed, 96 insertions(+), 23 deletions(-) create mode 100644 AirBomber/AirBomber/AirBomberNotFoundException.cs create mode 100644 AirBomber/AirBomber/StorageOverflowException.cs diff --git a/AirBomber/AirBomber/AirBomberNotFoundException.cs b/AirBomber/AirBomber/AirBomberNotFoundException.cs new file mode 100644 index 0000000..9ff6925 --- /dev/null +++ b/AirBomber/AirBomber/AirBomberNotFoundException.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 AirBomber +{ + [Serializable] + internal class AirBomberNotFoundException : ApplicationException + { + public AirBomberNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public AirBomberNotFoundException() : base() { } + public AirBomberNotFoundException(string message) : base(message) { } + public AirBomberNotFoundException(string message, Exception exception) : base(message, exception) { } + protected AirBomberNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/AirBomber/AirBomber/FormMapWithSetAirBombers.cs b/AirBomber/AirBomber/FormMapWithSetAirBombers.cs index e9d7648..2ce2671 100644 --- a/AirBomber/AirBomber/FormMapWithSetAirBombers.cs +++ b/AirBomber/AirBomber/FormMapWithSetAirBombers.cs @@ -48,9 +48,20 @@ namespace AirBomber { return; } - var formAirBomberConfig = new FormAirBomberConfig(); - formAirBomberConfig.AddEvent(AddAction); - formAirBomberConfig.Show(); + try + { + var formAirBomberConfig = new FormAirBomberConfig(); + formAirBomberConfig.AddEvent(AddAction); + formAirBomberConfig.Show(); + } + catch (StorageOverflowException ex) + { + MessageBox.Show(ex.Message); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } private void buttonRemoveAirBomber_Click(object sender, EventArgs e) @@ -68,14 +79,21 @@ 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(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } } - else + catch (AirBomberNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -183,13 +201,14 @@ namespace AirBomber { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(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); } } } @@ -198,14 +217,23 @@ namespace AirBomber { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); } - else + catch(FileFormatException ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + catch(FileNotFoundException ex) + { + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/AirBomber/AirBomber/MapsCollection.cs b/AirBomber/AirBomber/MapsCollection.cs index b33ff80..a11452a 100644 --- a/AirBomber/AirBomber/MapsCollection.cs +++ b/AirBomber/AirBomber/MapsCollection.cs @@ -87,7 +87,7 @@ namespace AirBomber /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -102,7 +102,6 @@ namespace AirBomber sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", sw); } } - return true; } /// @@ -110,11 +109,11 @@ namespace AirBomber /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (FileStream fs = new(filename, FileMode.Open)) using (StreamReader sr = new StreamReader(fs)) @@ -122,7 +121,7 @@ namespace AirBomber string line; line = sr.ReadLine(); line.Trim(); - if (line != "MapsCollection") return false; + if (line != "MapsCollection") throw new FileFormatException("Неверный формат файла"); _mapStorages.Clear(); while ((line = sr.ReadLine()) != null) { @@ -145,7 +144,6 @@ namespace AirBomber _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } - return true; } } } diff --git a/AirBomber/AirBomber/SetAirBombersGeneric.cs b/AirBomber/AirBomber/SetAirBombersGeneric.cs index a743086..aa09fbc 100644 --- a/AirBomber/AirBomber/SetAirBombersGeneric.cs +++ b/AirBomber/AirBomber/SetAirBombersGeneric.cs @@ -36,7 +36,10 @@ namespace AirBomber /// public int Insert(T airBomber) { - if (_places.Count + 1 >= _maxCount) return -1; + if (_places.Count + 1 >= _maxCount) + { + throw new StorageOverflowException(_maxCount); + } _places.Insert(0, airBomber); return 0; } @@ -49,7 +52,10 @@ namespace AirBomber public int Insert(T airBomber, int position) { if (position < 0 || position >= _maxCount) return -1; - if (_places.Count + 1 >= _maxCount) return -1; + if (_places.Count + 1 >= _maxCount) + { + throw new StorageOverflowException(_maxCount); + } _places.Insert(position, airBomber); return position; } @@ -60,7 +66,10 @@ namespace AirBomber /// public T Remove(int position) { - if (position < 0 || position >= _maxCount) return null; + if (position < 0 || position >= _maxCount) + { + throw new AirBomberNotFoundException(position); + } T removedObject = _places[position]; _places.RemoveAt(position); return removedObject; diff --git a/AirBomber/AirBomber/StorageOverflowException.cs b/AirBomber/AirBomber/StorageOverflowException.cs new file mode 100644 index 0000000..a3fa037 --- /dev/null +++ b/AirBomber/AirBomber/StorageOverflowException.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 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) { } + } +} -- 2.25.1 From 3bc4f02768b042261984a5bf313831df5e0cbe55 Mon Sep 17 00:00:00 2001 From: abazov73 <92822431+abazov73@users.noreply.github.com> Date: Tue, 29 Nov 2022 14:29:47 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9B=D0=BE=D0=B3=D0=B3=D0=B8=D0=BD=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AirBomber/AirBomber/AirBomber.csproj | 23 ++++++ .../AirBomber/FormMapWithSetAirBombers.cs | 74 +++++++++++++------ AirBomber/AirBomber/Program.cs | 29 +++++++- AirBomber/AirBomber/SetAirBombersGeneric.cs | 6 +- AirBomber/AirBomber/appsettings.json | 24 ++++++ 5 files changed, 131 insertions(+), 25 deletions(-) create mode 100644 AirBomber/AirBomber/appsettings.json diff --git a/AirBomber/AirBomber/AirBomber.csproj b/AirBomber/AirBomber/AirBomber.csproj index 13ee123..9f835ae 100644 --- a/AirBomber/AirBomber/AirBomber.csproj +++ b/AirBomber/AirBomber/AirBomber.csproj @@ -8,6 +8,29 @@ enable + + + + + + + Always + + + + + + + + + + + + + + + + True diff --git a/AirBomber/AirBomber/FormMapWithSetAirBombers.cs b/AirBomber/AirBomber/FormMapWithSetAirBombers.cs index 2ce2671..fc51939 100644 --- a/AirBomber/AirBomber/FormMapWithSetAirBombers.cs +++ b/AirBomber/AirBomber/FormMapWithSetAirBombers.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -29,17 +30,44 @@ namespace AirBomber private Action AddAction; - public FormMapWithSetAirBombers() + private readonly ILogger _logger; + + public FormMapWithSetAirBombers(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) { comboBoxSelectorMap.Items.Add(elem.Key); } - AddAction = airBomber => { _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].add(new DrawingObjectAirBomber(airBomber)); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();}; + AddAction = addAirBomber; + } + + private void addAirBomber(DrawingAirBomber airBomber) + { + try + { + int res = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectAirBomber(airBomber); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Добавлен объект {airBomber.ToString()}"); + } + catch (ArgumentNullException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"Ошибка: {ex.Message}"); + } + catch (StorageOverflowException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"Ошибка: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); + } } private void buttonAddAirBomber_Click(object sender, EventArgs e) @@ -48,20 +76,9 @@ namespace AirBomber { return; } - try - { - var formAirBomberConfig = new FormAirBomberConfig(); - formAirBomberConfig.AddEvent(AddAction); - formAirBomberConfig.Show(); - } - catch (StorageOverflowException ex) - { - MessageBox.Show(ex.Message); - } - catch (Exception ex) - { - MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); - } + var formAirBomberConfig = new FormAirBomberConfig(); + formAirBomberConfig.AddEvent(AddAction); + formAirBomberConfig.Show(); } private void buttonRemoveAirBomber_Click(object sender, EventArgs e) @@ -81,19 +98,20 @@ namespace AirBomber int pos = Convert.ToInt32(maskedTextBoxPosition.Text); try { - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } + IDrawingObject drawingObject = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Удалён объект {drawingObject.ToString()}"); } catch (AirBomberNotFoundException ex) { MessageBox.Show($"Ошибка удаления: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); } catch (Exception ex) { MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); } } @@ -177,11 +195,13 @@ namespace AirBomber } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}, тип карты: {comboBoxSelectorMap.Text}"); } private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } private void buttonDeleteMap_Click(object sender, EventArgs e) @@ -190,11 +210,13 @@ namespace AirBomber { return; } + string mapName = listBoxMaps.SelectedItem?.ToString(); if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } + _logger.LogInformation($"Удалена карта {mapName}"); } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) @@ -205,10 +227,12 @@ namespace AirBomber { _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}"); } } } @@ -222,18 +246,22 @@ namespace AirBomber _mapsCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); + _logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}"); } catch(FileFormatException ex) { MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); } catch(FileNotFoundException ex) { MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); } catch (Exception ex) { MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); } } } diff --git a/AirBomber/AirBomber/Program.cs b/AirBomber/AirBomber/Program.cs index d75f7b1..17e4b78 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 Microsoft.VisualBasic.Logging; +using Serilog; +using System; + namespace AirBomber { internal static class Program @@ -11,7 +18,27 @@ 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 FormMapWithSetAirBombers()); + 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 => + { + option.SetMinimumLevel(LogLevel.Information); + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json") + .Build(); + Serilog.Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + option.AddSerilog(); + }); } } } \ No newline at end of file diff --git a/AirBomber/AirBomber/SetAirBombersGeneric.cs b/AirBomber/AirBomber/SetAirBombersGeneric.cs index aa09fbc..f5047e1 100644 --- a/AirBomber/AirBomber/SetAirBombersGeneric.cs +++ b/AirBomber/AirBomber/SetAirBombersGeneric.cs @@ -36,7 +36,11 @@ namespace AirBomber /// public int Insert(T airBomber) { - if (_places.Count + 1 >= _maxCount) + if (airBomber == null) + { + throw new ArgumentNullException(); + } + if (_places.Count + 1 > _maxCount) { throw new StorageOverflowException(_maxCount); } diff --git a/AirBomber/AirBomber/appsettings.json b/AirBomber/AirBomber/appsettings.json new file mode 100644 index 0000000..d2acb30 --- /dev/null +++ b/AirBomber/AirBomber/appsettings.json @@ -0,0 +1,24 @@ +{ + "exclude": [ + "**/bin", + "**/bower_components", + "**/jspm_packages", + "**/node_modules", + "**/obj", + "**/platforms" + ], + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "Logs/log.log" } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file -- 2.25.1 From ddb2f99e7a8c2bdc9ada18eb23c3af1eee678d94 Mon Sep 17 00:00:00 2001 From: abazov73 <92822431+abazov73@users.noreply.github.com> Date: Fri, 2 Dec 2022 00:12:05 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BD=D0=B5=D0=B4=D0=BE=D1=81=D1=82=D0=B0=D1=8E=D1=89?= =?UTF-8?q?=D0=B8=D0=B9=20=D0=BF=D1=80=D0=BE=D0=B1=D1=80=D0=BE=D1=81=20Air?= =?UTF-8?q?BomberNotFoundException=20=D0=B2=20=D0=BC=D0=B5=D1=82=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=20Insert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AirBomber/AirBomber/SetAirBombersGeneric.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/AirBomber/AirBomber/SetAirBombersGeneric.cs b/AirBomber/AirBomber/SetAirBombersGeneric.cs index f5047e1..f494dd8 100644 --- a/AirBomber/AirBomber/SetAirBombersGeneric.cs +++ b/AirBomber/AirBomber/SetAirBombersGeneric.cs @@ -55,7 +55,10 @@ namespace AirBomber /// public int Insert(T airBomber, int position) { - if (position < 0 || position >= _maxCount) return -1; + if (position < 0 || position >= _maxCount) + { + throw new AirBomberNotFoundException(position); + } if (_places.Count + 1 >= _maxCount) { throw new StorageOverflowException(_maxCount); -- 2.25.1