From aceb46ebe155ca436bd7ca268b2bf2fea0c3e2dd Mon Sep 17 00:00:00 2001 From: ArtemEmelyanov Date: Fri, 25 Nov 2022 15:57:08 +0400 Subject: [PATCH 1/5] =?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 --- Airbus/Airbus/FormMapWithSetPlanes.cs | 40 ++++++++++++++--------- Airbus/Airbus/MapsCollection.cs | 20 +++--------- Airbus/Airbus/PlaneNotFoundException.cs | 19 +++++++++++ Airbus/Airbus/SetPlanesGeneric.cs | 9 +++-- Airbus/Airbus/StorageOverflowException.cs | 19 +++++++++++ 5 files changed, 71 insertions(+), 36 deletions(-) create mode 100644 Airbus/Airbus/PlaneNotFoundException.cs create mode 100644 Airbus/Airbus/StorageOverflowException.cs diff --git a/Airbus/Airbus/FormMapWithSetPlanes.cs b/Airbus/Airbus/FormMapWithSetPlanes.cs index b51ea65..71f8274 100644 --- a/Airbus/Airbus/FormMapWithSetPlanes.cs +++ b/Airbus/Airbus/FormMapWithSetPlanes.cs @@ -154,14 +154,24 @@ namespace Airbus return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + try{ + 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 (PlaneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } /// @@ -230,15 +240,14 @@ namespace Airbus { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Information); + _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); } } } @@ -248,14 +257,15 @@ namespace Airbus // TODO продумать логику if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); ReloadMaps(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/Airbus/Airbus/MapsCollection.cs b/Airbus/Airbus/MapsCollection.cs index a1ecbed..4700bdb 100644 --- a/Airbus/Airbus/MapsCollection.cs +++ b/Airbus/Airbus/MapsCollection.cs @@ -78,21 +78,11 @@ namespace Airbus } } /// - /// Метод записи информации в файл - /// - /// Строка, которую следует записать - /// Поток для записи - private static void WriteToFile(string text, FileStream stream) - { - byte[] info = new UTF8Encoding(true).GetBytes(text); - stream.Write(info, 0, info.Length); - } - /// /// Сохранение информации по самолетам в хранилище в файл /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -106,25 +96,24 @@ namespace Airbus sw.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 Exception("Файл не найден"); } using (StreamReader sr = new(filename)) { string str = ""; if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { - return false; + throw new Exception("Формат данных в файле не правильный"); } _mapStorages.Clear(); while ((str = sr.ReadLine()) != null) @@ -144,7 +133,6 @@ namespace Airbus _mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } - return true; } } } diff --git a/Airbus/Airbus/PlaneNotFoundException.cs b/Airbus/Airbus/PlaneNotFoundException.cs new file mode 100644 index 0000000..3aab506 --- /dev/null +++ b/Airbus/Airbus/PlaneNotFoundException.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 Airbus +{ + [Serializable] + internal class PlaneNotFoundException : ApplicationException + { + public PlaneNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public PlaneNotFoundException() : base() { } + public PlaneNotFoundException(string message) : base(message) { } + public PlaneNotFoundException(string message, Exception exception) : base(message, exception) { } + protected PlaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/Airbus/Airbus/SetPlanesGeneric.cs b/Airbus/Airbus/SetPlanesGeneric.cs index f1a02ba..9403758 100644 --- a/Airbus/Airbus/SetPlanesGeneric.cs +++ b/Airbus/Airbus/SetPlanesGeneric.cs @@ -51,12 +51,11 @@ namespace Airbus { // TODO проверка позиции // TODO вставка по позиции - if (position >= _maxCount || position < 0) + if (Count == _maxCount) { - return -1; + throw new StorageOverflowException(_maxCount); } - if (_places.Count + 1 >= _maxCount) - return -1; + if (position < 0 || position > _maxCount) return -1; _places.Insert(position, plane); return position; } @@ -71,7 +70,7 @@ namespace Airbus // TODO удаление объекта из массива, присовив элементу массива значение null if (position >= _maxCount || position < 0) { - return null; + throw new PlaneNotFoundException(position); } T DeletePlane = _places[position]; _places.RemoveAt(position); diff --git a/Airbus/Airbus/StorageOverflowException.cs b/Airbus/Airbus/StorageOverflowException.cs new file mode 100644 index 0000000..bdd1ec7 --- /dev/null +++ b/Airbus/Airbus/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 Airbus +{ + [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 70543c40c7e55774dee6459ae54b579a4186df15 Mon Sep 17 00:00:00 2001 From: ArtemEmelyanov Date: Fri, 25 Nov 2022 16:18:49 +0400 Subject: [PATCH 2/5] =?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.=20=D0=A1=D0=BE=D0=B1=D1=80=D0=B0?= =?UTF-8?q?=D0=BD=D0=BD=D0=B0=D1=8F=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Airbus/Airbus/Airbus.csproj | 17 +++++++++++++++++ Airbus/Airbus/FormMapWithSetPlanes.cs | 8 ++++++-- Airbus/Airbus/Program.cs | 19 ++++++++++++++++++- Airbus/Airbus/nlog.config | 13 +++++++++++++ 4 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 Airbus/Airbus/nlog.config diff --git a/Airbus/Airbus/Airbus.csproj b/Airbus/Airbus/Airbus.csproj index 13ee123..90645bb 100644 --- a/Airbus/Airbus/Airbus.csproj +++ b/Airbus/Airbus/Airbus.csproj @@ -8,6 +8,23 @@ enable + + + + + + + Always + + + + + + + + + + True diff --git a/Airbus/Airbus/FormMapWithSetPlanes.cs b/Airbus/Airbus/FormMapWithSetPlanes.cs index 71f8274..7b1afab 100644 --- a/Airbus/Airbus/FormMapWithSetPlanes.cs +++ b/Airbus/Airbus/FormMapWithSetPlanes.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -28,9 +29,11 @@ namespace Airbus /// /// Конструктор /// - public FormMapWithSetPlanes() + private readonly ILogger _logger; + public FormMapWithSetPlanes(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -78,6 +81,7 @@ namespace Airbus _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } /// /// Выбор карты diff --git a/Airbus/Airbus/Program.cs b/Airbus/Airbus/Program.cs index 5166800..b0ef970 100644 --- a/Airbus/Airbus/Program.cs +++ b/Airbus/Airbus/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + namespace Airbus { internal static class Program @@ -11,7 +15,20 @@ namespace Airbus // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetPlanes()); + 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/Airbus/Airbus/nlog.config b/Airbus/Airbus/nlog.config new file mode 100644 index 0000000..ce63bd2 --- /dev/null +++ b/Airbus/Airbus/nlog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file -- 2.25.1 From 39f7f8c79b504ca36231f83a163ba04c748cfabb Mon Sep 17 00:00:00 2001 From: ArtemEmelyanov Date: Sat, 26 Nov 2022 21:00:21 +0400 Subject: [PATCH 3/5] =?UTF-8?q?=D0=B2=D1=80=D0=BE=D0=B4=D0=B5=20=D0=BA?= =?UTF-8?q?=D0=B0=D0=BA=20=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Airbus/Airbus/Airbus.csproj | 13 ++------- Airbus/Airbus/FormMapWithSetPlanes.cs | 42 ++++++++++++++++++++------- Airbus/Airbus/MapsCollection.cs | 4 +-- Airbus/Airbus/Program.cs | 15 ++++++---- Airbus/Airbus/SetPlanesGeneric.cs | 7 +---- Airbus/Airbus/nlog.config | 13 --------- 6 files changed, 47 insertions(+), 47 deletions(-) delete mode 100644 Airbus/Airbus/nlog.config diff --git a/Airbus/Airbus/Airbus.csproj b/Airbus/Airbus/Airbus.csproj index 90645bb..66d2207 100644 --- a/Airbus/Airbus/Airbus.csproj +++ b/Airbus/Airbus/Airbus.csproj @@ -8,21 +8,14 @@ enable - - - - - - - Always - - - + + + diff --git a/Airbus/Airbus/FormMapWithSetPlanes.cs b/Airbus/Airbus/FormMapWithSetPlanes.cs index 7b1afab..abeb67b 100644 --- a/Airbus/Airbus/FormMapWithSetPlanes.cs +++ b/Airbus/Airbus/FormMapWithSetPlanes.cs @@ -71,11 +71,13 @@ namespace Airbus if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта"); return; } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, @@ -91,6 +93,7 @@ namespace Airbus private void listBoxMaps_SelectedIndexChanged_1(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } /// /// Удаление карты @@ -105,6 +108,7 @@ namespace Airbus } if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } @@ -118,25 +122,35 @@ namespace Airbus { var formPlaneConfig = new FormPlaneConfig(); formPlaneConfig.AddEvent(AddPlane); - // TODO formPlaneConfig.Show(); } private void AddPlane(DrawningPlane plane) { - if (listBoxMaps.SelectedIndex == -1) + try { - MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + if (listBoxMaps.SelectedIndex == -1) + { + MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + } + else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Plane}", plane); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Не удалось добавить объект"); + } } - else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -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); } + } /// /// Удаление объекта @@ -162,19 +176,23 @@ namespace Airbus if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) { MessageBox.Show("Объект удален"); + _logger.LogInformation("Из текущей карты удалён объект {@Plane}", _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); } else { + _logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos); MessageBox.Show("Не удалось удалить объект"); } } catch (PlaneNotFoundException ex) { + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); MessageBox.Show($"Ошибка удаления: {ex.Message}"); } catch (Exception ex) { + _logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message); MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } @@ -247,10 +265,12 @@ namespace Airbus try { _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { + _logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -264,11 +284,13 @@ namespace Airbus 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($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/Airbus/Airbus/MapsCollection.cs b/Airbus/Airbus/MapsCollection.cs index 4700bdb..dde5d2b 100644 --- a/Airbus/Airbus/MapsCollection.cs +++ b/Airbus/Airbus/MapsCollection.cs @@ -106,14 +106,14 @@ namespace Airbus { if (!File.Exists(filename)) { - throw new Exception("Файл не найден"); + throw new FileNotFoundException("Файл не найден"); } using (StreamReader sr = new(filename)) { string str = ""; if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { - throw new Exception("Формат данных в файле не правильный"); + throw new FileFormatException("Формат данных в файле не правильный"); } _mapStorages.Clear(); while ((str = sr.ReadLine()) != null) diff --git a/Airbus/Airbus/Program.cs b/Airbus/Airbus/Program.cs index b0ef970..ebce7f5 100644 --- a/Airbus/Airbus/Program.cs +++ b/Airbus/Airbus/Program.cs @@ -1,6 +1,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; +using Serilog; namespace Airbus { @@ -24,11 +24,14 @@ namespace Airbus } private static void ConfigureServices(ServiceCollection services) { - services.AddSingleton().AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); + var serilogLogger = new LoggerConfiguration().WriteTo.File("seriallog.txt").CreateLogger(); + + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger: serilogLogger, dispose: true); + }); } } } \ No newline at end of file diff --git a/Airbus/Airbus/SetPlanesGeneric.cs b/Airbus/Airbus/SetPlanesGeneric.cs index 9403758..1137d01 100644 --- a/Airbus/Airbus/SetPlanesGeneric.cs +++ b/Airbus/Airbus/SetPlanesGeneric.cs @@ -34,12 +34,7 @@ namespace Airbus /// public int Insert(T plane) { - // TODO вставка в начало набора - // TODO проверка на _maxCount - if (_places.Count + 1 >= _maxCount) - return -1; - _places.Insert(0, plane); - return 0; + return Insert(plane, 0); ; } /// /// Добавление объекта в набор на конкретную позицию diff --git a/Airbus/Airbus/nlog.config b/Airbus/Airbus/nlog.config deleted file mode 100644 index ce63bd2..0000000 --- a/Airbus/Airbus/nlog.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file -- 2.25.1 From 5fa1c4cdc34a7b9cddd17b6a67102a5837051600 Mon Sep 17 00:00:00 2001 From: ArtemEmelyanov Date: Wed, 30 Nov 2022 10:08:55 +0400 Subject: [PATCH 4/5] =?UTF-8?q?=D0=A1=D0=B4=D0=B0=D0=BD=D0=BD=D0=B0=D1=8F?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Airbus/Airbus/FormMapWithSetPlanes.cs | 2 +- Airbus/Airbus/MapWithSetPlanesGeneric.cs | 4 ---- Airbus/Airbus/SetPlanesGeneric.cs | 24 +++++++++++------------- Airbus/Airbus/serialogConfig.json | 17 +++++++++++++++++ 4 files changed, 29 insertions(+), 18 deletions(-) create mode 100644 Airbus/Airbus/serialogConfig.json diff --git a/Airbus/Airbus/FormMapWithSetPlanes.cs b/Airbus/Airbus/FormMapWithSetPlanes.cs index abeb67b..6b0c7bd 100644 --- a/Airbus/Airbus/FormMapWithSetPlanes.cs +++ b/Airbus/Airbus/FormMapWithSetPlanes.cs @@ -176,7 +176,7 @@ namespace Airbus if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) { MessageBox.Show("Объект удален"); - _logger.LogInformation("Из текущей карты удалён объект {@Plane}", _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos); + _logger.LogInformation("Из текущей карты удалён объект"); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); } else diff --git a/Airbus/Airbus/MapWithSetPlanesGeneric.cs b/Airbus/Airbus/MapWithSetPlanesGeneric.cs index c900b75..ebaf55b 100644 --- a/Airbus/Airbus/MapWithSetPlanesGeneric.cs +++ b/Airbus/Airbus/MapWithSetPlanesGeneric.cs @@ -169,8 +169,6 @@ namespace Airbus g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, (_pictureHeight / _placeSizeHeight) * _placeSizeHeight); } - - } /// /// Метод прорисовки объектов @@ -214,7 +212,5 @@ namespace Airbus _setPlanes.Insert(DrawningObjectPlane.Create(rec) as T); } } - } - } diff --git a/Airbus/Airbus/SetPlanesGeneric.cs b/Airbus/Airbus/SetPlanesGeneric.cs index 1137d01..4036acb 100644 --- a/Airbus/Airbus/SetPlanesGeneric.cs +++ b/Airbus/Airbus/SetPlanesGeneric.cs @@ -34,7 +34,9 @@ namespace Airbus /// public int Insert(T plane) { - return Insert(plane, 0); ; + if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); + _places.Insert(0, plane); + return 0; } /// /// Добавление объекта в набор на конкретную позицию @@ -46,11 +48,7 @@ namespace Airbus { // TODO проверка позиции // TODO вставка по позиции - if (Count == _maxCount) - { - throw new StorageOverflowException(_maxCount); - } - if (position < 0 || position > _maxCount) return -1; + if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); _places.Insert(position, plane); return position; } @@ -63,13 +61,13 @@ namespace Airbus { // TODO проверка позиции // TODO удаление объекта из массива, присовив элементу массива значение null - if (position >= _maxCount || position < 0) - { - throw new PlaneNotFoundException(position); - } - T DeletePlane = _places[position]; - _places.RemoveAt(position); - return DeletePlane; + if (position >= _maxCount || position >= _places.Count) throw new PlaneNotFoundException(position); + + T res = _places[position]; + _places.Remove(res); + + if (res == null) throw new PlaneNotFoundException(position); + return res; } /// /// Получение объекта из набора по позиции diff --git a/Airbus/Airbus/serialogConfig.json b/Airbus/Airbus/serialogConfig.json new file mode 100644 index 0000000..3bac7a9 --- /dev/null +++ b/Airbus/Airbus/serialogConfig.json @@ -0,0 +1,17 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "{Level:u4}: {Message:lj} [{Timestamp:HH:mm:ss.fff}]{NewLine}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ] + } +} -- 2.25.1 From 644ea73342e33d7e29a9e9bfe530a7dda8698472 Mon Sep 17 00:00:00 2001 From: ArtemEmelyanov Date: Fri, 9 Dec 2022 11:59:35 +0400 Subject: [PATCH 5/5] complete --- Airbus/Airbus/Airbus.csproj | 4 ++++ Airbus/Airbus/Program.cs | 21 ++++++++++++------- .../{serialogConfig.json => serilog.json} | 11 ++++++---- 3 files changed, 25 insertions(+), 11 deletions(-) rename Airbus/Airbus/{serialogConfig.json => serilog.json} (59%) diff --git a/Airbus/Airbus/Airbus.csproj b/Airbus/Airbus/Airbus.csproj index 66d2207..f8653ab 100644 --- a/Airbus/Airbus/Airbus.csproj +++ b/Airbus/Airbus/Airbus.csproj @@ -9,12 +9,16 @@ + + + + diff --git a/Airbus/Airbus/Program.cs b/Airbus/Airbus/Program.cs index ebce7f5..8494375 100644 --- a/Airbus/Airbus/Program.cs +++ b/Airbus/Airbus/Program.cs @@ -1,3 +1,4 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Serilog; @@ -24,14 +25,20 @@ namespace Airbus } private static void ConfigureServices(ServiceCollection services) { - var serilogLogger = new LoggerConfiguration().WriteTo.File("seriallog.txt").CreateLogger(); + services.AddSingleton().AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true) + .Build(); - services.AddSingleton() - .AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddSerilog(logger: serilogLogger, dispose: true); - }); + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); } } } \ No newline at end of file diff --git a/Airbus/Airbus/serialogConfig.json b/Airbus/Airbus/serilog.json similarity index 59% rename from Airbus/Airbus/serialogConfig.json rename to Airbus/Airbus/serilog.json index 3bac7a9..5dd3d1b 100644 --- a/Airbus/Airbus/serialogConfig.json +++ b/Airbus/Airbus/serilog.json @@ -6,12 +6,15 @@ { "Name": "File", "Args": { - "path": "Logs/log_.log", + "path": "log.log", "rollingInterval": "Day", - "outputTemplate": "{Level:u4}: {Message:lj} [{Timestamp:HH:mm:ss.fff}]{NewLine}" + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" } } ], - "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ] + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "ContainerShip" + } } -} +} \ No newline at end of file -- 2.25.1