diff --git a/lab_0/CollectionGenericObject/AbstractCompany.cs b/lab_0/CollectionGenericObject/AbstractCompany.cs index e5624a4..e91d543 100644 --- a/lab_0/CollectionGenericObject/AbstractCompany.cs +++ b/lab_0/CollectionGenericObject/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectBus.Drawnings; +using ProjectBus.Exceptions; namespace ProjectBus.CollectionGenericObject; /// @@ -34,7 +35,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор @@ -95,8 +96,19 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningSimpleBus? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningSimpleBus? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException e) + { + // Relax Man ;) + } + catch (PositionOutOfCollectionException e) + { + // Relax Man ;) + } } return bitmap; diff --git a/lab_0/CollectionGenericObject/BusStation.cs b/lab_0/CollectionGenericObject/BusStation.cs index ddc7084..8c32ace 100644 --- a/lab_0/CollectionGenericObject/BusStation.cs +++ b/lab_0/CollectionGenericObject/BusStation.cs @@ -1,5 +1,6 @@ using ProjectBus.Drawnings; using ProjectBus.Entities; +using ProjectBus.Exceptions; using System; namespace ProjectBus.CollectionGenericObject; @@ -41,13 +42,25 @@ public class BusStation : AbstractCompany { for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) { - DrawningSimpleBus? drawningSimpleBus = _collection?.Get(n); - n++; - if (drawningSimpleBus != null) + try { - drawningSimpleBus.SetPictureSize(_pictureWidth, _pictureHeight); - drawningSimpleBus.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); + DrawningSimpleBus? drawingSimpleBus = _collection?.Get(n); + if (drawingSimpleBus != null) + { + drawingSimpleBus.SetPictureSize(_pictureWidth, _pictureHeight); + drawingSimpleBus.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); + } } + catch (ObjectNotFoundException e) + { + // Relax Man ;) + } + catch (PositionOutOfCollectionException e) + { + // Relax Man ;) + } + + n++; } } } diff --git a/lab_0/CollectionGenericObject/ListGenericObjects.cs b/lab_0/CollectionGenericObject/ListGenericObjects.cs index a831d86..890d317 100644 --- a/lab_0/CollectionGenericObject/ListGenericObjects.cs +++ b/lab_0/CollectionGenericObject/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectBus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -46,42 +47,32 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - - if (position < 0 || position > _collection.Count - 1) - { - return null; - } + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } + public int Insert(T obj) { - if (_collection.Count + 1 > _maxCount) { return 0; } + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); - - return 1; + return Count; } public int Insert(T obj, int position) { - if (_collection.Count + 1 < _maxCount) { return 0; } - if (position > _collection.Count || position < 0) - { - return 0; - } + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); - return 1; + return position; } public T Remove(int position) { - if (position > _collection.Count || position < 0) - { - return null; - } - T temp = _collection[position]; + if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return temp; + return obj; } public IEnumerable GetItems() diff --git a/lab_0/CollectionGenericObject/MassiveGenericObjects.cs b/lab_0/CollectionGenericObject/MassiveGenericObjects.cs index f230ed1..ba7e618 100644 --- a/lab_0/CollectionGenericObject/MassiveGenericObjects.cs +++ b/lab_0/CollectionGenericObject/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectBus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -50,48 +51,57 @@ namespace ProjectBus.CollectionGenericObject; /// Конструктор /// public MassiveGenericObjects() - { - _collection = Array.Empty(); - } + { + _collection = Array.Empty(); + } - public T? Get(int position) + public T? Get(int position) + { + 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) + { + // вставка в свободное место набора + for (int i = 0; i < Count; i++) { - if (position >= 0 && position < Count) + if (_collection[i] == null) { - return _collection[position]; + _collection[i] = obj; + return i; } - - return null; } - public int Insert(T obj) + throw new CollectionOverflowException(Count); + } + + public int Insert(T obj, int position) + { + // проверка позиции + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + + // проверка, что элемент массива по этой позиции пустой, если нет, то + // ищется свободное место после этой позиции и идет вставка туда + // если нет после, ищем до + if (_collection[position] != null) { - // вставка в свободное место набора - for (int i = 0; i < Count; i++) + bool pushed = false; + for (int index = position + 1; index < Count; index++) { - if (_collection[i] == null) + if (_collection[index] == null) { - _collection[i] = obj; - return i; + position = index; + pushed = true; + break; } } - return -1; - } - - public int Insert(T obj, int position) - { - // проверка позиции - if (position < 0 || position >= Count) + if (!pushed) { - return -1; - } - - // проверка, что элемент массива по этой позиции пустой, если нет, то ищется свободное место после этой позиции и идет вставка туда если нет после, ищем до - if (_collection[position] != null) - { - bool pushed = false; - for (int index = position + 1; index < Count; index++) + for (int index = position - 1; index >= 0; index--) { if (_collection[index] == null) { @@ -100,46 +110,30 @@ namespace ProjectBus.CollectionGenericObject; break; } } - - if (!pushed) - { - for (int index = position - 1; index >= 0; index--) - { - if (_collection[index] == null) - { - position = index; - pushed = true; - break; - } - } - } - - if (!pushed) - { - return position; - } } - // вставка - _collection[position] = obj; - return position; - } - - public T? Remove(int position) - { - // проверка позиции - if (position < 0 || position >= Count) + if (!pushed) { - return null; + throw new CollectionOverflowException(Count); } - - if (_collection[position] == null) return null; - - T? temp = _collection[position]; - _collection[position] = null; - return temp; } + // вставка + _collection[position] = obj; + return position; + } + + public T? Remove(int position) + { + // проверка позиции + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + + 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) @@ -147,5 +141,4 @@ namespace ProjectBus.CollectionGenericObject; yield return _collection[i]; } } -} - +} \ No newline at end of file diff --git a/lab_0/CollectionGenericObject/StorageCollection.cs b/lab_0/CollectionGenericObject/StorageCollection.cs index f0f0f76..343f3eb 100644 --- a/lab_0/CollectionGenericObject/StorageCollection.cs +++ b/lab_0/CollectionGenericObject/StorageCollection.cs @@ -1,6 +1,8 @@ using ProjectBus.Drawnings; +using ProjectBus.Exceptions; using System; using System.Collections.Generic; +using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -54,19 +56,12 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (name == null || _storages.ContainsKey(name)) { return; } - switch (collectionType) - - { - case CollectionType.None: - return; - case CollectionType.Massive: - _storages.Add(name, new MassiveGenericObjects { }); - return; - case CollectionType.List: - _storages.Add(name, new ListGenericObjects { }); - return; - } + if (_storages.ContainsKey(name)) return; + if (collectionType == CollectionType.None) return; + else if (collectionType == CollectionType.Massive) + _storages[name] = new MassiveGenericObjects(); + else if (collectionType == CollectionType.List) + _storages[name] = new ListGenericObjects(); } @@ -76,8 +71,8 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (name == null || !_storages.ContainsKey(name)) { return; } - _storages.Remove(name); + if (_storages.ContainsKey(name)) + _storages.Remove(name); } /// @@ -89,8 +84,9 @@ public class StorageCollection { get { - if (name == null || !_storages.ContainsKey(name)) { return null; } - return _storages[name]; + if (_storages.ContainsKey(name)) + return _storages[name]; + return null; } } @@ -99,11 +95,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)) @@ -118,6 +114,7 @@ public class StorageCollection { StringBuilder sb = new(); sb.Append(Environment.NewLine); + // не сохраняем пустые коллекции if (value.Value.Count == 0) { @@ -137,16 +134,12 @@ public class StorageCollection { continue; } - sb.Append(data); sb.Append(_separatorItems); } - writer.Write(sb); } } - - return true; } /// @@ -154,11 +147,11 @@ public class StorageCollection /// /// Путь и имя файла /// 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)) @@ -166,14 +159,12 @@ 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 = ""; while ((strs = fs.ReadLine()) != null) @@ -183,31 +174,33 @@ public class StorageCollection { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); 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); foreach (string elem in set) { - if (elem?.CreateDrawningSimpleBus() is T bus) + if (elem?.CreateDrawningSimpleBus() is T simpleBus) { - if (collection.Insert(bus) == -1) + try { - return false; + if (collection.Insert(simpleBus) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new DataException("Коллекция переполнена", ex); } } } - _storages.Add(record[0], collection); } - - return true; } } diff --git a/lab_0/Exceptions/CollectionAlreadyExistsException.cs b/lab_0/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..367c50d --- /dev/null +++ b/lab_0/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.Exceptions; + +public class CollectionAlreadyExistsException : Exception +{ + public CollectionAlreadyExistsException() : base() { } + public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { } + public CollectionAlreadyExistsException(string name, Exception exception) :base($"Коллекция {name} уже существует!", exception) + { } + protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/lab_0/Exceptions/CollectionInsertException.cs b/lab_0/Exceptions/CollectionInsertException.cs new file mode 100644 index 0000000..b90d4f0 --- /dev/null +++ b/lab_0/Exceptions/CollectionInsertException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.Exceptions; + +public class CollectionInsertException : Exception +{ + public CollectionInsertException() : base() { } + public CollectionInsertException(string message) : base(message) { } + public CollectionInsertException(string message, Exception exception) :base(message, exception) + { } + protected CollectionInsertException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + +} diff --git a/lab_0/Exceptions/CollectionOverflowException.cs b/lab_0/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..df9f5fc --- /dev/null +++ b/lab_0/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + + +namespace ProjectBus.Exceptions; + +[Serializable] + +public 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/lab_0/Exceptions/CollectionTypeException.cs b/lab_0/Exceptions/CollectionTypeException.cs new file mode 100644 index 0000000..9740cc7 --- /dev/null +++ b/lab_0/Exceptions/CollectionTypeException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.Exceptions; +[Serializable] + +public class CollectionTypeException : Exception +{ + public CollectionTypeException() : base() { } + public CollectionTypeException(string message) : base(message) { } + public CollectionTypeException(string message, Exception exception) :base(message, exception) + { } + protected CollectionTypeException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + +} diff --git a/lab_0/Exceptions/EmptyFileExeption.cs b/lab_0/Exceptions/EmptyFileExeption.cs new file mode 100644 index 0000000..aff6dbd --- /dev/null +++ b/lab_0/Exceptions/EmptyFileExeption.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.Exceptions; + +public class EmptyFileExeption : Exception +{ + public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { } + public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { } + public EmptyFileExeption(string name, string message) : base(message) { } + public EmptyFileExeption(string name, string message, Exception exception) : base(message, exception) + { } + protected EmptyFileExeption(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + +} diff --git a/lab_0/Exceptions/ObjectNotFoundException.cs b/lab_0/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..c30eeca --- /dev/null +++ b/lab_0/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace ProjectBus.Exceptions; + + +[Serializable] +public 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/lab_0/Exceptions/PositionOutOfCollectionException.cs b/lab_0/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..a8890e0 --- /dev/null +++ b/lab_0/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,18 @@ +using System.Runtime.Serialization; + + +namespace ProjectBus.Exceptions; + +[Serializable] +public 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/lab_0/FormSimpleBusCollection.cs b/lab_0/FormSimpleBusCollection.cs index cd5331b..f782e15 100644 --- a/lab_0/FormSimpleBusCollection.cs +++ b/lab_0/FormSimpleBusCollection.cs @@ -2,6 +2,7 @@ using ProjectBus.Drawnings; using ProjectBus.CollectionGenericObject; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace ProjectBus; @@ -17,13 +18,16 @@ public partial class FormSimpleBusCollection : Form /// private AbstractCompany? _company = null; + private readonly ILogger _logger; + /// /// Конструктор /// - public FormSimpleBusCollection() + public FormSimpleBusCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -35,8 +39,9 @@ public partial class FormSimpleBusCollection : Form { switch (comboBoxSelectorCompany.Text) { - case "хранилище": - _company = new BusStation(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); + case "Хранилище": + _company = new BusStation(pictureBox.Width, pictureBox.Height, + new MassiveGenericObjects()); break; } } @@ -55,18 +60,24 @@ public partial class FormSimpleBusCollection : Form private void SetSimpleBus(DrawningSimpleBus? drawningSimpleBus) { - if (_company == null || drawningSimpleBus == null) return; - drawningSimpleBus.SetPictureSize(pictureBox.Width, pictureBox.Height); - - if (_company + drawningSimpleBus != -1) + if (_company == null || drawningSimpleBus == null) { + return; + } + try + { + var res = _company + drawningSimpleBus; MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); pictureBox.Image = _company.Show(); } - else + catch (Exception ex) { - MessageBox.Show("Объект не удалось добавить"); + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } + } @@ -128,20 +139,25 @@ public partial class FormSimpleBusCollection : Form return; } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { return; } int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) + try { + var res = _company - pos; MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален под индексом {pos}"); pictureBox.Image = _company.Show(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message, "Не удалось удалить объект", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -153,13 +169,15 @@ public partial class FormSimpleBusCollection : Form /// private void ButtonRefresh_Click(object sender, EventArgs e) { - if (_company == null) + listBoxCollection.Items.Clear(); + for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - return; + string? colName = _storageCollection.Keys?[i]; + if (!string.IsNullOrEmpty(colName)) + { + listBoxCollection.Items.Add(colName); + } } - - pictureBox.Image = _company.Show(); - } /// @@ -206,7 +224,8 @@ public partial class FormSimpleBusCollection : Form /// private void ButtonCollectionAdd_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || + (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; @@ -222,8 +241,18 @@ public partial class FormSimpleBusCollection : Form collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); + try + { + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавление коллекции"); + RerfreshListBoxItems(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } + } @@ -239,15 +268,19 @@ public partial class FormSimpleBusCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Коллекция удалена"); + RerfreshListBoxItems(); } + /// /// Обновление списка в listBoxCollection /// @@ -287,8 +320,9 @@ public partial class FormSimpleBusCollection : Form switch (comboBoxSelectorCompany.Text) { - case "хранилище": + case "Хранилище": _company = new BusStation(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Компания создана"); break; } @@ -296,6 +330,7 @@ public partial class FormSimpleBusCollection : Form RerfreshListBoxItems(); } + /// /// Обработка нажатия "Сохранение" /// @@ -305,13 +340,19 @@ public partial class FormSimpleBusCollection : 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($"Ошибка: {ex.Message}", ex.Message); } } @@ -326,14 +367,20 @@ public partial class FormSimpleBusCollection : 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($"Загрузка прошла успешно в {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/lab_0/Program.cs b/lab_0/Program.cs index beb3124..bce618e 100644 --- a/lab_0/Program.cs +++ b/lab_0/Program.cs @@ -1,4 +1,9 @@ +using Microsoft.Extensions.DependencyInjection; +using NLog.Extensions.Logging; +using Microsoft.Extensions.Configuration; using ProjectBus; +using System; +using Microsoft.Extensions.Logging; namespace lab_0 { @@ -13,7 +18,22 @@ namespace lab_0 // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormSimpleBusCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + } + + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/lab_0/ProjectBus.csproj b/lab_0/ProjectBus.csproj index 244387d..d258f05 100644 --- a/lab_0/ProjectBus.csproj +++ b/lab_0/ProjectBus.csproj @@ -8,6 +8,11 @@ enable + + + + + True @@ -23,4 +28,10 @@ + + + Always + + + \ No newline at end of file diff --git a/lab_0/ProjectBus.sln b/lab_0/ProjectBus.sln new file mode 100644 index 0000000..27b89b0 --- /dev/null +++ b/lab_0/ProjectBus.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34031.279 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectBus", "ProjectBus.csproj", "{7F126B40-AEDE-40A9-840E-4158D2218B6F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7F126B40-AEDE-40A9-840E-4158D2218B6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7F126B40-AEDE-40A9-840E-4158D2218B6F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7F126B40-AEDE-40A9-840E-4158D2218B6F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7F126B40-AEDE-40A9-840E-4158D2218B6F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {771E3743-AEF8-46E6-BE29-0866902F9DDA} + EndGlobalSection +EndGlobal diff --git a/lab_0/nlog.config b/lab_0/nlog.config new file mode 100644 index 0000000..98fa0dd --- /dev/null +++ b/lab_0/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + +