From f22b50acad0764dc82aa823d42f51a36e3a00030 Mon Sep 17 00:00:00 2001 From: "leonteva.v" Date: Sat, 15 Jun 2024 03:12:12 +0400 Subject: [PATCH] lab 7 --- .../AbstractCompany.cs | 13 +- .../ListGenericObjects.cs | 13 +- .../MassiveGenericObjects.cs | 17 +- .../CollectionGenericObjects/ShipDocks.cs | 46 +- .../StorageCollection.cs | 28 +- .../Exceptions/CollectionOverflowException.cs | 20 + .../Exceptions/ObjectNotFoundException.cs | 20 + .../PositionOutOfCollectionException.cs | 20 + .../FormShipCollection.Designer.cs | 366 +++++++------ .../ProjectBattleship/FormShipCollection.cs | 482 +++++++++--------- .../ProjectBattleship/FormShipCollection.resx | 9 +- .../ProjectBattleship/Program.cs | 38 +- .../ProjectBattleship.csproj | 10 + .../ProjectBattleship/appSetting.json | 20 + 14 files changed, 620 insertions(+), 482 deletions(-) create mode 100644 ProjectBattleship/ProjectBattleship/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectBattleship/ProjectBattleship/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectBattleship/ProjectBattleship/appSetting.json diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs index 886bd27..36b24b7 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Battleship.Exceptions; namespace ProjectBattleship.CollectionGenericObjects; /// @@ -38,7 +39,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор @@ -99,13 +100,15 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawingShip? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawingShip? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException) { }; } - return bitmap; } - /// /// Вывод заднего фона /// diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs index bc92291..a8e9cc7 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Battleship.Exceptions; namespace ProjectBattleship.CollectionGenericObjects; @@ -41,7 +42,7 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { if (position < 0 || position >= _collection.Count) - return null; + throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) @@ -51,19 +52,21 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.Add(obj); return _collection.Count - 1; } - return -1; + throw new CollectionOverflowException(MaxCount); } public bool Insert(T obj, int position) { - if (_collection.Count + 1 > _maxCount || position < 0 || position >= _collection.Count) - return false; + if (_collection.Count + 1 > MaxCount) + throw new CollectionOverflowException(MaxCount); + if (position < 0 || position >= MaxCount) + throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); return true; } public T Remove(int position) { if (position < 0 || position >= _collection.Count) - return null; + throw new PositionOutOfCollectionException(position); T temp = _collection[position]; _collection.RemoveAt(position); return temp; diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs index bf4ca02..ebd1ceb 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -6,6 +6,8 @@ using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; +using Battleship.Exceptions; + namespace ProjectBattleship.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -58,8 +60,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects /// public T? Get(int position) { - if (position < 0 || position >= _collection.Length) - return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) @@ -72,12 +73,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; + throw new CollectionOverflowException(_collection.Length); } public bool Insert(T obj, int position) { if (position < 0 || position >= _collection.Length) // проверка позиции - return false; + throw new PositionOutOfCollectionException(position); if (_collection[position] == null) // Попытка вставить на указанную позицию { _collection[position] = obj; @@ -99,12 +100,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects return true; } } - return false; + throw new CollectionOverflowException(_collection.Length); } public T Remove(int position) { - if (position < 0 || position >= _collection.Length || _collection[position] == null) // проверка позиции и наличия объекта - return null; + if (position < 0 || position >= _collection.Length) // проверка позиции + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) + throw new ObjectNotFoundException(position); T temp = _collection[position]; _collection[position] = null; diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ShipDocks.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ShipDocks.cs index 68f1030..546c82d 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ShipDocks.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ShipDocks.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Security.AccessControl; using System.Text; using System.Threading.Tasks; +using Battleship.Exceptions; namespace ProjectBattleship.CollectionGenericObjects; @@ -27,32 +28,45 @@ namespace ProjectBattleship.CollectionGenericObjects; protected override void DrawBackground(Graphics g) { - Pen pen = new Pen(Color.Brown, 4); - int x = 0, y = 0; - while (y + _placeSizeHeight < _pictureHeight) + Pen pen = new(Color.Black); + for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) { - while (x + _placeSizeWidth < _pictureWidth) + for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) { - g.DrawLine(pen, x, y, x + _placeSizeWidth, y); - g.DrawLine(pen, x, y, x, y + _placeSizeHeight); - g.DrawLine(pen, x, y + _placeSizeHeight, x + _placeSizeWidth, y + _placeSizeHeight); - x += _placeSizeWidth + 50; + g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), + new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j)); + g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), + new(_placeSizeWidth * i, _placeSizeHeight * (j + 1))); } - y += _placeSizeHeight; - x = 0; + + g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), + new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight))); } } protected override void SetObjectsPosition() { - int count = 0; - for (int iy = _placeSizeHeight * 11 + 5; iy >= 0; iy -= _placeSizeHeight) + int n = 0; + for (int j = _pictureHeight / _placeSizeHeight - 1; j >= 0; j--) { - for (int ix = 5; ix + _placeSizeWidth + 50 < _pictureWidth; ix += _placeSizeWidth + 50) + for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) { - _collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(count)?.SetPosition(ix, iy); - count++; + try + { + DrawingShip? drawingTrans = _collection?.Get(n); + if (drawingTrans != null) + { + drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight); + drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); + } + } + catch (ObjectNotFoundException e) + { + } + catch (PositionOutOfCollectionException e) + { + } + n++; } } } diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs index 621ca3a..a4f85fa 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs @@ -1,6 +1,7 @@ using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.Drawnings; using System.Text; +using Battleship.Exceptions; namespace ProjectBattleship.CollectionGenericObjects; @@ -73,11 +74,11 @@ public class StorageCollection return null; } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -110,20 +111,19 @@ public class StorageCollection sb.Clear(); } } - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует"); } using (StreamReader sr = new StreamReader(filename)) { string? str; str = sr.ReadLine(); if (str != _collectionKey.ToString()) - return false; + throw new FormatException("В файле неверные данные"); _storages.Clear(); while ((str = sr.ReadLine()) != null) { @@ -136,7 +136,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -144,14 +144,22 @@ public class StorageCollection { if (elem?.CreateDrawningShip() is T ship) { - if (collection.Insert(ship) == -1) - return false; + try + { + if (collection.Insert(ship) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } } } _storages.Add(record[0], collection); } } - return true; } /// /// Создание коллекции по типу diff --git a/ProjectBattleship/ProjectBattleship/Exceptions/CollectionOverflowException.cs b/ProjectBattleship/ProjectBattleship/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..fc5b181 --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace Battleship.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/ProjectBattleship/ProjectBattleship/Exceptions/ObjectNotFoundException.cs b/ProjectBattleship/ProjectBattleship/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..6f76124 --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace Battleship.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/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs b/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..c243d55 --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace Battleship.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/ProjectBattleship/ProjectBattleship/FormShipCollection.Designer.cs b/ProjectBattleship/ProjectBattleship/FormShipCollection.Designer.cs index af1d2dd..4026aee 100644 --- a/ProjectBattleship/ProjectBattleship/FormShipCollection.Designer.cs +++ b/ProjectBattleship/ProjectBattleship/FormShipCollection.Designer.cs @@ -1,4 +1,4 @@ -namespace Battleship +namespace ProjectBattleship { partial class FormShipCollection { @@ -28,15 +28,8 @@ /// private void InitializeComponent() { - Tools = new GroupBox(); - panelCompanyTools = new Panel(); - buttonAddShip = new Button(); - buttonRefresh = new Button(); - maskedTextBox = new MaskedTextBox(); - buttonGoToTest = new Button(); - buttonDelShip = new Button(); - buttonCreateCompany = new Button(); - panelStorage = new Panel(); + pictureBox = new PictureBox(); + groupBoxTools = new GroupBox(); buttonCollectionDel = new Button(); listBoxCollection = new ListBox(); buttonCollectionAdd = new Button(); @@ -45,162 +38,89 @@ textBoxCollectionName = new TextBox(); labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); - pictureBox = new PictureBox(); + buttonCreateCompany = new Button(); + buttonRefresh = new Button(); + buttonGoToCheck = new Button(); + buttonRemoveShip = new Button(); + maskedTextBoxPosition = new MaskedTextBox(); + buttonAddShip = new Button(); menuStrip = new MenuStrip(); - файлToolStripMenuItem = new ToolStripMenuItem(); + fileToolStripMenuItem = new ToolStripMenuItem(); saveToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem(); - saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); - Tools.SuspendLayout(); - panelCompanyTools.SuspendLayout(); - panelStorage.SuspendLayout(); + saveFileDialog = new SaveFileDialog(); + panelCompanyTools = new Panel(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + groupBoxTools.SuspendLayout(); menuStrip.SuspendLayout(); + panelCompanyTools.SuspendLayout(); SuspendLayout(); // - // Tools + // pictureBox // - Tools.Controls.Add(panelCompanyTools); - Tools.Controls.Add(buttonCreateCompany); - Tools.Controls.Add(panelStorage); - Tools.Controls.Add(comboBoxSelectorCompany); - Tools.Dock = DockStyle.Right; - Tools.Location = new Point(1605, 40); - Tools.Name = "Tools"; - Tools.Size = new Size(488, 1224); - Tools.TabIndex = 0; - Tools.TabStop = false; - Tools.Text = "Инструменты"; + pictureBox.Dock = DockStyle.Left; + pictureBox.Location = new Point(0, 24); + pictureBox.Name = "pictureBox"; + pictureBox.Size = new Size(783, 592); + pictureBox.TabIndex = 0; + pictureBox.TabStop = false; // - // panelCompanyTools + // groupBoxTools // - panelCompanyTools.Controls.Add(buttonAddShip); - panelCompanyTools.Controls.Add(buttonRefresh); - panelCompanyTools.Controls.Add(maskedTextBox); - panelCompanyTools.Controls.Add(buttonGoToTest); - panelCompanyTools.Controls.Add(buttonDelShip); - panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(0, 686); - panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(488, 569); - panelCompanyTools.TabIndex = 8; - // - // buttonAddShip - // - buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddShip.Location = new Point(9, 3); - buttonAddShip.Name = "buttonAddShip"; - buttonAddShip.Size = new Size(473, 90); - buttonAddShip.TabIndex = 1; - buttonAddShip.Text = "Добавить корабль"; - buttonAddShip.UseVisualStyleBackColor = true; - buttonAddShip.Click += ButtonAddShip_Click; - // - // buttonRefresh - // - buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(16, 432); - buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(466, 90); - buttonRefresh.TabIndex = 6; - buttonRefresh.Text = "Обновить"; - buttonRefresh.UseVisualStyleBackColor = true; - buttonRefresh.Click += ButtonRefresh_Click; - // - // maskedTextBox - // - maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox.Location = new Point(12, 195); - maskedTextBox.Mask = "00"; - maskedTextBox.Name = "maskedTextBox"; - maskedTextBox.Size = new Size(470, 39); - maskedTextBox.TabIndex = 3; - maskedTextBox.ValidatingType = typeof(int); - // - // buttonGoToTest - // - buttonGoToTest.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToTest.Location = new Point(16, 336); - buttonGoToTest.Name = "buttonGoToTest"; - buttonGoToTest.Size = new Size(466, 90); - buttonGoToTest.TabIndex = 5; - buttonGoToTest.Text = "Передать на тест"; - buttonGoToTest.UseVisualStyleBackColor = true; - buttonGoToTest.Click += ButtonGoToTest_Click; - // - // buttonDelShip - // - buttonDelShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonDelShip.Location = new Point(12, 240); - buttonDelShip.Name = "buttonDelShip"; - buttonDelShip.Size = new Size(473, 90); - buttonDelShip.TabIndex = 4; - buttonDelShip.Text = "Удалить корабль"; - buttonDelShip.UseVisualStyleBackColor = true; - buttonDelShip.Click += ButtonDelShip_Click; - // - // buttonCreateCompany - // - buttonCreateCompany.Location = new Point(9, 612); - buttonCreateCompany.Name = "buttonCreateCompany"; - buttonCreateCompany.Size = new Size(473, 68); - buttonCreateCompany.TabIndex = 7; - buttonCreateCompany.Text = "Создать компанию"; - buttonCreateCompany.UseVisualStyleBackColor = true; - buttonCreateCompany.Click += ButtonCreateCompany_Click; - // - // panelStorage - // - panelStorage.Controls.Add(buttonCollectionDel); - panelStorage.Controls.Add(listBoxCollection); - panelStorage.Controls.Add(buttonCollectionAdd); - panelStorage.Controls.Add(radioButtonList); - panelStorage.Controls.Add(radioButtonMassive); - panelStorage.Controls.Add(textBoxCollectionName); - panelStorage.Controls.Add(labelCollectionName); - panelStorage.Dock = DockStyle.Top; - panelStorage.Location = new Point(3, 35); - panelStorage.Name = "panelStorage"; - panelStorage.Size = new Size(482, 512); - panelStorage.TabIndex = 7; + groupBoxTools.Controls.Add(buttonCreateCompany); + groupBoxTools.Controls.Add(buttonCollectionDel); + groupBoxTools.Controls.Add(listBoxCollection); + groupBoxTools.Controls.Add(buttonCollectionAdd); + groupBoxTools.Controls.Add(radioButtonList); + groupBoxTools.Controls.Add(radioButtonMassive); + groupBoxTools.Controls.Add(textBoxCollectionName); + groupBoxTools.Controls.Add(labelCollectionName); + groupBoxTools.Controls.Add(comboBoxSelectorCompany); + groupBoxTools.Dock = DockStyle.Right; + groupBoxTools.Location = new Point(784, 24); + groupBoxTools.Name = "groupBoxTools"; + groupBoxTools.Size = new Size(178, 592); + groupBoxTools.TabIndex = 0; + groupBoxTools.TabStop = false; + groupBoxTools.Text = "Инструменты"; // // buttonCollectionDel // - buttonCollectionDel.Location = new Point(6, 443); + buttonCollectionDel.Location = new Point(7, 232); buttonCollectionDel.Name = "buttonCollectionDel"; - buttonCollectionDel.Size = new Size(473, 46); - buttonCollectionDel.TabIndex = 6; + buttonCollectionDel.Size = new Size(167, 23); + buttonCollectionDel.TabIndex = 13; buttonCollectionDel.Text = "Удалить коллекцию"; buttonCollectionDel.UseVisualStyleBackColor = true; - buttonCollectionDel.Click += ButtonCollectionDel_Click; + buttonCollectionDel.Click += buttonCollectionDel_Click; // // listBoxCollection // listBoxCollection.FormattingEnabled = true; - listBoxCollection.ItemHeight = 32; - listBoxCollection.Location = new Point(9, 209); + listBoxCollection.ItemHeight = 15; + listBoxCollection.Location = new Point(7, 118); listBoxCollection.Name = "listBoxCollection"; - listBoxCollection.Size = new Size(473, 228); - listBoxCollection.TabIndex = 5; + listBoxCollection.Size = new Size(167, 109); + listBoxCollection.TabIndex = 12; // // buttonCollectionAdd // - buttonCollectionAdd.Location = new Point(6, 157); + buttonCollectionAdd.Location = new Point(7, 90); buttonCollectionAdd.Name = "buttonCollectionAdd"; - buttonCollectionAdd.Size = new Size(473, 46); - buttonCollectionAdd.TabIndex = 4; + buttonCollectionAdd.Size = new Size(167, 23); + buttonCollectionAdd.TabIndex = 11; buttonCollectionAdd.Text = "Добавить коллекцию"; buttonCollectionAdd.UseVisualStyleBackColor = true; - buttonCollectionAdd.Click += ButtonCollectionAdd_Click; + buttonCollectionAdd.Click += buttonCollectionAdd_Click; // // radioButtonList // radioButtonList.AutoSize = true; - radioButtonList.Location = new Point(306, 102); + radioButtonList.Location = new Point(102, 64); radioButtonList.Name = "radioButtonList"; - radioButtonList.Size = new Size(125, 36); - radioButtonList.TabIndex = 3; + radioButtonList.Size = new Size(66, 19); + radioButtonList.TabIndex = 10; radioButtonList.TabStop = true; radioButtonList.Text = "Список"; radioButtonList.UseVisualStyleBackColor = true; @@ -208,28 +128,28 @@ // radioButtonMassive // radioButtonMassive.AutoSize = true; - radioButtonMassive.Location = new Point(43, 102); + radioButtonMassive.Location = new Point(20, 64); radioButtonMassive.Name = "radioButtonMassive"; - radioButtonMassive.Size = new Size(128, 36); - radioButtonMassive.TabIndex = 2; + radioButtonMassive.Size = new Size(67, 19); + radioButtonMassive.TabIndex = 9; radioButtonMassive.TabStop = true; radioButtonMassive.Text = "Массив"; radioButtonMassive.UseVisualStyleBackColor = true; // // textBoxCollectionName // - textBoxCollectionName.Location = new Point(6, 48); + textBoxCollectionName.Location = new Point(7, 36); textBoxCollectionName.Name = "textBoxCollectionName"; - textBoxCollectionName.Size = new Size(476, 39); - textBoxCollectionName.TabIndex = 1; + textBoxCollectionName.Size = new Size(167, 23); + textBoxCollectionName.TabIndex = 8; // // labelCollectionName // labelCollectionName.AutoSize = true; - labelCollectionName.Location = new Point(128, 13); + labelCollectionName.Location = new Point(31, 18); labelCollectionName.Name = "labelCollectionName"; - labelCollectionName.Size = new Size(251, 32); - labelCollectionName.TabIndex = 0; + labelCollectionName.Size = new Size(125, 15); + labelCollectionName.TabIndex = 7; labelCollectionName.Text = "Название коллекции:"; // // comboBoxSelectorCompany @@ -237,111 +157,173 @@ comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.FormattingEnabled = true; - comboBoxSelectorCompany.Items.AddRange(new object[] { "Доки" }); - comboBoxSelectorCompany.Location = new Point(9, 566); + comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); + comboBoxSelectorCompany.Location = new Point(7, 274); comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; - comboBoxSelectorCompany.Size = new Size(476, 40); + comboBoxSelectorCompany.Size = new Size(166, 23); comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; // - // pictureBox + // buttonCreateCompany // - pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 40); - pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1605, 1224); - pictureBox.TabIndex = 1; - pictureBox.TabStop = false; + buttonCreateCompany.Location = new Point(9, 313); + buttonCreateCompany.Name = "buttonCreateCompany"; + buttonCreateCompany.Size = new Size(165, 23); + buttonCreateCompany.TabIndex = 14; + buttonCreateCompany.Text = "Создать компанию"; + buttonCreateCompany.UseVisualStyleBackColor = true; + buttonCreateCompany.Click += buttonCreateCompany_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(8, 208); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(164, 40); + buttonRefresh.TabIndex = 6; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += ButtonRefresh_Click; + // + // buttonGoToCheck + // + buttonGoToCheck.Location = new Point(8, 162); + buttonGoToCheck.Name = "buttonGoToCheck"; + buttonGoToCheck.Size = new Size(164, 40); + buttonGoToCheck.TabIndex = 5; + buttonGoToCheck.Text = "Передать на тесты"; + buttonGoToCheck.UseVisualStyleBackColor = true; + buttonGoToCheck.Click += ButtonGoToCheck_Click; + // + // buttonRemoveShip + // + buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonRemoveShip.Location = new Point(8, 116); + buttonRemoveShip.Name = "buttonRemoveShip"; + buttonRemoveShip.Size = new Size(164, 40); + buttonRemoveShip.TabIndex = 4; + buttonRemoveShip.Text = "Удалить корабль"; + buttonRemoveShip.UseVisualStyleBackColor = true; + buttonRemoveShip.Click += ButtonRemoveShip_Click; + // + // maskedTextBoxPosition + // + maskedTextBoxPosition.Location = new Point(8, 87); + maskedTextBoxPosition.Mask = "00"; + maskedTextBoxPosition.Name = "maskedTextBoxPosition"; + maskedTextBoxPosition.Size = new Size(164, 23); + maskedTextBoxPosition.TabIndex = 3; + // + // buttonAddShip + // + buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddShip.Location = new Point(8, 41); + buttonAddShip.Name = "buttonAddShip"; + buttonAddShip.Size = new Size(164, 40); + buttonAddShip.TabIndex = 1; + buttonAddShip.Text = "Добавление корабля"; + buttonAddShip.UseVisualStyleBackColor = true; + buttonAddShip.Click += ButtonAddShip_Click; // // menuStrip // - menuStrip.ImageScalingSize = new Size(32, 32); - menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(2093, 40); - menuStrip.TabIndex = 2; - menuStrip.Text = "menuStrip"; + menuStrip.Padding = new Padding(5, 2, 0, 2); + menuStrip.Size = new Size(962, 24); + menuStrip.TabIndex = 1; + menuStrip.Text = "menuStrip1"; // - // файлToolStripMenuItem + // fileToolStripMenuItem // - файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); - файлToolStripMenuItem.Name = "файлToolStripMenuItem"; - файлToolStripMenuItem.Size = new Size(90, 36); - файлToolStripMenuItem.Text = "Файл"; + fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + fileToolStripMenuItem.Size = new Size(48, 20); + fileToolStripMenuItem.Text = "Файл"; // // saveToolStripMenuItem // saveToolStripMenuItem.Name = "saveToolStripMenuItem"; - saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; - saveToolStripMenuItem.Size = new Size(343, 44); + saveToolStripMenuItem.Size = new Size(133, 22); saveToolStripMenuItem.Text = "Сохранить"; saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; // // loadToolStripMenuItem // loadToolStripMenuItem.Name = "loadToolStripMenuItem"; - loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; - loadToolStripMenuItem.Size = new Size(343, 44); + loadToolStripMenuItem.Size = new Size(133, 22); loadToolStripMenuItem.Text = "Загрузить"; loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; // - // saveFileDialog - // - saveFileDialog.Filter = "txt file | *.txt"; - // // openFileDialog // - openFileDialog.Filter = "txt file | *.txt"; + openFileDialog.FileName = "Ships"; + // + // saveFileDialog + // + saveFileDialog.FileName = "Ships"; + // + // panelCompanyTools + // + panelCompanyTools.Controls.Add(buttonAddShip); + panelCompanyTools.Controls.Add(maskedTextBoxPosition); + panelCompanyTools.Controls.Add(buttonRemoveShip); + panelCompanyTools.Controls.Add(buttonGoToCheck); + panelCompanyTools.Controls.Add(buttonRefresh); + panelCompanyTools.Enabled = false; + panelCompanyTools.Location = new Point(784, 366); + panelCompanyTools.Name = "panelCompanyTools"; + panelCompanyTools.Size = new Size(178, 250); + panelCompanyTools.TabIndex = 15; // // FormShipCollection // - AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(2093, 1264); + ClientSize = new Size(962, 616); + Controls.Add(panelCompanyTools); + Controls.Add(groupBoxTools); Controls.Add(pictureBox); - Controls.Add(Tools); Controls.Add(menuStrip); MainMenuStrip = menuStrip; Name = "FormShipCollection"; Text = "Коллекция кораблей"; - Tools.ResumeLayout(false); - panelCompanyTools.ResumeLayout(false); - panelCompanyTools.PerformLayout(); - panelStorage.ResumeLayout(false); - panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + groupBoxTools.ResumeLayout(false); + groupBoxTools.PerformLayout(); menuStrip.ResumeLayout(false); menuStrip.PerformLayout(); + panelCompanyTools.ResumeLayout(false); + panelCompanyTools.PerformLayout(); ResumeLayout(false); PerformLayout(); } #endregion - private GroupBox Tools; - private Button buttonAddShip; - private ComboBox comboBoxSelectorCompany; - private Button buttonDelShip; - private MaskedTextBox maskedTextBox; private PictureBox pictureBox; + private GroupBox groupBoxTools; + private ComboBox comboBoxSelectorCompany; + private Button buttonAddShip; + private MaskedTextBox maskedTextBoxPosition; private Button buttonRefresh; - private Button buttonGoToTest; - private Panel panelStorage; - private Label labelCollectionName; + private Button buttonGoToCheck; + private Button buttonRemoveShip; + private ListBox listBoxCollection; + private Button buttonCollectionAdd; private RadioButton radioButtonList; private RadioButton radioButtonMassive; private TextBox textBoxCollectionName; + private Label labelCollectionName; private Button buttonCollectionDel; - private ListBox listBoxCollection; - private Button buttonCollectionAdd; private Button buttonCreateCompany; - private Panel panelCompanyTools; private MenuStrip menuStrip; - private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem fileToolStripMenuItem; private ToolStripMenuItem saveToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem; - private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; + private Panel panelCompanyTools; } } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/FormShipCollection.cs b/ProjectBattleship/ProjectBattleship/FormShipCollection.cs index 502752a..e12c09b 100644 --- a/ProjectBattleship/ProjectBattleship/FormShipCollection.cs +++ b/ProjectBattleship/ProjectBattleship/FormShipCollection.cs @@ -1,265 +1,271 @@ -using ProjectBattleship; +using Battleship; using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.Drawnings; +using System.Windows.Forms; +using Battleship.Exceptions; +using Microsoft.Extensions.Logging; - -namespace Battleship; - -public partial class FormShipCollection : Form +namespace ProjectBattleship { - private readonly StorageCollection _storageCollection; - /// - /// Компания - /// - private AbstractCompany? _company = null; - /// - /// Конструктор - /// - public FormShipCollection() - { - InitializeComponent(); - _storageCollection = new(); - } - /// - /// Выбор компании - /// - /// - /// - private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) - { - panelCompanyTools.Enabled = false; - } - /// - /// Кнопка удаления корабля - /// - /// - /// - private void ButtonDelShip_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) - { - return; - } + public partial class FormShipCollection : Form - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + private readonly StorageCollection _storageCollection; + /// + /// Компания + /// + private AbstractCompany? _company = null; + private readonly ILogger _logger; + /// + /// Конструктор + /// + public FormShipCollection(ILogger logger) + { + InitializeComponent(); + _storageCollection = new(); + _logger = logger; + } + /// + /// Выбор компании + /// + /// + /// + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { - return; + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new ShipDocks(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); + break; + } + panelCompanyTools.Enabled = false; } - - int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) + /// + /// Добавление обычного автомобиля + /// + /// + /// + private void ButtonAddShip_Click(object sender, EventArgs e) { - MessageBox.Show("Объект удален"); + FormShipConfig form = new(); + form.Show(); + form.AddEvent(SetShip); + } + private void SetShip(DrawingShip? ship) + { + if (_company == null || ship == null) + return; + try + { + var res = _company + ship; + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); + pictureBox.Image = _company.Show(); + } + catch (CollectionOverflowException ex) + { + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } + } + private void ButtonRemoveShip_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) + { + return; + } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + + try + { + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удаление корабля по индексу {pos}", pos); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation("Не удалось удалить корабль из коллекции по индексу {pos}", pos); + } + } + catch (ObjectNotFoundException ex) + { + MessageBox.Show("Ошибка: отсутствует объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show("Ошибка: неправильная позиция"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + /// + /// Передача объекта в другую форму + /// + /// + /// + private void ButtonGoToCheck_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + DrawingShip? car = null; + int counter = 100; + while (car == null) + { + car = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + if (car == null) + { + return; + } + + FormBattleship form = new() + { + SetShip = car + }; + form.ShowDialog(); + } + /// + /// Перерисовка коллекции + /// + /// + /// + private void ButtonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + pictureBox.Image = _company.Show(); } - else - { - MessageBox.Show("Не удалось удалить объект"); - } - } - /// - /// Кнопка отправки на тест - /// - /// - /// - private void ButtonGoToTest_Click(object sender, EventArgs e) - { - if (_company == null) - { - return; - } - DrawingShip? ship = null; - int counter = 100; - while (ship == null) + private void buttonCreateCompany_Click(object sender, EventArgs e) { - ship = _company.GetRandomObject(); - counter--; - if (counter <= 0) + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { - break; + MessageBox.Show("Коллекция не выбрана"); + return; } - } - if (ship == null) - { - return; - } - - FormBattleship form = new() - { - SetShip = ship - }; - form.ShowDialog(); - - } - /// - /// Кнопка обновить - /// - /// - /// - private void ButtonRefresh_Click(object sender, EventArgs e) - { - if (_company == null) - { - return; - } - - pictureBox.Image = _company.Show(); - } - /// - /// Кнопка добавления корабля - /// - /// - /// - private void ButtonAddShip_Click(object sender, EventArgs e) - { - FormShipConfig form = new(); - form.AddEvent(SetShip); - form.Show(); - } - /// - /// Метод установки корабля в компанию - /// - private void SetShip(DrawingShip? ship) - { - if (_company == null) - return; - if (_company + ship != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } - /// - /// Добавление коллекции - /// - /// - /// - private void ButtonCollectionAdd_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) - { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) - { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); - } - /// - /// Удаление коллекции - /// - /// - /// - private void ButtonCollectionDel_Click(object sender, EventArgs e) - { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - return; - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); - } - /// - /// Обновление списка в listBoxCollection - /// - private void RerfreshListBoxItems() - { - listBoxCollection.Items.Clear(); - for (int i = 0; i < _storageCollection.Keys?.Count; ++i) - { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) + ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + if (collection == null) { - listBoxCollection.Items.Add(colName); + MessageBox.Show("Коллекция не проинициализирована"); + return; } + + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new ShipDocks(pictureBox.Width, pictureBox.Height, collection); + break; + } + panelCompanyTools.Enabled = true; + RerfreshListBoxItems(); } - } - /// - /// Создание компании - /// - /// - /// - private void ButtonCreateCompany_Click(object sender, EventArgs e) - { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + private void buttonCollectionDel_Click(object sender, EventArgs e) { - MessageBox.Show("Коллекция не выбрана"); - return; - } + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + return; + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + } + private void RerfreshListBoxItems() + { + listBoxCollection.Items.Clear(); + for (int i = 0; i < _storageCollection.Keys?.Count; ++i) + { + string? colName = _storageCollection.Keys?[i]; + if (!string.IsNullOrEmpty(colName)) + { + listBoxCollection.Items.Add(colName); + } + } + } + private void buttonCollectionAdd_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + { + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); + return; + } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; - if (collection == null) - { - MessageBox.Show("Коллекция не проинициализирована"); - return; - } + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text); + RerfreshListBoxItems(); + } - switch (comboBoxSelectorCompany.Text) + private void saveToolStripMenuItem_Click(object sender, EventArgs e) { - case "Доки": - _company = new ShipDocks(pictureBox.Width, pictureBox.Height, collection); - break; - } + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { - panelCompanyTools.Enabled = true; - RerfreshListBoxItems(); - } - /// - /// Обработка кнопки сохранения - /// - /// - /// - private void saveToolStripMenuItem_Click(object sender, EventArgs e) - { - if (saveFileDialog.ShowDialog() == DialogResult.OK) + try + { + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); + } + catch (Exception ex) + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + } + + private void loadToolStripMenuItem_Click(object sender, EventArgs e) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) - { - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else - { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - /// - /// Обработка кнопки загрузки - /// - /// - /// - private void loadToolStripMenuItem_Click(object sender, EventArgs e) - { - if (openFileDialog.ShowDialog() == DialogResult.OK) - { - if (_storageCollection.LoadData(openFileDialog.FileName)) - { - RerfreshListBoxItems(); - MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else - { - MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.LoadData(openFileDialog.FileName); + RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); + } + catch (Exception ex) + { + MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + } } } diff --git a/ProjectBattleship/ProjectBattleship/FormShipCollection.resx b/ProjectBattleship/ProjectBattleship/FormShipCollection.resx index 9340a84..4e47bf5 100644 --- a/ProjectBattleship/ProjectBattleship/FormShipCollection.resx +++ b/ProjectBattleship/ProjectBattleship/FormShipCollection.resx @@ -120,13 +120,10 @@ 17, 17 - - 204, 17 - - 447, 17 + 145, 17 - - 25 + + 307, 17 \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/Program.cs b/ProjectBattleship/ProjectBattleship/Program.cs index 72a21a8..b2a8154 100644 --- a/ProjectBattleship/ProjectBattleship/Program.cs +++ b/ProjectBattleship/ProjectBattleship/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; using Battleship; namespace ProjectBattleship @@ -13,7 +17,35 @@ namespace ProjectBattleship // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormShipCollection()); - } - } + 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 => + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true) + .Build(); + + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); + } + } } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj b/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj index 13ee123..6f2854e 100644 --- a/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj +++ b/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True diff --git a/ProjectBattleship/ProjectBattleship/appSetting.json b/ProjectBattleship/ProjectBattleship/appSetting.json new file mode 100644 index 0000000..165ec4f --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/appSetting.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Battleship" + } + } +}