From 3a7858e07a2f6e763f7906e3925b30fc8d680159 Mon Sep 17 00:00:00 2001 From: SAliulov <146759803+SAliulov@users.noreply.github.com> Date: Sun, 16 Jun 2024 23:00:17 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=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=20=D0=BD=D0=BE=D0=BC=D0=B5=D1=80=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 73 +++++++------- .../BomberHungarService.cs | 58 ++++++----- .../ListGenericObjects.cs | 18 ++-- .../MassiveGenericObjects.cs | 33 +++---- .../StorageCollection.cs | 34 ++++--- .../Exceptions/CollectionOverflowException.cs | 18 ++++ .../Exceptions/ObjectNotFoundException.cs | 17 ++++ .../PositionOutOfCollectionException.cs | 17 ++++ .../ProjectAirBomber/FormBomberCollection.cs | 96 ++++++++++++------- ProjectAirBomber/ProjectAirBomber/Program.cs | 36 ++++++- .../ProjectAirBomber/ProjectAirBomber.csproj | 20 ++++ .../ProjectAirBomber/serilogConfig.json | 20 ++++ 12 files changed, 302 insertions(+), 138 deletions(-) create mode 100644 ProjectAirBomber/ProjectAirBomber/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectAirBomber/ProjectAirBomber/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectAirBomber/ProjectAirBomber/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectAirBomber/ProjectAirBomber/serilogConfig.json diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs index d6b240f..f94729e 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectAirBomber.Drawnings; +using ProjectAirBomber.Exceptions; namespace ProjectAirBomber.CollectionGenericObjects; @@ -32,18 +33,18 @@ public abstract class AbstractCompany /// protected ICollectionGenericObjects? _collection = null; - /// - /// Вычисление максимального количества элементов, который можно разместить в окне - /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + /// + /// Вычисление максимального количества элементов, который можно разместить в окне + /// + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); - /// - /// Конструктор - /// - /// Ширина окна - /// Высота окна - /// Коллекция поездов - public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) + /// + /// Конструктор + /// + /// Ширина окна + /// Высота окна + /// Коллекция поездов + public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) { _pictureWidth = picWidth; _pictureHeight = picHeight; @@ -83,31 +84,37 @@ public abstract class AbstractCompany return _collection?.Get(rnd.Next(GetMaxCount)); } - /// - /// Вывод всей коллекции - /// - /// - public Bitmap? Show() - { - Bitmap bitmap = new(_pictureWidth, _pictureHeight); - Graphics graphics = Graphics.FromImage(bitmap); - DrawBackgound(graphics); + /// + /// Вывод всей коллекции + /// + /// + public Bitmap? Show() + { + Bitmap bitmap = new(_pictureWidth, _pictureHeight); + Graphics graphics = Graphics.FromImage(bitmap); + DrawBackgound(graphics); - SetObjectsPosition(); - for (int i = 0; i < (_collection?.Count ?? 0); ++i) - { - DrawningBomber? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); - } + SetObjectsPosition(); + for (int i = 0; i < (_collection?.Count ?? 0); ++i) + { + try + { + DrawningBomber? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException) + { - return bitmap; - } + } + } + return bitmap; + } - /// - /// Вывод заднего фона - /// - /// - protected abstract void DrawBackgound(Graphics g); + /// + /// Вывод заднего фона + /// + /// + protected abstract void DrawBackgound(Graphics g); /// /// Расстановка объектов diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/BomberHungarService.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/BomberHungarService.cs index 7625891..8136069 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/BomberHungarService.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/BomberHungarService.cs @@ -1,5 +1,6 @@ using ProjectAirBomber.Drawnings; using ProjectAirBomber.Entities; +using ProjectAirBomber.Exceptions; using System; namespace ProjectAirBomber.CollectionGenericObjects; @@ -9,56 +10,63 @@ namespace ProjectAirBomber.CollectionGenericObjects; /// public class BomberHungarService : AbstractCompany { - /// - /// Конструктор - /// - /// - /// - /// - public BomberHungarService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) + + /// + /// Конструктор + /// + /// + /// + /// + public BomberHungarService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) { } /// - /// Вывод заднего фона + /// Отрисовка хранилища /// - /// - /// + /// Графика + int pamat_i = 0; + int pamat_j = 0; protected override void DrawBackgound(Graphics g) { - Pen pen = new(Color.Black, 2); - for (int i = 0; i < _pictureWidth / _placeSizeWidth + 1; i++) + Pen pen = new(Color.Black, 4); + for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) { + pamat_i = i; for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) { + pamat_j = j; g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * j)); g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1))); } g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight))); } + + } - - - - - /// /// Установка объекта в Ангар /// protected override void SetObjectsPosition() { - int n = 0; - for (int i = _pictureWidth / _placeSizeWidth; i > 0; i--) + int currentIndex = 0; + for (int j = pamat_j; j >= 0; j--) { - for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) + for (int i = pamat_i; i >= 0; i--) { - DrawningBomber? drawningBomber = _collection?.Get(n); - n++; - if (drawningBomber != null) + try { - drawningBomber.SetPictureSize(_pictureWidth, _pictureHeight); - drawningBomber.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); + if (_collection?.Get(currentIndex) != null) + { + _collection.Get(currentIndex)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection.Get(currentIndex)?.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); + } } + catch (ObjectNotFoundException) + { + + } + currentIndex++; } } } diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs index e43b802..2f87eab 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectAirBomber.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -50,25 +51,26 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(); return _collection[position]; } public int Insert(T obj) { - if (Count + 1 > _maxCount) return -1; + if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - if (Count + 1 > _maxCount) return -1; - if (position < 0 || position > Count) return -1; + if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count); + if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); - return 1; + return position; } public T? Remove(int position) { - if (position < 0 || position > Count) return null; + if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position); T? temp = _collection[position]; _collection.RemoveAt(position); return temp; @@ -81,4 +83,4 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } -} +} \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs index d27fe74..814e124 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,6 +1,6 @@ using System.Runtime.Remoting; using ProjectAirBomber.Drawnings; - +using ProjectAirBomber.Exceptions; namespace ProjectAirBomber.CollectionGenericObjects; /// @@ -52,12 +52,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - - return null; + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); + return _collection[position]; } public int Insert(T obj) @@ -72,20 +69,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { // проверка позиции - if (position < 0 || position >= Count) - { - return -1; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); // проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до + // ищется свободное место после этой позиции и идет вставка туда + // если нет после, ищем до if (_collection[position] != null) { bool pushed = false; @@ -114,7 +108,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (!pushed) { - return position; + throw new CollectionOverflowException(Count); } } @@ -123,21 +117,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects return position; } + public T? Remove(int position) { // проверка позиции - if (position < 0 || position >= Count) - { - return null; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) return null; + if (_collection[position] == null) throw new ObjectNotFoundException(position); T? temp = _collection[position]; _collection[position] = null; return temp; } - public IEnumerable GetItems() { for (int i = 0; i < _collection.Length; ++i) diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs index a4b3ee7..508fe55 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,6 @@ using ProjectAirBomber.Drawnings; +using ProjectAirBomber.Exceptions; +using System.Data; using System.Text; namespace ProjectAirBomber.CollectionGenericObjects; @@ -88,12 +90,11 @@ public class StorageCollection /// Сохранение информации по самолётам в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -133,21 +134,18 @@ public class StorageCollection } writer.Write(sb); } - } - return true; } /// /// Загрузка информации по самолётам в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException($"{filename} не существует"); } using (StreamReader fs = File.OpenText(filename)) @@ -155,11 +153,11 @@ public class StorageCollection string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new FileFormatException("Файл не подходит"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new IOException("В файле неверные данные"); } _storages.Clear(); string strs = ""; @@ -174,7 +172,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -182,15 +180,21 @@ public class StorageCollection { if (elem?.CreateDrawningBomber() is T bomber) { - if (collection.Insert(bomber) == -1) + try { - return false; + if (collection.Insert(bomber) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new DataException("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } - return true; } } @@ -208,4 +212,4 @@ public class StorageCollection _ => null, }; } -} +} \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/Exceptions/CollectionOverflowException.cs b/ProjectAirBomber/ProjectAirBomber/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..4c4162d --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,18 @@ + +using System.Runtime.Serialization; + + +namespace ProjectAirBomber.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) { } +} + diff --git a/ProjectAirBomber/ProjectAirBomber/Exceptions/ObjectNotFoundException.cs b/ProjectAirBomber/ProjectAirBomber/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..098a3be --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,17 @@ + +using System.Runtime.Serialization; + + +namespace ProjectAirBomber.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) { } +} diff --git a/ProjectAirBomber/ProjectAirBomber/Exceptions/PositionOutOfCollectionException.cs b/ProjectAirBomber/ProjectAirBomber/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..2afd4b5 --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,17 @@ + +using System.Runtime.Serialization; + + +namespace ProjectAirBomber.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/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs index 9fbf2de..5d279c5 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs @@ -1,5 +1,7 @@ -using ProjectAirBomber.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectAirBomber.CollectionGenericObjects; using ProjectAirBomber.Drawnings; +using ProjectAirBomber.Exceptions; using System; using System.Collections.Generic; using System.ComponentModel; @@ -29,15 +31,22 @@ public partial class FormBomberCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormBomberCollection() + public FormBomberCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } + /// /// Выбор компании /// @@ -71,14 +80,17 @@ public partial class FormBomberCollection : Form return; } - if (_company + bomber != -1) + try { + int addingObject = (_company + bomber); MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект {bomber.GetDataForSave()}"); pictureBox.Image = _company.Show(); } - else + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError($"Не удалось добавить объект: {ex.Message}"); } } @@ -92,6 +104,7 @@ public partial class FormBomberCollection : Form { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { + _logger.LogError("Удаление объекта из несуществующей коллекции"); return; } @@ -101,14 +114,22 @@ public partial class FormBomberCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { + object decrementObject = _company - pos; MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект по позиции {pos}"); pictureBox.Image = _company.Show(); } - else + catch (ObjectNotFoundException) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Объект не найден"); + _logger.LogError($"Удаление не найденного объекта в позиции {pos} "); + } + catch (PositionOutOfCollectionException) + { + MessageBox.Show("Удаление вне рамках коллекции"); + _logger.LogError($"Удаление объекта за пределами коллекции {pos} "); } } @@ -124,28 +145,33 @@ public partial class FormBomberCollection : Form return; } - DrawningBomber? bomber = null; - int counter = 100; - while (bomber == null) + try { - bomber = _company.GetRandomObject(); - counter--; - if (counter <= 0) + DrawningBomber? bomber = null; + int counter = 100; + while (bomber == null) { - break; + bomber = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + if (bomber == null) + { + return; + } + FormAirBomber form = new() + { + SetBomber = bomber + }; + form.ShowDialog(); } - - if (bomber == null) + catch (ObjectNotFoundException) { - return; + _logger.LogError("Ошибка при передаче объекта на FormAirFighter"); } - - FormAirBomber form = new() - { - SetBomber = bomber - }; - form.ShowDialog(); } /// @@ -226,6 +252,7 @@ public partial class FormBomberCollection : Form } } } + /// /// Создание компании /// @@ -264,17 +291,21 @@ public partial class FormBomberCollection : 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); } } } + /// /// Обработка нажатия "Загрузка" /// @@ -284,16 +315,17 @@ public partial class FormBomberCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storageCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); RerfreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectAirBomber/ProjectAirBomber/Program.cs b/ProjectAirBomber/ProjectAirBomber/Program.cs index 0a98864..29a8e14 100644 --- a/ProjectAirBomber/ProjectAirBomber/Program.cs +++ b/ProjectAirBomber/ProjectAirBomber/Program.cs @@ -1,17 +1,45 @@ + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Serilog; +using Microsoft.Extensions.Logging; + namespace ProjectAirBomber { internal static class Program { - /// - /// The main entry point for the application. - /// [STAThread] static void Main() { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormBomberCollection()); + 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 => + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: $"{pathNeed}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/ProjectAirBomber/ProjectAirBomber/ProjectAirBomber.csproj b/ProjectAirBomber/ProjectAirBomber/ProjectAirBomber.csproj index 244387d..228b2c7 100644 --- a/ProjectAirBomber/ProjectAirBomber/ProjectAirBomber.csproj +++ b/ProjectAirBomber/ProjectAirBomber/ProjectAirBomber.csproj @@ -8,6 +8,20 @@ enable + + + + + + + + + + + + + + True @@ -23,4 +37,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/serilogConfig.json b/ProjectAirBomber/ProjectAirBomber/serilogConfig.json new file mode 100644 index 0000000..a604a73 --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/serilogConfig.json @@ -0,0 +1,20 @@ +{ + "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}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "AirBomber" + } + } +} \ No newline at end of file -- 2.25.1