From b549f626a632b80b86f7cdbc31a2d3de30351296 Mon Sep 17 00:00:00 2001 From: easynickname1 <7326033@gmail.com> Date: Tue, 21 May 2024 00:48:53 +0400 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=E2=84=967?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 12 ++- .../BoatHarborService.cs | 21 ++-- .../ICollectionGenericObjects.cs | 6 +- .../ListGenericObjects.cs | 47 ++++---- .../MassiveGenericObjects.cs | 47 ++++---- .../StorageCollection.cs | 39 ++++--- .../Exceptions/CollectionOverflowException.cs | 20 ++++ .../Exceptions/ObjectNotFoundException.cs | 20 ++++ .../PositionOutOfCollectionException.cs | 20 ++++ .../FormBoatCollection.Designer.cs | 16 +-- .../ProjectMotorBoat/FormBoatCollection.cs | 102 ++++++++++++------ ProjectMotorBoat/ProjectMotorBoat/Program.cs | 29 ++++- .../ProjectMotorBoat/ProjectMotorBoat.csproj | 12 +++ ProjectMotorBoat/ProjectMotorBoat/nlog.config | 15 +++ ProjectMotorBoat/ProjectMotorBoat/save.txt | 2 + ProjectMotorBoat/ProjectMotorBoat/save2.txt | 2 + 16 files changed, 283 insertions(+), 127 deletions(-) create mode 100644 ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectMotorBoat/ProjectMotorBoat/nlog.config create mode 100644 ProjectMotorBoat/ProjectMotorBoat/save.txt create mode 100644 ProjectMotorBoat/ProjectMotorBoat/save2.txt diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs index 5a87d1f..524d736 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs @@ -10,7 +10,7 @@ public abstract class AbstractCompany /// /// Размер места (ширина) /// - protected readonly int _placeSizeWidth = 120; + protected readonly int _placeSizeWidth = 126; /// /// Размер места (высота) @@ -35,7 +35,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth * _pictureHeight) / (_placeSizeWidth * _placeSizeHeight); /// /// Конструктор @@ -96,8 +96,12 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawingBoat? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawingBoat? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (Exception) { } } return bitmap; diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs index 0854001..58ee77b 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs @@ -1,5 +1,6 @@ using ProjectMotorBoat.Drawings; using ProjectMotorBoat.Entities; +using ProjectMotorBoat.Exceptions; using System.Drawing; namespace ProjectMotorBoat.CollectionGenericObjects; @@ -24,9 +25,9 @@ public class BoatHarborService : AbstractCompany { Pen pen = new(Color.BurlyWood, 4); - for (int startPosX = 5; (startPosX + _placeSizeWidth) < _pictureWidth; startPosX += _placeSizeWidth) + for (int startPosX = 0; (startPosX + _placeSizeWidth) < _pictureWidth; startPosX += _placeSizeWidth) { - for (int startPosY = 5; (startPosY + _placeSizeHeight) < _pictureHeight; startPosY += _placeSizeHeight) + for (int startPosY = 0; (startPosY + _placeSizeHeight) < _pictureHeight; startPosY += _placeSizeHeight) { Point[] points = { @@ -42,19 +43,23 @@ public class BoatHarborService : AbstractCompany protected override void SetObjectsPosition() { - int startPosX = 10; - int startPosY = 10; + int startPosX = 5; + int startPosY = 5; - for (int i = 0; _collection?.Get(i) != null; i++) + for (int i = 0; i < (_collection?.Count ?? 0); i++) { if (startPosX + _placeSizeWidth > _pictureWidth) { - startPosX = 10; + startPosX = 5; startPosY += _placeSizeHeight; } - _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i).SetPosition(startPosX, startPosY); + try + { + _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); + _collection.Get(i).SetPosition(startPosX, startPosY); + } + catch (Exception) { } startPosX += _placeSizeWidth; } diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs index b405892..329018d 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,7 +21,7 @@ public interface ICollectionGenericObjects /// Добавление объекта в коллекцию /// /// Добавляемый объект - /// true - вставка прошла удачно, false - вставка не удалась + /// Count - вставка прошла удачно, -1 - вставка не удалась int Insert(T obj); /// @@ -29,14 +29,14 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// Позиция - /// true - вставка прошла удачно, false - вставка не удалась + /// Count - вставка прошла удачно, -1 - вставка не удалась int Insert(T obj, int position); /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция - /// true - удаление прошло удачно, false - удаление не удалось + /// Объект T? Remove(int position); /// diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs index f815ab9..ff3e277 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectMotorBoat.CollectionGenericObjects; +using ProjectMotorBoat.Exceptions; + +namespace ProjectMotorBoat.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -39,46 +41,41 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < Count && _collection[position] != null) - { - return _collection[position]; - } - return null; + // выброс ошибки, если выход за границы массива + if (position < 0 || position > _collection.Count) throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { - if (Count < _maxCount) - { - _collection.Add(obj); - return _collection.Count; - } - return -1; + // выброс ошибки, если переполнение + if (Count >= _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); + return _collection.Count; } public int Insert(T obj, int position) { - if (Count < _maxCount) + // выброс ошибки, если переполнение + if (Count >= _maxCount) throw new CollectionOverflowException(); + + if (_collection[position] == null) { - if (_collection[position] == null) - { - _collection.Insert(position, obj); - return position; - } + _collection.Insert(position, obj); + return position; } return -1; } public T? Remove(int position) { - if (Count < _maxCount) + // выброс ошибки, если выход за границы массива + if (position < 0 || position > _collection.Count) throw new PositionOutOfCollectionException(position); + if (_collection[position] != null) { - if (_collection[position] != null) - { - T? obj = _collection[position]; - _collection.RemoveAt(position); - return obj; - } + T? obj = _collection[position]; + _collection.RemoveAt(position); + return obj; } return null; } diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs index 27cc790..a0ca361 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectMotorBoat.CollectionGenericObjects; +using ProjectMotorBoat.Exceptions; + +namespace ProjectMotorBoat.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -48,12 +50,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - // проверка позиции ✔ - if (_collection[position] != null && position < Count - 1) - { - return _collection[position]; - } - return null; + // выброс ошибки, если выход за границы массива + if (position >= Count) throw new PositionOutOfCollectionException(position); + // выброс ошибки, если объект пустой + if (_collection[position] == null) throw new ObjectNotFoundException(position); + + return _collection[position]; } public int Insert(T obj) @@ -67,16 +69,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects return Count; } } - return -1; + // выброс ошибки, если переполнение + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - // проверка позиции ✔ - // проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до ✔ - // вставка ✔ + // выброс ошибки, если выход за границы массива + if (position >= Count) throw new PositionOutOfCollectionException(position); + if (_collection[position] != null) { for (int i = position; i < Count; i++) @@ -97,22 +98,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } - - return -1; + // выброс ошибки, если переполнение + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - // проверка позиции ✔ - // удаление объекта из массива, присвоив элементу массива значение null ✔ - if (_collection[position] != null) - { - T? obj = _collection[position]; - _collection[position] = null; - return obj; - } + // выброс ошибки, если выход за границы массива + if (position >= Count) throw new PositionOutOfCollectionException(position); + // выброс ошибки, если объект пустой + if (_collection[position] == null) throw new ObjectNotFoundException(position); - return null; + T? obj = _collection[position]; + _collection[position] = null; + return obj; } public IEnumerable GetItems() diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs index 8001079..2c0555f 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectMotorBoat.Drawings; +using ProjectMotorBoat.Exceptions; using ProjectMotorBoat.MovementStrategy; using System.Text; using System.Windows.Forms; @@ -103,12 +104,11 @@ public class StorageCollection /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -151,19 +151,17 @@ public class StorageCollection using FileStream fs = new(filename, FileMode.Create); byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); fs.Write(info, 0, info.Length); - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } string bufferTextFromFile = ""; @@ -180,13 +178,12 @@ public class StorageCollection string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!strs[0].Equals(_collectionKey)) { - // Если нет такой записи, то это не те данные - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); @@ -199,12 +196,8 @@ public class StorageCollection } CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - return false; - } - + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -212,17 +205,21 @@ public class StorageCollection { if (elem?.CreateDrawingBoat() is T boat) { - if (collection.Insert(boat) == 0) + try { - return false; + if (collection.Insert(boat) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } - _storages.Add(record[0], collection); } - - return true; } /// diff --git a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..25aa59b --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectMotorBoat.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + + public CollectionOverflowException() : base() { } + + public CollectionOverflowException(string message) : base(message) { } + + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..d4bdf6d --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectMotorBoat.Exceptions; + +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + + public ObjectNotFoundException() : base() { } + + public ObjectNotFoundException(string message) : base(message) { } + + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..7bbfa51 --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectMotorBoat.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/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs index fcf7995..f6297f9 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs @@ -66,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(777, 24); + groupBoxTools.Location = new Point(763, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(201, 561); + groupBoxTools.Size = new Size(201, 544); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -82,15 +82,15 @@ panelCompanyTools.Controls.Add(buttonRemoveBoat); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 329); + panelCompanyTools.Location = new Point(3, 322); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(195, 229); + panelCompanyTools.Size = new Size(195, 219); panelCompanyTools.TabIndex = 8; // // buttonAddBoat // buttonAddBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddBoat.Location = new Point(3, 4); + buttonAddBoat.Location = new Point(3, 3); buttonAddBoat.Name = "buttonAddBoat"; buttonAddBoat.Size = new Size(184, 32); buttonAddBoat.TabIndex = 1; @@ -249,7 +249,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(777, 561); + pictureBox.Size = new Size(763, 544); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -258,7 +258,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(978, 24); + menuStrip.Size = new Size(964, 24); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip1"; // @@ -297,7 +297,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(978, 585); + ClientSize = new Size(964, 568); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); diff --git a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs index a830c41..525a334 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs @@ -1,4 +1,5 @@ -using ProjectMotorBoat.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectMotorBoat.CollectionGenericObjects; using ProjectMotorBoat.Drawings; namespace ProjectMotorBoat; @@ -18,13 +19,19 @@ public partial class FormBoatCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormBoatCollection() + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -61,14 +68,19 @@ public partial class FormBoatCollection : Form return; } - if (_company + boat >= 0) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + boat >= 0) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект: {boat}", boat.GetDataForSave()); + pictureBox.Image = _company.Show(); + } } - else + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -90,14 +102,20 @@ public partial class FormBoatCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation("Удалён объект по позиции: {pos}", pos); + pictureBox.Image = _company.Show(); + } } - else + catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -115,26 +133,33 @@ public partial class FormBoatCollection : Form DrawingBoat? boat = null; int counter = 100; - while (boat == null) + try { - boat = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (boat == null) { - break; + boat = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } - } - if (boat == null) - { - return; - } + if (boat == null) + { + return; + } - FormMotorBoat form = new() + FormMotorBoat form = new() + { + SetBoat = boat + }; + form.ShowDialog(); + } + catch (Exception ex) { - SetBoat = boat - }; - form.ShowDialog(); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// @@ -176,6 +201,7 @@ public partial class FormBoatCollection : Form } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавлена коллекция: {collection} Типа: {type}", textBoxCollectionName.Text, collectionType.ToString()); RerfreshListBoxItems(); } @@ -195,8 +221,11 @@ public partial class FormBoatCollection : Form return; } if (_storageCollection.Keys.Contains(listBoxCollection.SelectedItem.ToString() ?? string.Empty)) + { _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString() ?? string.Empty); + } + _logger.LogInformation("Удалена коллекция: {collection}", listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); } @@ -241,6 +270,7 @@ public partial class FormBoatCollection : Form { case "Хранилище": _company = new BoatHarborService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Создана компания на коллекции: {collection}", listBoxCollection.SelectedItem.ToString()); break; } @@ -257,13 +287,16 @@ public partial class FormBoatCollection : 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); } } } @@ -275,18 +308,21 @@ public partial class FormBoatCollection : Form /// private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { - // TODO продумать логику if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); RerfreshListBoxItems(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - 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/ProjectMotorBoat/ProjectMotorBoat/Program.cs b/ProjectMotorBoat/ProjectMotorBoat/Program.cs index bcbd11e..843a24c 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/Program.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectMotorBoat { internal static class Program @@ -11,7 +15,30 @@ namespace ProjectMotorBoat // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormBoatCollection()); + + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .WriteTo.File("boatlog-.log", rollingInterval: RollingInterval.Day) + .CreateLogger(); + + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// + /// Конфигурация сервиса DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(Log.Logger); + }); } } } \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj b/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj index 13ee123..659ff05 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj +++ b/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj @@ -8,6 +8,12 @@ enable + + + + + + True @@ -23,4 +29,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/nlog.config b/ProjectMotorBoat/ProjectMotorBoat/nlog.config new file mode 100644 index 0000000..d94f71a --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/save.txt b/ProjectMotorBoat/ProjectMotorBoat/save.txt new file mode 100644 index 0000000..36db68b --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/save.txt @@ -0,0 +1,2 @@ +CollectionsStorage +Коллекция|Massive|60|EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White; \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/save2.txt b/ProjectMotorBoat/ProjectMotorBoat/save2.txt new file mode 100644 index 0000000..458d81f --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/save2.txt @@ -0,0 +1,2 @@ +CollectionsStorage +1|Massive|55|EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True; \ No newline at end of file