From 48eac5dc3a7e947fe3c171f58a349a514956f1dd Mon Sep 17 00:00:00 2001 From: BoiledMilk123 Date: Mon, 20 May 2024 21:12:31 +0400 Subject: [PATCH] labwok07 --- .../AbstractCompany.cs | 11 +++- .../ListGenericObjects.cs | 41 +++++++------ .../LocomotiveDepot.cs | 7 ++- .../MassiveGenericObjects.cs | 33 ++++++---- .../StorageCollection.cs | 32 +++++----- .../Exceptions/CollectionOwerflowException.cs | 25 ++++++++ .../Exceptions/FileHasWrongDataExpextion.cs | 23 +++++++ .../Exceptions/FileIsEmptyException.cs | 24 ++++++++ .../Exceptions/NoCollectionExpection.cs | 20 +++++++ .../Exceptions/NullCollectionExpection.cs | 20 +++++++ .../Exceptions/ObjectNotFoundException.cs | 25 ++++++++ .../PositionOutOfCollectionException.cs | 25 ++++++++ .../FormLocomotiveCollection.cs | 60 ++++++++++++++----- .../ProjectElectricLocomotive/Program.cs | 31 +++++++++- .../ProjectElectricLocomotive.csproj | 24 ++++++++ .../ProjectElectricLocomotive/Settings.json | 16 +++++ 16 files changed, 356 insertions(+), 61 deletions(-) create mode 100644 ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/CollectionOwerflowException.cs create mode 100644 ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/FileHasWrongDataExpextion.cs create mode 100644 ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/FileIsEmptyException.cs create mode 100644 ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/NoCollectionExpection.cs create mode 100644 ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/NullCollectionExpection.cs create mode 100644 ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectElectricLocomotive/ProjectElectricLocomotive/Settings.json diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs index 20c3f40..e64da79 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs @@ -97,8 +97,15 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningLocomotive? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningLocomotive? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch(Exception) + { + continue; + } } return bitmap; } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs index 325c0bb..0af16a8 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectElectricLocomotive.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -48,17 +49,21 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { // проверка позиции - if (position >= Count || position < 0) + 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) { - if (Count == _maxCount) return -1; + if (Count == _maxCount) throw new CollectionOwerflowException(Count); _collection.Add(obj); return Count; } @@ -69,14 +74,10 @@ public class ListGenericObjects : ICollectionGenericObjects // проверка позиции // вставка по позиции - if (position >= Count || position < 0) - { - return -1; - } - if (Count == _maxCount) - { - return -1; - } + if (position > MaxCount) throw new CollectionOwerflowException(position); + + if (obj == null) throw new ArgumentNullException(nameof(obj)); + _collection.Insert(position, obj); return position; @@ -86,10 +87,16 @@ public class ListGenericObjects : ICollectionGenericObjects { // проверка позиции // удаление объекта из списка - if (position >= Count || position < 0) return null; - T obj = _collection[position]; - _collection.RemoveAt(position); - return obj; + try + { + T obj = _collection[position]; + _collection.RemoveAt(position); + return obj; + } + catch (IndexOutOfRangeException) + { + throw new PositionOutOfCollectionException(position); + } } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/LocomotiveDepot.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/LocomotiveDepot.cs index f6e9926..1d245ab 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/LocomotiveDepot.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/LocomotiveDepot.cs @@ -47,17 +47,20 @@ public class LocomotiveDepot : AbstractCompany { for (int i = 0; i < (_collection?.Count); i++) { - if (_collection.Get(i) != null) + try { _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i)?.SetPosition(_placeSizeWidth * positionWidth + 25, positionHeight * _placeSizeHeight + 10); } + catch(Exception) + { + + } if (positionWidth < width - 1) { positionWidth++; } - else { positionWidth = 0; diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs index 0f1f62d..c09300d 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectElectricLocomotive.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -55,11 +56,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { // проверка позиции - if (position >= Count || position < 0) + 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) { @@ -72,7 +77,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; + throw new CollectionOwerflowException(Count); } @@ -112,7 +117,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } - return -1; + throw new CollectionOwerflowException(Count); } public T? Remove(int position) @@ -120,10 +125,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects //// проверка позиции //// удаление объекта из массива, присвоив элементу массива значение null - if (position >= Count || position < 0 || _collection[position] == null) return null; - T removedObject = _collection[position]; - _collection[position] = null; - return removedObject; + try + { + T removedObject = _collection[position]; + if (removedObject == null) throw new ObjectNotFoundException(position); + _collection[position] = null; + return removedObject; + } + catch (IndexOutOfRangeException) + { + throw new PositionOutOfCollectionException(position); + } + } public IEnumerable GetItems() diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs index 90c3e24..b9d1c06 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectElectricLocomotive.Drawnings; +using ProjectElectricLocomotive.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -100,15 +101,14 @@ public class StorageCollection /// Сохранение информации по автомобилям в хранилице в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } - if (_storages.Count == 0) return false; + if (_storages.Count == 0) throw new NoCollectionExpection("В хранилище отсутствуют коллекции для сохранения"); using (StreamWriter writer = new StreamWriter(filename)) { @@ -129,25 +129,27 @@ public class StorageCollection 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("В файле нет данных"); + } + if (!line.Equals(_collectionKey)) + { + throw new FileHasWrongDataExpextion("В файле неверные данные"); } _storages.Clear(); @@ -166,7 +168,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) return false; + if (collection == null) throw new NullCollectionExpection("Не удалось создать коллекцию"); ; collection.MaxCount = Convert.ToInt32(record[2]); @@ -176,9 +178,13 @@ public class StorageCollection { if (elem?.CreateDrawningLocomotive() is T locomotive) { - if (collection.Insert(locomotive) == -1) + try { - return false; + collection.Insert(locomotive); + } + catch(Exception ex) + { + throw new CollectionOwerflowException("Коллекция переполнена", ex); } } } @@ -187,8 +193,6 @@ public class StorageCollection line = reader.ReadLine(); } } - - return true; } /// diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/CollectionOwerflowException.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/CollectionOwerflowException.cs new file mode 100644 index 0000000..a0fe931 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/CollectionOwerflowException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions; + +/// +/// Класс, описывающий переполнение коллекции +/// +[Serializable] +internal class CollectionOwerflowException : ApplicationException +{ + public CollectionOwerflowException(int count) : base("В коллекции превышено допустимое количество: count " + count) { } + + public CollectionOwerflowException() : base() { } + + public CollectionOwerflowException(string message) : base(message) { } + + public CollectionOwerflowException(string message, Exception exception) : base(message, exception) { } + + public CollectionOwerflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/FileHasWrongDataExpextion.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/FileHasWrongDataExpextion.cs new file mode 100644 index 0000000..d4ecc7e --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/FileHasWrongDataExpextion.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions; + +/// +/// Класс, описывающий переполнение коллекции +/// +[Serializable] +internal class FileHasWrongDataExpextion : ApplicationException +{ + public FileHasWrongDataExpextion() : base() { } + + public FileHasWrongDataExpextion(string message) : base("Файл имеет неверные данные: " + message) { } + + public FileHasWrongDataExpextion(string message, Exception exception) : base(message, exception) { } + + public FileHasWrongDataExpextion(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/FileIsEmptyException.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/FileIsEmptyException.cs new file mode 100644 index 0000000..739fb7e --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/FileIsEmptyException.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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) { } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/NoCollectionExpection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/NoCollectionExpection.cs new file mode 100644 index 0000000..d71f65e --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/NoCollectionExpection.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions; + +[Serializable] +internal class NoCollectionExpection : ApplicationException +{ + public NoCollectionExpection() : base() { } + + public NoCollectionExpection(string message) : base(message) { } + + public NoCollectionExpection(string message, Exception exception) : base(message, exception) { } + + public NoCollectionExpection(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/NullCollectionExpection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/NullCollectionExpection.cs new file mode 100644 index 0000000..6f8bd94 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/NullCollectionExpection.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions; + +[Serializable] +internal class NullCollectionExpection : ApplicationException +{ + public NullCollectionExpection() : base() { } + + public NullCollectionExpection(string message) : base(message) { } + + public NullCollectionExpection(string message, Exception exception) : base(message, exception) { } + + public NullCollectionExpection(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/ObjectNotFoundException.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..0498603 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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) { } + + public ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/PositionOutOfCollectionException.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..77fea7a --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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) { } + + public PositionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs index 19b6768..5fc3458 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs @@ -1,4 +1,5 @@ -using ProjectElectricLocomotive.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectElectricLocomotive.CollectionGenericObjects; using ProjectElectricLocomotive.Drawnings; using System; using System.Collections.Generic; @@ -25,13 +26,19 @@ public partial class FormLocomotiveCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логгер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormLocomotiveCollection() + public FormLocomotiveCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -67,15 +74,23 @@ public partial class FormLocomotiveCollection : Form return; } - if (_company + locomotive != -1) + if (_company == null) return; + + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if((_company + locomotive) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект: {entity}", locomotive.GetDataForSave()); + pictureBox.Image = _company.Show(); + } } - else + catch(Exception ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show("Объект не был добавлен"); + _logger.LogError("Ошибка: {Message}", ex.Message); } + } @@ -95,14 +110,17 @@ public partial class FormLocomotiveCollection : Form return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { + DrawningLocomotive locomotive = _company - pos; + _logger.LogInformation("Объект по позиции {pos} удаден", pos); MessageBox.Show("Объект удален"); pictureBox.Image = _company.Show(); } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -178,6 +196,8 @@ public partial class FormLocomotiveCollection : Form _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RefreshListBoxItems(); + + _logger.LogInformation("Добавлена коллекция: {CollectionName} типа: {Type}", textBoxCollectionName.Text, collectionType); } /// @@ -197,6 +217,7 @@ public partial class FormLocomotiveCollection : Form return; } if (MessageBox.Show("Вы хотите удалить коллекцию?", "Коллекция удалена", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; + _logger.LogInformation("Коллекция успешно удалена: {collectionName}", listBoxCollection.SelectedIndex.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString() ?? string.Empty); RefreshListBoxItems(); } @@ -233,14 +254,17 @@ public partial class FormLocomotiveCollection : Form if (collection == null) { MessageBox.Show("Коллекция не проиннициализирована"); + _logger.LogInformation("Коллекция не проиннициализирована"); return; } switch (comboBoxSelectorCompany.Text) { case "Хранилище": _company = new LocomotiveDepot(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Создана компания типа депо, коллекция: {CollectionName}", listBoxCollection.SelectedItem); break; } + _logger.LogInformation("Создана компания на коллекции : {CollectionName}", listBoxCollection.SelectedItem); panelCompanyTools.Enabled = true; RefreshListBoxItems(); } @@ -254,13 +278,16 @@ public partial class FormLocomotiveCollection : 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); } } } @@ -274,15 +301,18 @@ public partial class FormLocomotiveCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - RefreshListBoxItems(); + _logger.LogInformation("Загрузка прошла успешно из файла, {filename}", openFileDialog.FileName); } - else + catch(Exception ex) { MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка {Message}", ex.Message); } + RefreshListBoxItems(); } } } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Program.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Program.cs index 5def1ba..a9f2e2c 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/Program.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Program.cs @@ -1,3 +1,12 @@ +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 ProjectElectricLocomotive { internal static class Program @@ -11,7 +20,27 @@ namespace ProjectElectricLocomotive // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormLocomotiveCollection()); + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + + 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/ProjectElectricLocomotive/ProjectElectricLocomotive/ProjectElectricLocomotive.csproj b/ProjectElectricLocomotive/ProjectElectricLocomotive/ProjectElectricLocomotive.csproj index 244387d..632a495 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/ProjectElectricLocomotive.csproj +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/ProjectElectricLocomotive.csproj @@ -8,6 +8,24 @@ enable + + + + + + + + + + + + + + + + + + True @@ -23,4 +41,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Settings.json b/ProjectElectricLocomotive/ProjectElectricLocomotive/Settings.json new file mode 100644 index 0000000..bd6231e --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Settings.json @@ -0,0 +1,16 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/locomotiveLog.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ] + } +} \ No newline at end of file -- 2.25.1