From bf12e1a9bf7a21aa062bf5f99c6577b31574a1cd Mon Sep 17 00:00:00 2001 From: ShuryginDima Date: Mon, 20 May 2024 14:06:46 +0300 Subject: [PATCH] =?UTF-8?q?7=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 12 +++- .../ListGenericObjects.cs | 35 ++++++---- .../MassiveGenericObjects.cs | 23 +++---- .../PlaneSharingService.cs | 20 ++++-- .../StorageCollection.cs | 37 +++++++---- .../Exceptions/CollectionOverflowException.cs | 16 +++++ .../Exceptions/FileHasWrongDataException.cs | 19 ++++++ .../Exceptions/FileIsEmptyException.cs | 19 ++++++ .../Exceptions/NoCollectionException.cs | 15 +++++ .../Exceptions/NullCollectionException.cs | 15 +++++ .../Exceptions/ObjectNotFoundException.cs | 22 +++++++ .../PositionOutOfCollectionException.cs | 16 +++++ .../ProjectSeaplane/FormPlaneCollection.cs | 65 +++++++++++++------ ProjectSeaplane/ProjectSeaplane/Program.cs | 34 +++++++++- .../ProjectSeaplane/ProjectSeaplane.csproj | 18 +++++ ProjectSeaplane/ProjectSeaplane/Settings.json | 16 +++++ ProjectSeaplane/ProjectSeaplane/nlog.config | 15 +++++ 17 files changed, 332 insertions(+), 65 deletions(-) create mode 100644 ProjectSeaplane/ProjectSeaplane/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectSeaplane/ProjectSeaplane/Exceptions/FileHasWrongDataException.cs create mode 100644 ProjectSeaplane/ProjectSeaplane/Exceptions/FileIsEmptyException.cs create mode 100644 ProjectSeaplane/ProjectSeaplane/Exceptions/NoCollectionException.cs create mode 100644 ProjectSeaplane/ProjectSeaplane/Exceptions/NullCollectionException.cs create mode 100644 ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectSeaplane/ProjectSeaplane/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectSeaplane/ProjectSeaplane/Settings.json create mode 100644 ProjectSeaplane/ProjectSeaplane/nlog.config diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs index f4f0aac..ccc56d8 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectSeaplane.Drawnings; +using ProjectSeaplane.Exceptions; namespace ProjectSeaplane.CollectionGenericObjects; @@ -104,8 +105,15 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningPlane? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningPlane? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (Exception) + { + continue; + } } return bitmap; } diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs index 57b551a..54ccb31 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectSeaplane.CollectionGenericObjects; +using ProjectSeaplane.Exceptions; + +namespace ProjectSeaplane.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -42,11 +44,15 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - if (position < 0 || position > _collection.Count) + try { - return null; + if (_collection[position] == null) throw new ObjectNotFoundException(position); + return _collection[position]; + } + catch (IndexOutOfRangeException) + { + throw new PositionOutOfCollectionException(position); } - return _collection[position]; } public int Insert(T obj) { @@ -54,22 +60,25 @@ public class ListGenericObjects : ICollectionGenericObjects } public int Insert(T obj, int position) { - if (_maxCount == _collection.Count || position < 0 || position > _collection.Count) - { - return -1; - } + if (position > MaxCount) throw new CollectionOverflowException(position); + + if (obj == null) throw new ArgumentNullException(nameof(obj)); + _collection.Insert(position, obj); return _collection.Count; } public T? Remove(int position) { - if (position < 0 || position > _collection.Count) + try { - return null; + T obj = _collection[position]; + _collection.RemoveAt(position); + return obj; + } + catch (IndexOutOfRangeException) + { + throw new PositionOutOfCollectionException(position); } - T obj = _collection[position]; - _collection.RemoveAt(position); - return obj; } public IEnumerable GetItems() diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs index ccedd1b..ca763ee 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ using ProjectSeaplane.Drawnings; +using ProjectSeaplane.Exceptions; namespace ProjectSeaplane.CollectionGenericObjects; @@ -51,13 +52,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) + try { + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } - else + catch (IndexOutOfRangeException) { - return null; + throw new PositionOutOfCollectionException(position); } } @@ -94,23 +96,22 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - if (position < 0 || position >= _collection.Count()) - { - return null; - } - if (_collection[position] != null) + try { T obj = _collection[position]; + if (obj == null) throw new ObjectNotFoundException(position); _collection[position] = null; return obj; - } - return null; + catch (IndexOutOfRangeException) + { + throw new PositionOutOfCollectionException(position); + } } public IEnumerable GetItems() diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/PlaneSharingService.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/PlaneSharingService.cs index 6e80060..7b8d701 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/PlaneSharingService.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/PlaneSharingService.cs @@ -24,6 +24,7 @@ public class PlaneSharingService : AbstractCompany protected override void DrawBackgound(Graphics g) { Pen pen = new Pen(Color.Brown); + int max_count = 0; int x = 1, y = 0; while (y + _placeSizeHeight <= _pictureHeight) { @@ -31,6 +32,7 @@ public class PlaneSharingService : AbstractCompany while (x + _placeSizeWidth <= _pictureWidth) { count++; + max_count++; g.DrawLine(pen, x, y, x + _placeSizeWidth, y); g.DrawLine(pen, x, y, x, y + _placeSizeHeight); g.DrawLine(pen, x, y + _placeSizeHeight, x + _placeSizeWidth, y + _placeSizeHeight); @@ -43,6 +45,7 @@ public class PlaneSharingService : AbstractCompany y += _placeSizeHeight + 5; countRow++; } + _collection.MaxCount = max_count; } protected override void SetObjectsPosition() @@ -54,12 +57,19 @@ public class PlaneSharingService : AbstractCompany int row = countRow, col = 1; for (int i = 0; i < _collection?.Count; i++, col++) { - _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(i)?.SetPosition(locCoord[row * countInRow - col].Item1 + 5, locCoord[row * countInRow - col].Item2 + 5); - if (col == countInRow) + try { - col = 0; - row--; + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(locCoord[row * countInRow - col].Item1 + 5, locCoord[row * countInRow - col].Item2 + 5); + if (col == countInRow) + { + col = 0; + row--; + } + } + catch (Exception) + { + continue; } } } diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs index f8fc453..71482df 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using ProjectSeaplane.Drawnings; using System.Text; +using ProjectSeaplane.Exceptions; namespace ProjectSeaplane.CollectionGenericObjects; @@ -105,8 +106,7 @@ public class StorageCollection /// Сохранение информации по самолётам в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -115,7 +115,7 @@ public class StorageCollection if (_storage.Count == 0) { - return false; + throw new NoCollectionException("В хранилище отсутствуют коллекции для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) @@ -133,26 +133,31 @@ public class StorageCollection writer.Write(data + _separatorItems); } } - writer.WriteLine(); } + writer.WriteLine(); } - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { - if (!File.Exists(filename)) return false; + if (!File.Exists(filename)) + { + throw new FileNotFoundException("Файл не существует"); + } using (StreamReader reader = new StreamReader(filename)) { string line = reader.ReadLine(); - if (line == null || !line.Equals(_collectionKey)) + if (line == null) { - return false; + throw new FileIsEmptyException(filename); + } + if (!line.Equals(_collectionKey)) + { + throw new FileHasWrongDataException(filename); } _storage.Clear(); @@ -169,7 +174,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new NullCollectionException("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -179,17 +184,21 @@ public class StorageCollection { if (elem?.CreateDrawningPlane() is T plane) { - if (collection.Insert(plane) == -1) + try { - return false; + collection.Insert(plane); } + catch (Exception ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } + } } _storage.Add(record[0], collection); line = reader.ReadLine(); } } - return true; } /// diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/CollectionOverflowException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..7a92552 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectSeaplane.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/FileHasWrongDataException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/FileHasWrongDataException.cs new file mode 100644 index 0000000..7fb497c --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/FileHasWrongDataException.cs @@ -0,0 +1,19 @@ +using System.Runtime.Serialization; + +namespace ProjectSeaplane.Exceptions; + +/// +/// Класс, описывающий переполнение коллекции +/// +[Serializable] + +internal class FileHasWrongDataException : ApplicationException +{ + public FileHasWrongDataException() : base() { } + + public FileHasWrongDataException(string message) : base("Файл имеет неверные данные: " + message) { } + + public FileHasWrongDataException(string message, Exception exception) : base(message, exception) { } + + public FileHasWrongDataException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/FileIsEmptyException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/FileIsEmptyException.cs new file mode 100644 index 0000000..1cd450c --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/FileIsEmptyException.cs @@ -0,0 +1,19 @@ +using System.Runtime.Serialization; + +namespace ProjectSeaplane.Exceptions; + +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[Serializable] +internal class FileIsEmptyException : ApplicationException +{ + + public FileIsEmptyException() : base() { } + + public FileIsEmptyException(string message) : base("Файл пустой: " + message) { } + + public FileIsEmptyException(string message, Exception exception) : base(message, exception) { } + + public FileIsEmptyException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/NoCollectionException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/NoCollectionException.cs new file mode 100644 index 0000000..23426a1 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/NoCollectionException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; + +namespace ProjectSeaplane.Exceptions; + +[Serializable] +internal class NoCollectionException : ApplicationException +{ + public NoCollectionException() : base() { } + + public NoCollectionException(string message) : base(message) { } + + public NoCollectionException(string message, Exception exception) : base(message, exception) { } + + public NoCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/NullCollectionException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/NullCollectionException.cs new file mode 100644 index 0000000..27d1a79 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/NullCollectionException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; + +namespace ProjectSeaplane.Exceptions; + +[Serializable] +internal class NullCollectionException : ApplicationException +{ + public NullCollectionException() : base() { } + + public NullCollectionException(string message) : base(message) { } + + public NullCollectionException(string message, Exception exception) : base(message, exception) { } + + public NullCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotFoundException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..4b9f518 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,22 @@ +using Microsoft.VisualBasic.ApplicationServices; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectSeaplane.Exceptions; + +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/PositionOutOfCollectionException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..35fe735 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectSeaplane.Exceptions; + +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs index 9c45682..4bae1ed 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs @@ -1,4 +1,6 @@ -using ProjectSeaplane.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using System.Security.Cryptography; +using ProjectSeaplane.CollectionGenericObjects; using ProjectSeaplane.Drawnings; namespace ProjectSeaplane; @@ -18,13 +20,19 @@ public partial class FormPlaneCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormPlaneCollection() + public FormPlaneCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -53,21 +61,25 @@ public partial class FormPlaneCollection : Form /// Добавление самолёта в коллекцию /// /// - private void SetPlane(DrawningPlane? plane) + private void SetPlane(DrawningPlane plane) { - if (_company == null || plane == null) + if (_company == null) { return; } - - if ((_company + plane) != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if ((_company + plane) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект: {entity}", plane.GetDataForSave()); + pictureBox.Image = _company.Show(); + } } - else + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show("Объект не был добавлен"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -89,14 +101,17 @@ public partial class FormPlaneCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if ((_company - pos) != null) + try { + DrawningPlane plane = _company - pos; + _logger.LogInformation("Объект по позиции {pos} удаден", pos); MessageBox.Show("Объект удален"); pictureBox.Image = _company.Show(); } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -174,6 +189,8 @@ public partial class FormPlaneCollection : Form } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RefreshListBoxItems(); + + _logger.LogInformation("Добавлена коллекция: {CollectionName} типа: {Type}", textBoxCollectionName.Text, collectionType); } /// @@ -192,6 +209,7 @@ public partial class FormPlaneCollection : Form { return; } + _logger.LogInformation("Коллекция успешно удалена: {collectionName}", listBoxCollection.SelectedIndex.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString() ?? string.Empty); RefreshListBoxItems(); } @@ -230,6 +248,7 @@ public partial class FormPlaneCollection : Form if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); + _logger.LogInformation("Коллекция не проиннициализирована"); return; } @@ -237,8 +256,10 @@ public partial class FormPlaneCollection : Form { case "Хранилище": _company = new PlaneSharingService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Создана компания типа плейншейринг, коллекция: {CollectionName}", listBoxCollection.SelectedItem); break; } + _logger.LogInformation("Создана компания на коллекции : {CollectionName}", listBoxCollection.SelectedItem); panelCompanyTools.Enabled = true; RefreshListBoxItems(); } @@ -252,13 +273,16 @@ public partial class FormPlaneCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -272,15 +296,18 @@ public partial class FormPlaneCollection : Form { if (loadFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(loadFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - RefreshListBoxItems(); + _storageCollection.LoadData(loadFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка прошла успешно из файла, {filename}", loadFileDialog.FileName); } - else + catch(Exception ex) { MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка {Message}", ex.Message); } + RefreshListBoxItems(); } } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Program.cs b/ProjectSeaplane/ProjectSeaplane/Program.cs index 0b08fb7..4984552 100644 --- a/ProjectSeaplane/ProjectSeaplane/Program.cs +++ b/ProjectSeaplane/ProjectSeaplane/Program.cs @@ -1,3 +1,11 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Events; +using Serilog.Sinks.File; +using Serilog.Configuration; +using Microsoft.Extensions.Configuration; + namespace ProjectSeaplane { internal static class Program @@ -11,7 +19,31 @@ namespace ProjectSeaplane // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormPlaneCollection()); + + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); } + + /// + /// DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("Settings.json") + .Build(); + services.AddSingleton() + .AddLogging(builder => + { + builder.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger()); + }); + } + } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj b/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj index 244387d..8f5cda0 100644 --- a/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj +++ b/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True @@ -23,4 +35,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Settings.json b/ProjectSeaplane/ProjectSeaplane/Settings.json new file mode 100644 index 0000000..94d4cea --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Settings.json @@ -0,0 +1,16 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/planeLog.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ] + } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/nlog.config b/ProjectSeaplane/ProjectSeaplane/nlog.config new file mode 100644 index 0000000..6839c03 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file