diff --git a/Monorail/Monorail/CollectionGenericObjects/AbstractCompany.cs b/Monorail/Monorail/CollectionGenericObjects/AbstractCompany.cs index ddb9b9f..8867108 100644 --- a/Monorail/Monorail/CollectionGenericObjects/AbstractCompany.cs +++ b/Monorail/Monorail/CollectionGenericObjects/AbstractCompany.cs @@ -40,7 +40,9 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + //private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); + //private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор @@ -53,7 +55,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.MaxCount = GetMaxCount; + collection.MaxCount = GetMaxCount; } /// @@ -75,7 +77,7 @@ public abstract class AbstractCompany /// public static DrawningLocomotive operator -(AbstractCompany company, int position) { - return company._collection?.Remove(position); + return company._collection.Remove(position); } /// @@ -97,14 +99,16 @@ public abstract class AbstractCompany Bitmap bitmap = new(_pictureWidth, _pictureHeight); Graphics graphics = Graphics.FromImage(bitmap); DrawBackgound(graphics); - 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) { } } - return bitmap; } diff --git a/Monorail/Monorail/CollectionGenericObjects/ICollectionGenericObjects.cs b/Monorail/Monorail/CollectionGenericObjects/ICollectionGenericObjects.cs index feec3bb..7507321 100644 --- a/Monorail/Monorail/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Monorail/Monorail/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -39,7 +39,7 @@ public interface ICollectionGenericObjects /// /// Позиция /// true - удаление прошло удачно, false - удаление не удалось - T Remove(int position); + T? Remove(int position); /// /// Получение объекта по позиции diff --git a/Monorail/Monorail/CollectionGenericObjects/ListGenericObjects.cs b/Monorail/Monorail/CollectionGenericObjects/ListGenericObjects.cs index 52e6019..f911cb2 100644 --- a/Monorail/Monorail/CollectionGenericObjects/ListGenericObjects.cs +++ b/Monorail/Monorail/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using Monorail.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -30,7 +31,10 @@ public class ListGenericObjects : ICollectionGenericObjects public int MaxCount { - get => _maxCount; + get + { + return Count; + } set { if (value > 0) @@ -52,37 +56,50 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - // TODO проверка позиции - if (position >= Count || position < 0) return null; + //TODO выброс ошибки если выход за границу + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } return _collection[position]; } public int Insert(T obj) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора - if (Count == _maxCount) return -1; + // TODO выброс ошибки если переполнение + if (Count == _maxCount) + { + throw new CollectionOverflowException(Count); + } _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO проверка позиции - // TODO вставка по позиции - if (Count == _maxCount) return -1; - if (position >= Count || position < 0) return -1; + // TODO выброс ошибки если переполнение + // TODO выброс ошибки если за границу + if (Count == _maxCount) + { + throw new CollectionOverflowException(Count); + } + // Проверка позиции + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } _collection.Insert(position, obj); return position; } - public T Remove(int position) + public T? Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из списка - if (position >= Count || position < 0) return null; - T obj = _collection[position]; + // TODO если выброс за границу + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } + T? obj = _collection[position]; _collection.RemoveAt(position); return obj; } diff --git a/Monorail/Monorail/CollectionGenericObjects/LocomotiveSharingService.cs b/Monorail/Monorail/CollectionGenericObjects/LocomotiveSharingService.cs index 4e245cb..ed51484 100644 --- a/Monorail/Monorail/CollectionGenericObjects/LocomotiveSharingService.cs +++ b/Monorail/Monorail/CollectionGenericObjects/LocomotiveSharingService.cs @@ -45,13 +45,17 @@ public class LocomotiveSharingService : AbstractCompany { int posX = 0; int posY = _pictureHeight / _placeSizeHeight - 1; + int LocomotiveWidth = posX - 1; + int LocomotiveHeight = 0; for (int i = 0; i < _collection?.Count; i++) { - if (_collection.Get(i) != null) + + try { _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i)?.SetPosition(posX * _placeSizeWidth + 3, posY * _placeSizeHeight + 3); } + catch (Exception) { } posY--; if (posY < 0) { diff --git a/Monorail/Monorail/CollectionGenericObjects/MassiveGenericObjects.cs b/Monorail/Monorail/CollectionGenericObjects/MassiveGenericObjects.cs index 38e3d9e..dbd0781 100644 --- a/Monorail/Monorail/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Monorail/Monorail/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using Monorail.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -19,6 +20,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects private T?[] _collection; public int Count => _collection.Length; + public CollectionType GetCollectionType => CollectionType.Massive; + public int MaxCount { get @@ -42,7 +45,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор @@ -54,73 +57,73 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - // TODO проверка позиции - if (position >= _collection.Length || position < 0) - { return null; } + // TODO выброс ошибки если выход за границу + // TODO выброс ошибки если объект пустой + 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) { - // TODO вставка в свободное место набора - int index = 0; - while (index < _collection.Length) - { - if (_collection[index] == null) - { - _collection[index] = obj; - return index; - } - - index++; - } - return -1; + // Вставка в свободное место набора + return Insert(obj, 0); } public int Insert(T obj, int position) { - // TODO проверка позиции - // TODO проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до - // TODO вставка - if (position >= _collection.Length || position < 0) - { return -1; } - + // Проверка позиции + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + // Проверка, что элемент массива по этой позиции пустой if (_collection[position] == null) { _collection[position] = obj; return position; } - int index; - - for (index = position + 1; index < _collection.Length; ++index) + //Свободное место после этой позиции + for (int i = position + 1; i < Count; i++) { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[position] = obj; - return position; + _collection[i] = obj; + return i; } } - - for (index = position - 1; index >= 0; --index) + //Свободное место до этой позиции + for (int i = position - 1; i >= 0; i--) { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[position] = obj; - return position; + _collection[i] = obj; + return i; } } - return -1; + throw new CollectionOverflowException(Count); } - public T Remove(int position) + public T? Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из массива, присвоив элементу массива значение null - if (position >= _collection.Length || position < 0) - { return null; } - T obj = _collection[position]; + // TODO выброс ошибки если выход за границу + // TODO выброс ошибки если объект пустой + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) + { + throw new ObjectNotFoundException(position); + } + // Удаление объекта из массива + T? obj = _collection[position]; _collection[position] = null; return obj; } diff --git a/Monorail/Monorail/CollectionGenericObjects/StorageCollection.cs b/Monorail/Monorail/CollectionGenericObjects/StorageCollection.cs index 887cc6f..eb75175 100644 --- a/Monorail/Monorail/CollectionGenericObjects/StorageCollection.cs +++ b/Monorail/Monorail/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using Monorail.Drawnings; +using Monorail.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -41,12 +42,18 @@ public class StorageCollection { // TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO Прописать логику для добавления - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - else if (collectionType == CollectionType.Massive) + if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name) || collectionType == CollectionType.None) + { + return; + } + if (collectionType == CollectionType.Massive) + { _storages[name] = new MassiveGenericObjects(); - else if (collectionType == CollectionType.List) + } + if (collectionType == CollectionType.List) + { _storages[name] = new ListGenericObjects(); + } } /// @@ -57,7 +64,9 @@ public class StorageCollection { // TODO Прописать логику для удаления коллекции if (_storages.ContainsKey(name)) + { _storages.Remove(name); + } } /// @@ -69,10 +78,14 @@ public class StorageCollection { get { - // TODO Продумать логику получения объекта if (_storages.ContainsKey(name)) + { return _storages[name]; - return null; + } + else + { + return null; + } } } @@ -94,35 +107,36 @@ public class StorageCollection /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); } + if (File.Exists(filename)) { File.Delete(filename); } + using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); foreach (KeyValuePair> value in _storages) { - StringBuilder sb = new(); - sb.Append(Environment.NewLine); + writer.Write(Environment.NewLine); // не сохраняем пустые коллекции if (value.Value.Count == 0) { continue; } - sb.Append(value.Key); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); - sb.Append(_separatorForKeyValue); + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.GetCollectionType); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; @@ -130,47 +144,37 @@ public class StorageCollection { continue; } - sb.Append(data); - sb.Append(_separatorItems); + writer.Write(data); + writer.Write(_separatorItems); } - 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 Exception("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) { - //по идее этого произойти не должно - //if (strs == null) - //{ - // return false; - //} string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 4) { @@ -180,7 +184,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -188,15 +192,19 @@ public class StorageCollection { if (elem?.CreateDrawningLocomotive() is T locomotive) { - if (collection.Insert(locomotive) == -1) + try { - return false; + if (collection.Insert(locomotive) == -1) + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } - return true; } } /// diff --git a/Monorail/Monorail/Exceptions/CollectionOverflowException.cs b/Monorail/Monorail/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..4b69a48 --- /dev/null +++ b/Monorail/Monorail/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.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/Monorail/Monorail/Exceptions/ObjectNotFoundException.cs b/Monorail/Monorail/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..9c8c0f3 --- /dev/null +++ b/Monorail/Monorail/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.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/Monorail/Monorail/Exceptions/PositionOutOfCollectionException.cs b/Monorail/Monorail/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..a70cdc0 --- /dev/null +++ b/Monorail/Monorail/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.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) { } +} diff --git a/Monorail/Monorail/FormLocomotiveCollection.cs b/Monorail/Monorail/FormLocomotiveCollection.cs index bdabc3e..a737b74 100644 --- a/Monorail/Monorail/FormLocomotiveCollection.cs +++ b/Monorail/Monorail/FormLocomotiveCollection.cs @@ -1,5 +1,7 @@ -using Monorail.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using Monorail.CollectionGenericObjects; using Monorail.Drawnings; +using Monorail.Exceptions; using System; using System.Collections.Generic; using System.ComponentModel; @@ -27,13 +29,20 @@ public partial class FormLocomotiveCollection : Form /// private AbstractCompany? _company = null; + + /// + /// Логер + /// + private readonly ILogger _logger; /// /// Конструктор - /// - public FormLocomotiveCollection() + /// z + public FormLocomotiveCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// @@ -65,19 +74,23 @@ public partial class FormLocomotiveCollection : Form /// private void SetLocomotive(DrawningLocomotive? locomotive) { - if (_company == null || locomotive == null) + try { - return; + if (_company == null || locomotive == null) + { + return; + } + if (_company + locomotive != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + locomotive.GetDataForSave()); + } } - - if (_company + locomotive != -1) + catch (CollectionOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -88,7 +101,6 @@ public partial class FormLocomotiveCollection : Form /// private void ButtonRemoveLocomotiv_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) { return; @@ -99,17 +111,31 @@ public partial class FormLocomotiveCollection : Form return; } - int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + int pos = Convert.ToInt32(maskedTextBox.Text); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удаление объекта по индексу " + pos); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation("Не удалось удалить объект из коллекции по индексу " + pos); + } } - else + catch (ObjectNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } - } @@ -127,26 +153,30 @@ public partial class FormLocomotiveCollection : Form DrawningLocomotive? locomotive = null; int counter = 100; - while (locomotive == null) + try { - locomotive = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (locomotive == null) { - break; + locomotive = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + if (locomotive == null) + { + return; } - } - if (locomotive == null) - { - return; + FormMonorail form = new FormMonorail(); + form.SetLocomotive = locomotive; + form.ShowDialog(); } - - FormMonorail form = new() + catch (Exception ex) { - SetLocomotive = locomotive - }; - form.ShowDialog(); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } /// @@ -176,19 +206,26 @@ public partial class FormLocomotiveCollection : Form MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) + try { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// /// @@ -201,17 +238,26 @@ public partial class FormLocomotiveCollection : Form // нужно убедиться, что есть выбранная коллекция // спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись // удалить и обновить ListBox - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null) { MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + + try { - return; + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + _logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString()); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); } /// @@ -271,16 +317,18 @@ public partial class FormLocomotiveCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _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); } + } } @@ -293,16 +341,17 @@ public partial class FormLocomotiveCollection : 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); RerfreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/Monorail/Monorail/FormLocomotiveConfig.cs b/Monorail/Monorail/FormLocomotiveConfig.cs index aab0d7b..a238e92 100644 --- a/Monorail/Monorail/FormLocomotiveConfig.cs +++ b/Monorail/Monorail/FormLocomotiveConfig.cs @@ -25,7 +25,7 @@ public partial class FormLocomotiveConfig : Form /// /// Событие для передачи объекта /// - + private event Action? LocomotiveDelegate; /// diff --git a/Monorail/Monorail/Monorail.csproj b/Monorail/Monorail/Monorail.csproj index 244387d..5e0ec26 100644 --- a/Monorail/Monorail/Monorail.csproj +++ b/Monorail/Monorail/Monorail.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True diff --git a/Monorail/Monorail/Program.cs b/Monorail/Monorail/Program.cs index e9e2c6d..64048fb 100644 --- a/Monorail/Monorail/Program.cs +++ b/Monorail/Monorail/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace Monorail { internal static class Program @@ -10,8 +15,36 @@ namespace Monorail { // 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()); + } + + /// + /// DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile($"{pathNeed}serilog.json") + .Build()) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/Monorail/Monorail/serilog.json b/Monorail/Monorail/serilog.json new file mode 100644 index 0000000..8966934 --- /dev/null +++ b/Monorail/Monorail/serilog.json @@ -0,0 +1,17 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "Locomotivelog.log" } + } + ], + "Properties": { + "Applicatoin": "Sample" + } + } + + +} \ No newline at end of file