diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs index 04860eb..de253dc 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectContainerShip.Drawings; +using System.Linq.Expressions; namespace ProjectContainerShip.CollectionGenericObjects; /// @@ -14,7 +15,7 @@ namespace ProjectContainerShip.CollectionGenericObjects; /// /// Размер места (высота) /// - protected readonly int _placeSizeHeight = 80; + protected readonly int _placeSizeHeight = 82; /// /// Ширина окна @@ -94,8 +95,12 @@ namespace ProjectContainerShip.CollectionGenericObjects; SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { + try + { DrawningShip? obj = _collection?.Get(i); obj?.DrawTransport(graphics); + } + catch (Exception) { } } return bitmap; } diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs index 073a871..b6b431c 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ using ProjectContainerShip.CollectionGenericObjects; +using ProjectContainerShip.Exceptions; public class ListGenericObjects : ICollectionGenericObjects where T : class @@ -40,14 +41,14 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { // TODO проверка позиции - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { // TODO проверка, что не превышено максимальное количество элементов // TODO вставка в конец набора - if (Count == _maxCount) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } @@ -56,8 +57,8 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка, что не превышено максимальное количество элементов // TODO проверка позиции // TODO вставка по позиции - if (Count == _maxCount) return -1; - if (position >= Count || position < 0) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); return position; } @@ -65,7 +66,7 @@ public class ListGenericObjects : ICollectionGenericObjects { // TODO проверка позиции // TODO удаление объекта из списка - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); T obj = _collection[position]; _collection.RemoveAt(position); return obj; diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs index 8eecafe..103c774 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectContainerShip.Exceptions; + namespace ProjectContainerShip.CollectionGenericObjects { public class MassiveGenericObjects : ICollectionGenericObjects @@ -45,7 +47,8 @@ namespace ProjectContainerShip.CollectionGenericObjects public T? Get(int position) { // TODO проверка позиции - if (position >= _collection.Length || position < 0) return null; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj) @@ -61,7 +64,7 @@ namespace ProjectContainerShip.CollectionGenericObjects } ++index; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { @@ -70,8 +73,8 @@ namespace ProjectContainerShip.CollectionGenericObjects // ищется свободное место после этой позиции и идет вставка туда // если нет после, ищем до // TODO вставка - if (position >= _collection.Length || position < 0) - return -1; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) { _collection[position] = obj; @@ -97,16 +100,15 @@ namespace ProjectContainerShip.CollectionGenericObjects } --index; } - return -1; + throw new CollectionOverflowException(Count); } public T Remove(int position) { // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значение null - if (position >= _collection.Length || position < 0) { - return null; - } + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); T obj = _collection[position]; _collection[position] = null; diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipPortService.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipPortService.cs index 76791bc..14b78cd 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipPortService.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipPortService.cs @@ -32,11 +32,15 @@ public class ShipPortService : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (_collection.Get(i) != null) + try { - _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 55, curHeight * _placeSizeHeight + 20); + if (_collection.Get(i) != null) + { + _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); + _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 55, curHeight * _placeSizeHeight + 20); + } } + catch (Exception) { } if (curWidth > 0) curWidth--; else diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs index 202a0b0..627b581 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,6 @@ using ProjectContainerShip.Drawings; +using ProjectContainerShip.Exceptions; +using System.Numerics; using System.Text; namespace ProjectContainerShip.CollectionGenericObjects; @@ -96,12 +98,11 @@ where T : DrawningShip /// Сохранение информации по кораблям в хранилище в файл /// /// Путь и имя файла - /// 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)) { @@ -139,14 +140,11 @@ where T : DrawningShip } } - - return true; } /// /// Загрузка информации по кораблям в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных public bool LoadData(string filename) { if (!File.Exists(filename)) @@ -196,6 +194,7 @@ where T : DrawningShip return true; } } + /// /// Создание коллекции по типу /// diff --git a/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..00d9d81 --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.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 ProjectContainerShip.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/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectNotFoundException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..cbc18b2 --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/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 ProjectContainerShip.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/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..9476469 --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.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 ProjectContainerShip.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/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs index f380d34..2e2a0f2 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs @@ -67,9 +67,11 @@ groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; groupBoxTools.ForeColor = Color.Black; - groupBoxTools.Location = new Point(1601, 40); + groupBoxTools.Location = new Point(722, 24); + groupBoxTools.Margin = new Padding(2, 1, 2, 1); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(388, 1072); + groupBoxTools.Padding = new Padding(2, 1, 2, 1); + groupBoxTools.Size = new Size(209, 497); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -83,17 +85,19 @@ panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 598); + panelCompanyTools.Location = new Point(2, 275); + panelCompanyTools.Margin = new Padding(2, 1, 2, 1); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(382, 471); + panelCompanyTools.Size = new Size(205, 221); panelCompanyTools.TabIndex = 10; // // buttonAddShip // buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddShip.Location = new Point(3, 70); + buttonAddShip.Location = new Point(2, 33); + buttonAddShip.Margin = new Padding(2, 1, 2, 1); buttonAddShip.Name = "buttonAddShip"; - buttonAddShip.Size = new Size(370, 77); + buttonAddShip.Size = new Size(198, 36); buttonAddShip.TabIndex = 1; buttonAddShip.Text = "Добавление корабля"; buttonAddShip.UseVisualStyleBackColor = true; @@ -101,19 +105,21 @@ // // maskedTextBox // - maskedTextBox.Location = new Point(3, 201); + maskedTextBox.Location = new Point(2, 94); + maskedTextBox.Margin = new Padding(2, 1, 2, 1); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; - maskedTextBox.Size = new Size(370, 39); + maskedTextBox.Size = new Size(201, 23); maskedTextBox.TabIndex = 3; maskedTextBox.ValidatingType = typeof(int); // // buttonRemoveShip // buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveShip.Location = new Point(3, 246); + buttonRemoveShip.Location = new Point(2, 115); + buttonRemoveShip.Margin = new Padding(2, 1, 2, 1); buttonRemoveShip.Name = "buttonRemoveShip"; - buttonRemoveShip.Size = new Size(370, 77); + buttonRemoveShip.Size = new Size(198, 36); buttonRemoveShip.TabIndex = 4; buttonRemoveShip.Text = "Удалить корабль"; buttonRemoveShip.UseVisualStyleBackColor = true; @@ -122,9 +128,10 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 329); + buttonGoToCheck.Location = new Point(2, 154); + buttonGoToCheck.Margin = new Padding(2, 1, 2, 1); buttonGoToCheck.Name = "buttonGoToCheck"; - buttonGoToCheck.Size = new Size(370, 77); + buttonGoToCheck.Size = new Size(198, 36); buttonGoToCheck.TabIndex = 5; buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.UseVisualStyleBackColor = true; @@ -133,9 +140,10 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 412); + buttonRefresh.Location = new Point(2, 193); + buttonRefresh.Margin = new Padding(2, 1, 2, 1); buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(370, 77); + buttonRefresh.Size = new Size(198, 36); buttonRefresh.TabIndex = 6; buttonRefresh.Text = "Обновить"; buttonRefresh.UseVisualStyleBackColor = true; @@ -143,9 +151,10 @@ // // buttonCreateCompany // - buttonCreateCompany.Location = new Point(6, 546); + buttonCreateCompany.Location = new Point(3, 256); + buttonCreateCompany.Margin = new Padding(2, 1, 2, 1); buttonCreateCompany.Name = "buttonCreateCompany"; - buttonCreateCompany.Size = new Size(370, 46); + buttonCreateCompany.Size = new Size(199, 22); buttonCreateCompany.TabIndex = 9; buttonCreateCompany.Text = "Создать компанию"; buttonCreateCompany.UseVisualStyleBackColor = true; @@ -161,17 +170,19 @@ panelStorage.Controls.Add(textBoxCollectionName); panelStorage.Controls.Add(labelCollectionName); panelStorage.Dock = DockStyle.Top; - panelStorage.Location = new Point(3, 35); + panelStorage.Location = new Point(2, 17); + panelStorage.Margin = new Padding(2, 1, 2, 1); panelStorage.Name = "panelStorage"; - panelStorage.Size = new Size(382, 459); + panelStorage.Size = new Size(205, 215); panelStorage.TabIndex = 8; // // radioButtonMassive // radioButtonMassive.AutoSize = true; - radioButtonMassive.Location = new Point(39, 91); + radioButtonMassive.Location = new Point(21, 43); + radioButtonMassive.Margin = new Padding(2, 1, 2, 1); radioButtonMassive.Name = "radioButtonMassive"; - radioButtonMassive.Size = new Size(128, 36); + radioButtonMassive.Size = new Size(67, 19); radioButtonMassive.TabIndex = 7; radioButtonMassive.TabStop = true; radioButtonMassive.Text = "Массив"; @@ -179,9 +190,10 @@ // // buttonCollectionDel // - buttonCollectionDel.Location = new Point(3, 387); + buttonCollectionDel.Location = new Point(2, 181); + buttonCollectionDel.Margin = new Padding(2, 1, 2, 1); buttonCollectionDel.Name = "buttonCollectionDel"; - buttonCollectionDel.Size = new Size(370, 46); + buttonCollectionDel.Size = new Size(199, 22); buttonCollectionDel.TabIndex = 6; buttonCollectionDel.Text = "Удалить коллекцию"; buttonCollectionDel.UseVisualStyleBackColor = true; @@ -190,16 +202,19 @@ // listBoxCollection // listBoxCollection.FormattingEnabled = true; - listBoxCollection.Location = new Point(3, 185); + listBoxCollection.ItemHeight = 15; + listBoxCollection.Location = new Point(2, 87); + listBoxCollection.Margin = new Padding(2, 1, 2, 1); listBoxCollection.Name = "listBoxCollection"; - listBoxCollection.Size = new Size(370, 196); + listBoxCollection.Size = new Size(201, 94); listBoxCollection.TabIndex = 5; // // buttonCollectionAdd // - buttonCollectionAdd.Location = new Point(3, 133); + buttonCollectionAdd.Location = new Point(2, 62); + buttonCollectionAdd.Margin = new Padding(2, 1, 2, 1); buttonCollectionAdd.Name = "buttonCollectionAdd"; - buttonCollectionAdd.Size = new Size(370, 46); + buttonCollectionAdd.Size = new Size(199, 22); buttonCollectionAdd.TabIndex = 4; buttonCollectionAdd.Text = "Добавить коллекцию"; buttonCollectionAdd.UseVisualStyleBackColor = true; @@ -208,9 +223,10 @@ // radioButtonList // radioButtonList.AutoSize = true; - radioButtonList.Location = new Point(215, 91); + radioButtonList.Location = new Point(116, 43); + radioButtonList.Margin = new Padding(2, 1, 2, 1); radioButtonList.Name = "radioButtonList"; - radioButtonList.Size = new Size(125, 36); + radioButtonList.Size = new Size(66, 19); radioButtonList.TabIndex = 3; radioButtonList.TabStop = true; radioButtonList.Text = "Список"; @@ -218,17 +234,19 @@ // // textBoxCollectionName // - textBoxCollectionName.Location = new Point(3, 46); + textBoxCollectionName.Location = new Point(2, 22); + textBoxCollectionName.Margin = new Padding(2, 1, 2, 1); textBoxCollectionName.Name = "textBoxCollectionName"; - textBoxCollectionName.Size = new Size(370, 39); + textBoxCollectionName.Size = new Size(201, 23); textBoxCollectionName.TabIndex = 1; // // labelCollectionName // labelCollectionName.AutoSize = true; - labelCollectionName.Location = new Point(69, 11); + labelCollectionName.Location = new Point(37, 5); + labelCollectionName.Margin = new Padding(2, 0, 2, 0); labelCollectionName.Name = "labelCollectionName"; - labelCollectionName.Size = new Size(251, 32); + labelCollectionName.Size = new Size(125, 15); labelCollectionName.TabIndex = 0; labelCollectionName.Text = "Название коллекции:"; // @@ -238,18 +256,20 @@ comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); - comboBoxSelectorCompany.Location = new Point(6, 500); + comboBoxSelectorCompany.Location = new Point(3, 234); + comboBoxSelectorCompany.Margin = new Padding(2, 1, 2, 1); comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; - comboBoxSelectorCompany.Size = new Size(370, 40); + comboBoxSelectorCompany.Size = new Size(201, 23); comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; // // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 40); + pictureBox.Location = new Point(0, 24); + pictureBox.Margin = new Padding(2, 1, 2, 1); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1601, 1072); + pictureBox.Size = new Size(722, 497); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -259,7 +279,8 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1989, 40); + menuStrip.Padding = new Padding(3, 1, 0, 1); + menuStrip.Size = new Size(931, 24); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip1"; // @@ -267,14 +288,14 @@ // файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); файлToolStripMenuItem.Name = "файлToolStripMenuItem"; - файлToolStripMenuItem.Size = new Size(90, 36); + файлToolStripMenuItem.Size = new Size(48, 22); файлToolStripMenuItem.Text = "Файл"; // // saveToolStripMenuItem // saveToolStripMenuItem.Name = "saveToolStripMenuItem"; saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; - saveToolStripMenuItem.Size = new Size(361, 44); + saveToolStripMenuItem.Size = new Size(181, 22); saveToolStripMenuItem.Text = "Сохранение"; saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; // @@ -282,7 +303,7 @@ // loadToolStripMenuItem.Name = "loadToolStripMenuItem"; loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; - loadToolStripMenuItem.Size = new Size(361, 44); + loadToolStripMenuItem.Size = new Size(181, 22); loadToolStripMenuItem.Text = "Загрузка"; loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; // @@ -296,13 +317,14 @@ // // FormShipCollection // - AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1989, 1112); + ClientSize = new Size(931, 521); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); MainMenuStrip = menuStrip; + Margin = new Padding(2, 1, 2, 1); Name = "FormShipCollection"; Text = "Коллекция кораблей"; groupBoxTools.ResumeLayout(false); diff --git a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs index a11b369..a4ec120 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs @@ -1,5 +1,8 @@ -using ProjectContainerShip.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectContainerShip.CollectionGenericObjects; using ProjectContainerShip.Drawings; +using ProjectContainerShip.Exceptions; +using System.Numerics; namespace ProjectContainerShip; /// @@ -17,13 +20,20 @@ public partial class FormShipCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormShipCollection() + public FormShipCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// @@ -54,19 +64,25 @@ public partial class FormShipCollection : Form /// private void SetShip(DrawningShip ship) { - if (_company == null || ship == null) + try { - return; - } + if (_company == null || ship == null) + { + return; + } - if (_company + ship != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + ship != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + ship.GetDataForSave()); + } } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка : {Messsage}", ex.Message); } } @@ -88,15 +104,19 @@ public partial class FormShipCollection : Form } int position = Convert.ToInt32(maskedTextBox.Text); - - if (_company - position != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + if (_company - position != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удален объект по позиции " + position); + } } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -114,26 +134,33 @@ public partial class FormShipCollection : Form DrawningShip? ship = null; int counter = 100; - while (ship == null) - { - ship = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } - } + try + { + while (ship == null) + { + ship = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + FormContainerShip form = new() + { + SetShip = ship + }; + form.ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + if (ship == null) { return; } - - FormContainerShip form = new() - { - SetShip = ship - }; - form.ShowDialog(); } /// @@ -164,17 +191,26 @@ public partial class FormShipCollection : Form MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) + + try { - collectionType = CollectionType.Massive; + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } - else if (radioButtonList.Checked) + catch (Exception ex) { - collectionType = CollectionType.List; + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); } /// @@ -209,12 +245,20 @@ public partial class FormShipCollection : Form 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(); } /// @@ -255,15 +299,16 @@ public partial class FormShipCollection : 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); } } @@ -278,16 +323,17 @@ public partial class FormShipCollection : 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/ProjectContainerShip/ProjectContainerShip/FormShipConfig.cs b/ProjectContainerShip/ProjectContainerShip/FormShipConfig.cs index f11a4dc..71c4941 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipConfig.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipConfig.cs @@ -64,7 +64,7 @@ public partial class FormShipConfig : Form Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height); Graphics gr = Graphics.FromImage(bmp); _ship?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height); - _ship?.SetPosition(110, 75); + _ship?.SetPosition(40, 25); _ship?.DrawTransport(gr); pictureBoxObject.Image = bmp; } diff --git a/ProjectContainerShip/ProjectContainerShip/Program.cs b/ProjectContainerShip/ProjectContainerShip/Program.cs index 4f76f20..e4d028b 100644 --- a/ProjectContainerShip/ProjectContainerShip/Program.cs +++ b/ProjectContainerShip/ProjectContainerShip/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectContainerShip { internal static class Program @@ -11,7 +16,35 @@ namespace ProjectContainerShip // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormShipCollection()); + + 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/ProjectContainerShip/ProjectContainerShip/ProjectContainerShip.csproj b/ProjectContainerShip/ProjectContainerShip/ProjectContainerShip.csproj index af03d74..18c8538 100644 --- a/ProjectContainerShip/ProjectContainerShip/ProjectContainerShip.csproj +++ b/ProjectContainerShip/ProjectContainerShip/ProjectContainerShip.csproj @@ -8,6 +8,21 @@ enable + + + + + + + + + + + + + + + True @@ -23,4 +38,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/serilog.json b/ProjectContainerShip/ProjectContainerShip/serilog.json new file mode 100644 index 0000000..a7878e1 --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +}