From 58f9a4f809b624a45078a2c6ec7a31f8048107ee Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 22 Nov 2022 00:51:18 +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 --- .../AirplaneNotFoundException.cs | 19 +++++++ .../FormMapWithSetAirplane.cs | 50 +++++++++++++------ .../AirplaneWithRadar/SetAirplaneGeneric.cs | 25 +++++++--- .../StorageOverflowException.cs | 19 +++++++ 4 files changed, 90 insertions(+), 23 deletions(-) create mode 100644 AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs create mode 100644 AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs new file mode 100644 index 0000000..b9f1b52 --- /dev/null +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.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 AirplaneWithRadar +{ + [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 context) : base(info, context) { } + } +} diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormMapWithSetAirplane.cs b/AirplaneWithRadar/AirplaneWithRadar/FormMapWithSetAirplane.cs index 16181cf..29e4aaa 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormMapWithSetAirplane.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormMapWithSetAirplane.cs @@ -85,20 +85,30 @@ namespace AirplaneWithRadar } private void AddAirplane(DrawningAirplane airplane) { - if (ListBoxMaps.SelectedIndex == -1) + try { - return; + if (ListBoxMaps.SelectedIndex == -1) + { + return; + } + if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectAirplane(airplane) != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } - if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectAirplane(airplane) != -1) + catch (StorageOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - else + catch (ArgumentException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - } /// /// Добавление объекта @@ -131,15 +141,25 @@ namespace AirplaneWithRadar } 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("Не удалось удалить объект"); + } } - else + catch (AirplaneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } /// @@ -253,7 +273,7 @@ namespace AirplaneWithRadar } catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/AirplaneWithRadar/AirplaneWithRadar/SetAirplaneGeneric.cs b/AirplaneWithRadar/AirplaneWithRadar/SetAirplaneGeneric.cs index 6ebcebc..b9a7f88 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/SetAirplaneGeneric.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/SetAirplaneGeneric.cs @@ -26,20 +26,29 @@ // Добавление объекта в набор на конкретную позицию public int Insert(T airplane, int position) { - if (position >= _maxCount || position < 0) return -1; + if (Count == _maxCount) + { + throw new StorageOverflowException(_maxCount); + } + if (position < 0 || position > _maxCount) return -1; _places.Insert(position, airplane); return position; } // Удаление объекта из набора с конкретной позиции public T Remove(int position) { - // проверка позиции - if (position >= _maxCount || position < 0) return null; - // удаление объекта из массива, присовив элементу массива значение null - T temp = _places[position]; - _places.RemoveAt(position); - return temp; - } + if (position < Count || position > 0) + { + if (_places.ElementAt(position) != null) + { + T ship = _places[position]; + _places.RemoveAt(position); + return ship; + } + throw new AirplaneNotFoundException(position); + } + return null; + } // Получение объекта из набора по позиции public T this[int position] { diff --git a/AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs b/AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs new file mode 100644 index 0000000..ae5e87f --- /dev/null +++ b/AirplaneWithRadar/AirplaneWithRadar/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 AirplaneWithRadar +{ + [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 context) : base(info, context) { } + } +} -- 2.25.1 From 3a77f272fc7cee07d01a0c49f2dd35552ffe3604 Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 22 Nov 2022 01:04:04 +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 --- .../AirplaneWithRadar.csproj | 17 ++++++++++++ .../FormMapWithSetAirplane.cs | 27 ++++++++++++++++--- .../AirplaneWithRadar/Program.cs | 21 ++++++++++++++- .../AirplaneWithRadar/SetAirplaneGeneric.cs | 13 ++++----- .../AirplaneWithRadar/nlog.config | 15 +++++++++++ 5 files changed, 81 insertions(+), 12 deletions(-) create mode 100644 AirplaneWithRadar/AirplaneWithRadar/nlog.config diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj index 13ee123..80654cf 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj @@ -8,6 +8,23 @@ enable + + + + + + + Always + + + + + + + + + + True diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormMapWithSetAirplane.cs b/AirplaneWithRadar/AirplaneWithRadar/FormMapWithSetAirplane.cs index 29e4aaa..b905e95 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormMapWithSetAirplane.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormMapWithSetAirplane.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -24,9 +25,11 @@ namespace AirplaneWithRadar {"Карта туманного неба с грозой", new FoggySkyMap() } }; private readonly MapsCollection _mapsCollection; - public FormMapWithSetAirplane() + private ILogger _logger; + public FormMapWithSetAirplane(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapDict) @@ -94,19 +97,23 @@ namespace AirplaneWithRadar if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectAirplane(airplane) != -1) { MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Airplane}", airplane); pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); } else { MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить объект"); } } catch (StorageOverflowException ex) { + _logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message); MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (ArgumentException ex) { + _logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, airplane); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -143,22 +150,27 @@ namespace AirplaneWithRadar int pos = Convert.ToInt32(maskedTextBoxPosition.Text); try { - if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? String.Empty] - pos != null) + var deletedAirplane = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (deletedAirplane != null) { MessageBox.Show("Объект удалён"); + _logger.LogInformation("Из текущей карты удалён объект {@Ship}", deletedAirplane); pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet(); } else { + _logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos); MessageBox.Show("Не удалось удалить объект"); } } catch (AirplaneNotFoundException ex) { + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); MessageBox.Show($"Ошибка удаления: {ex.Message}"); } catch (Exception ex) { + _logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message); MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } @@ -224,11 +236,13 @@ namespace AirplaneWithRadar if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта"); return; } if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text); return; } if (textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';')) @@ -238,11 +252,13 @@ namespace AirplaneWithRadar } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}"); } 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); } private void ButtonDeleteMap_Click(object sender, EventArgs e) @@ -255,6 +271,7 @@ namespace AirplaneWithRadar { _mapsCollection.DelMap(ListBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.LogInformation("Удалена карта {0}", ListBoxMaps.SelectedItem?.ToString() ?? string.Empty); } } /// @@ -269,11 +286,13 @@ namespace AirplaneWithRadar try { _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); } } } @@ -290,11 +309,13 @@ namespace AirplaneWithRadar try { _mapsCollection.LoadData(openFileDialog.FileName); + _logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName); ReloadMaps(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { + _logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message); MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/AirplaneWithRadar/AirplaneWithRadar/Program.cs b/AirplaneWithRadar/AirplaneWithRadar/Program.cs index 7c1941f..fc55971 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/Program.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; + namespace AirplaneWithRadar { internal static class Program @@ -11,7 +16,21 @@ namespace AirplaneWithRadar // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetAirplane()); + 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); + option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/AirplaneWithRadar/AirplaneWithRadar/SetAirplaneGeneric.cs b/AirplaneWithRadar/AirplaneWithRadar/SetAirplaneGeneric.cs index b9a7f88..b51b9cc 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/SetAirplaneGeneric.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/SetAirplaneGeneric.cs @@ -37,17 +37,14 @@ // Удаление объекта из набора с конкретной позиции public T Remove(int position) { - if (position < Count || position > 0) + if (position >= Count || position < 0) { - if (_places.ElementAt(position) != null) - { - T ship = _places[position]; - _places.RemoveAt(position); - return ship; - } throw new AirplaneNotFoundException(position); } - return null; + T airplane = _places[position]; + _places.RemoveAt(position); + return airplane; + } // Получение объекта из набора по позиции public T this[int position] diff --git a/AirplaneWithRadar/AirplaneWithRadar/nlog.config b/AirplaneWithRadar/AirplaneWithRadar/nlog.config new file mode 100644 index 0000000..5c71e85 --- /dev/null +++ b/AirplaneWithRadar/AirplaneWithRadar/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file -- 2.25.1 From 5dd9b3f1cb54d4ffc81c4f41d24c74db34672c7b Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 6 Dec 2022 01:02:00 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20nlog=20=D0=BD=D0=B0=20serilog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AirplaneWithRadar.csproj | 20 +++++++------- .../AirplaneWithRadar/FormAirplaneConfig.cs | 4 +++ .../AirplaneWithRadar/Program.cs | 26 ++++++++++++++----- .../AirplaneWithRadar/nlog.config | 15 ----------- .../AirplaneWithRadar/serilog.json | 20 ++++++++++++++ 5 files changed, 54 insertions(+), 31 deletions(-) delete mode 100644 AirplaneWithRadar/AirplaneWithRadar/nlog.config create mode 100644 AirplaneWithRadar/AirplaneWithRadar/serilog.json diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj index 80654cf..d19108c 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj @@ -9,20 +9,20 @@ - - - - - - Always - - - - + + + + + + + + + + diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs index 7c5a819..5d1bcc9 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs @@ -87,6 +87,10 @@ namespace AirplaneWithRadar _airplane = new DrawningAirplaneWithRadar((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, labelBaseColor.BackColor, labelDopColor.BackColor, checkBoxAddRadar.Checked, checkBoxAddLadder.Checked, checkBoxAddWindow.Checked); break; + + case null: + throw new AirplaneNotFoundException(0); + break; } DrawAirplane(); diff --git a/AirplaneWithRadar/AirplaneWithRadar/Program.cs b/AirplaneWithRadar/AirplaneWithRadar/Program.cs index fc55971..0c2e406 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/Program.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/Program.cs @@ -1,8 +1,9 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; using Serilog; + namespace AirplaneWithRadar { internal static class Program @@ -25,12 +26,25 @@ namespace AirplaneWithRadar } private static void ConfigureServices(ServiceCollection services) { + string path = Directory.GetCurrentDirectory(); + path = path.Substring(0, path.LastIndexOf("\\")); + path = path.Substring(0, path.LastIndexOf("\\")); + path = path.Substring(0, path.LastIndexOf("\\")); services.AddSingleton() - .AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); + .AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: path + "\\serilog.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/AirplaneWithRadar/AirplaneWithRadar/nlog.config b/AirplaneWithRadar/AirplaneWithRadar/nlog.config deleted file mode 100644 index 5c71e85..0000000 --- a/AirplaneWithRadar/AirplaneWithRadar/nlog.config +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/AirplaneWithRadar/AirplaneWithRadar/serilog.json b/AirplaneWithRadar/AirplaneWithRadar/serilog.json new file mode 100644 index 0000000..93b2c5b --- /dev/null +++ b/AirplaneWithRadar/AirplaneWithRadar/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "ContainerShip" + } + } +} -- 2.25.1