From cdf9d4e47065a0397796d942056b41e8c0fd3ef7 Mon Sep 17 00:00:00 2001 From: pnevmoslon1 Date: Tue, 21 May 2024 02:50:07 +0400 Subject: [PATCH 1/3] lab7 --- .../ListGenericObjects.cs | 14 +- .../MassiveGenericObjects.cs | 30 +- .../StorageCollection.cs | 34 +- .../Exceptions/CollectionOverflowException.cs | 21 +- .../Exceptions/ObjectNotFoundException.cs | 23 +- .../PositionOutOfCollectionException.cs | 21 +- .../WarmlyShip/FormShipCollection.Designer.cs | 24 +- WarmlyShip/WarmlyShip/FormShipCollection.cs | 305 ++++++++++-------- WarmlyShip/WarmlyShip/Program.cs | 38 ++- WarmlyShip/WarmlyShip/WarmlyShip.csproj | 13 + WarmlyShip/WarmlyShip/nlog.config | 13 + 11 files changed, 309 insertions(+), 227 deletions(-) create mode 100644 WarmlyShip/WarmlyShip/nlog.config diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/ListGenericObjects.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/ListGenericObjects.cs index d9a63a5..c74f037 100644 --- a/WarmlyShip/WarmlyShip/CollectionGenericObjects/ListGenericObjects.cs +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace WarmlyShip.CollectionGenericObjects; +using WarmlyShip.Exceptions; + +namespace WarmlyShip.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects where T : class @@ -32,7 +34,7 @@ public class ListGenericObjects : ICollectionGenericObjects where T : clas { if (position < 0 || position >= Count) { - return null; + throw new PositionOutOfCollectionException(position); } return _collection[position]; @@ -42,7 +44,7 @@ public class ListGenericObjects : ICollectionGenericObjects where T : clas { if (Count == _maxCount) { - return -1; + throw new CollectionOverflowException(Count); } _collection.Add(obj); return Count; @@ -52,11 +54,11 @@ public class ListGenericObjects : ICollectionGenericObjects where T : clas { if (Count == _maxCount) { - return -1; + throw new CollectionOverflowException(Count); } if (position >= Count || position < 0) { - return -1; + throw new CollectionOverflowException(Count); } _collection.Insert(position, obj); return position; @@ -66,7 +68,7 @@ public class ListGenericObjects : ICollectionGenericObjects where T : clas { if (position >= Count || position < 0) { - return null; + throw new PositionOutOfCollectionException(position); } T obj = _collection[position]; _collection.RemoveAt(position); diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs index 094b059..5b9a5d8 100644 --- a/WarmlyShip/WarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,7 @@ -namespace WarmlyShip.CollectionGenericObjects; +using WarmlyShip.Exceptions; +using WarmlyShip.Scripts.Exceptions; + +namespace WarmlyShip.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects where T : class @@ -43,7 +46,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects // TODO проверка позиции if (position < 0 || position > Count) { - return null; + throw new PositionOutOfCollectionException(position); } return _collection[position]; @@ -61,20 +64,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - // TODO проверка позиции - // TODO проверка, что элемент массима по этой позиции пустой, - // если элемент массима по этой позиции не пустой, - // найти свободное место после этой позиции, если не найдено, - // то искать до - // TODO вставка + if (position < 0 || position >= Count) { - return -1; + throw new PositionOutOfCollectionException(position); } if (_collection[position] == null) @@ -103,20 +101,22 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(Count); } public T Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из массива, - // присвоив элементу массива значение null if (position >= Count || position < 0) { return null; + throw new PositionOutOfCollectionException(position); } - T obj = _collection[position]; + T? obj = _collection[position]; + if (obj == null) + { + throw new ObjectNotFoundException(position); + } _collection[position] = null; return obj; } diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/StorageCollection.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/StorageCollection.cs index 9d92867..0215be2 100644 --- a/WarmlyShip/WarmlyShip/CollectionGenericObjects/StorageCollection.cs +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using System.Text; using WarmlyShip.Drawnings; +using WarmlyShip.Exceptions; namespace WarmlyShip.CollectionGenericObjects; @@ -63,11 +64,11 @@ public class StorageCollection where T : DrawningShip return null; } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -112,8 +113,6 @@ public class StorageCollection where T : DrawningShip } } - - return true; } /// @@ -121,11 +120,11 @@ public class StorageCollection where T : DrawningShip /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) @@ -134,12 +133,12 @@ public class StorageCollection where T : DrawningShip if (str == null || str.Length == 0) { - return false; + throw new IOException("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new IOException("В файле неверные данные"); } _storages.Clear(); @@ -153,11 +152,8 @@ public class StorageCollection where T : DrawningShip } 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]); @@ -166,15 +162,21 @@ public class StorageCollection where T : DrawningShip { if (elem?.CreateDrawningShip() is T ship) { - if (collection.Insert(ship) == -1) + try { - return false; + if (collection.Insert(ship) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } - return true; } } diff --git a/WarmlyShip/WarmlyShip/Exceptions/CollectionOverflowException.cs b/WarmlyShip/WarmlyShip/Exceptions/CollectionOverflowException.cs index cdc3543..2df852c 100644 --- a/WarmlyShip/WarmlyShip/Exceptions/CollectionOverflowException.cs +++ b/WarmlyShip/WarmlyShip/Exceptions/CollectionOverflowException.cs @@ -1,15 +1,14 @@ using System.Runtime.Serialization; -namespace ProjectMonorail.Scripts.Exceptions -{ +namespace WarmlyShip.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) { } - } + +[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/WarmlyShip/WarmlyShip/Exceptions/ObjectNotFoundException.cs b/WarmlyShip/WarmlyShip/Exceptions/ObjectNotFoundException.cs index 1ad765c..0c95158 100644 --- a/WarmlyShip/WarmlyShip/Exceptions/ObjectNotFoundException.cs +++ b/WarmlyShip/WarmlyShip/Exceptions/ObjectNotFoundException.cs @@ -1,17 +1,14 @@ using System.Runtime.Serialization; -namespace ProjectMonorail.Scripts.Exceptions +namespace WarmlyShip.Scripts.Exceptions; + + +[Serializable] +public class ObjectNotFoundException : ApplicationException { - /// - /// Класс, описывающий ошибку, что по указанной позиции нет элемента - /// - [Serializable] - public class ObjectNotFoundException : ApplicationException - { - public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } - public ObjectNotFoundException() : base() { } - public ObjectNotFoundException(string message) : base(message) { } - public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } - protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } - } + 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/WarmlyShip/WarmlyShip/Exceptions/PositionOutOfCollectionException.cs b/WarmlyShip/WarmlyShip/Exceptions/PositionOutOfCollectionException.cs index 307d977..242158d 100644 --- a/WarmlyShip/WarmlyShip/Exceptions/PositionOutOfCollectionException.cs +++ b/WarmlyShip/WarmlyShip/Exceptions/PositionOutOfCollectionException.cs @@ -1,15 +1,14 @@ using System.Runtime.Serialization; -namespace WarmlyShip.Exceptions -{ +namespace WarmlyShip.Exceptions; - [Serializable] - public class PositionOutOfCollectionException : ApplicationException - { - public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { } - public PositionOutOfCollectionException() : base() { } - public PositionOutOfCollectionException(string message) : base(message) { } - public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } - protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } - } + +[Serializable] +public class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } } diff --git a/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs b/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs index cbb9dfc..a2e8501 100644 --- a/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs +++ b/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs @@ -41,7 +41,7 @@ listBoxCollection = new ListBox(); buttonCollectionAdd = new Button(); radioButtonList = new RadioButton(); - radioButtonMssive = new RadioButton(); + radioButtonMassive = new RadioButton(); textBoxCollectionName = new TextBox(); labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); @@ -155,7 +155,7 @@ panelStoreage.Controls.Add(listBoxCollection); panelStoreage.Controls.Add(buttonCollectionAdd); panelStoreage.Controls.Add(radioButtonList); - panelStoreage.Controls.Add(radioButtonMssive); + panelStoreage.Controls.Add(radioButtonMassive); panelStoreage.Controls.Add(textBoxCollectionName); panelStoreage.Controls.Add(labelCollectionName); panelStoreage.Dock = DockStyle.Top; @@ -204,16 +204,16 @@ radioButtonList.Text = "Список"; radioButtonList.UseVisualStyleBackColor = true; // - // radioButtonMssive + // radioButtonMassive // - radioButtonMssive.AutoSize = true; - radioButtonMssive.Location = new Point(3, 47); - radioButtonMssive.Name = "radioButtonMssive"; - radioButtonMssive.Size = new Size(67, 19); - radioButtonMssive.TabIndex = 2; - radioButtonMssive.TabStop = true; - radioButtonMssive.Text = "Массив"; - radioButtonMssive.UseVisualStyleBackColor = true; + radioButtonMassive.AutoSize = true; + radioButtonMassive.Location = new Point(3, 47); + radioButtonMassive.Name = "radioButtonMassive"; + radioButtonMassive.Size = new Size(67, 19); + radioButtonMassive.TabIndex = 2; + radioButtonMassive.TabStop = true; + radioButtonMassive.Text = "Массив"; + radioButtonMassive.UseVisualStyleBackColor = true; // // textBoxCollectionName // @@ -327,7 +327,7 @@ private Label labelCollectionName; private Button buttonCollectionAdd; private RadioButton radioButtonList; - private RadioButton radioButtonMssive; + private RadioButton radioButtonMassive; private TextBox textBoxCollectionName; private Button buttonCreateCompany; private Button buttonCollectionDel; diff --git a/WarmlyShip/WarmlyShip/FormShipCollection.cs b/WarmlyShip/WarmlyShip/FormShipCollection.cs index 2e12e78..57644ae 100644 --- a/WarmlyShip/WarmlyShip/FormShipCollection.cs +++ b/WarmlyShip/WarmlyShip/FormShipCollection.cs @@ -9,40 +9,48 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WarmlyShip.Drawnings; +using Microsoft.Extensions.Logging; +using WarmlyShip.Exceptions; +using WarmlyShip.Scripts.Exceptions; -namespace WarmlyShip +namespace WarmlyShip; + +public partial class FormShipCollection : Form { - public partial class FormShipCollection : Form + public FormShipCollection(ILogger logger) { - public FormShipCollection() - { - InitializeComponent(); - _storageCollection = new(); - } - private AbstractCompany? _company = null; - private readonly StorageCollection _storageCollection; + InitializeComponent(); + _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма создалась"); + } + private AbstractCompany? _company = null; + private readonly StorageCollection _storageCollection; + private readonly ILogger _logger; - private void ComboBoxSelectorCompany_SelectedIndexChanged(Object sender, EventArgs e) - { - panelCompanyTools.Enabled = false; - } + private void ComboBoxSelectorCompany_SelectedIndexChanged(Object sender, EventArgs e) + { + panelCompanyTools.Enabled = false; + } - private void ButtonAddShip_Click(object sender, EventArgs e) - { - FormShipConfig form = new(); + private void ButtonAddShip_Click(object sender, EventArgs e) + { + FormShipConfig form = new(); - form.Show(); - form.AddEvent(SetShip); - } + form.Show(); + form.AddEvent(SetShip); + } - private void SetShip(DrawningShip ship) + private void SetShip(DrawningShip ship) + { + try { if (_company == null || ship == null) { @@ -53,47 +61,58 @@ namespace WarmlyShip { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Добавлен объект: " + ship.GetDataForSave()); } } - - - private void ButtonRemoveShip_Click(object sender, EventArgs e) + catch (ObjectNotFoundException ex) { } + catch (CollectionOverflowException ex) { - if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) - { - return; - } + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - return; - } - int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + 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; + } + + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + try + { if (_company - pos != null) { MessageBox.Show("Объект удален"); pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation("Удален объект по позиции " + pos); } } - - private void ButtonGoToCheck_Click(object sender, EventArgs e) + catch (Exception ex) { - if (_company == null) - { - return; - } + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } - DrawningShip? ship = null; - int counter = 100; + private void ButtonGoToCheck_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + DrawningShip? ship = null; + int counter = 100; + try + { while (ship == null) { ship = _company.GetRandomObject(); @@ -115,28 +134,34 @@ namespace WarmlyShip }; form.ShowDialog(); } - - private void ButtonRefresh_Click(object sender, EventArgs e) + catch (Exception ex) { - if (_company == null) - { - return; - } + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - pictureBox.Image = _company.Show(); + private void ButtonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; } + pictureBox.Image = _company.Show(); + } - private void ButtonCollectionAdd_Click(object sender, EventArgs e) + + private void ButtonCollectionAdd_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + { + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + try { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMssive.Checked)) - { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - CollectionType collectionType = CollectionType.None; - if (radioButtonMssive.Checked) + if (radioButtonMassive.Checked) { collectionType = CollectionType.Massive; } @@ -147,94 +172,112 @@ namespace WarmlyShip _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RefreshListBoxItems(); + _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } - - private void ButtonCollectionDel_Click(object sender, EventArgs e) + catch (Exception ex) { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + private void ButtonCollectionDel_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + try + { if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RefreshListBoxItems(); - - } - - private void ButtonCreateCompany_Click(object sender, EventArgs e) - { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } - - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty]; - if (collection == null) - { - MessageBox.Show("Коллекция не проинициализирована"); - return; - } - - switch (comboBoxSelectorCompany.Text) - { - case "Хранилище": - _company = new PortForShips(pictureBox.Width, pictureBox.Height, collection); - break; - } - - panelCompanyTools.Enabled = true; + _logger.LogInformation("Коллекция " + listBoxCollection.SelectedItem.ToString() + " удалена"); RefreshListBoxItems(); } - private void RefreshListBoxItems() + catch (Exception ex) { - 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); - } - } + _logger.LogError("Ошибка: {Message}", ex.Message); } - private void saveToolStripMenuItem_Click(object sender, EventArgs e) + } + + private void ButtonCreateCompany_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null) { - if (saveFileDialog.ShowDialog() == DialogResult.OK) - { - if (_storageCollection.SaveData(saveFileDialog.FileName)) - { - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else - { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + MessageBox.Show("Коллекция не выбрана"); + return; } - private void loadToolStripMenuItem_Click(object sender, EventArgs e) + ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty]; + if (collection == null) { - if (openFileDialog.ShowDialog() == DialogResult.OK) + MessageBox.Show("Коллекция не проинициализирована"); + return; + } + + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new PortForShips(pictureBox.Width, pictureBox.Height, collection); + break; + } + + panelCompanyTools.Enabled = true; + RefreshListBoxItems(); + } + private void RefreshListBoxItems() + { + listBoxCollection.Items.Clear(); + for (int i = 0; i < _storageCollection.Keys?.Count; ++i) + { + string? colName = _storageCollection.Keys?[i]; + if (!string.IsNullOrEmpty(colName)) { - if (_storageCollection.LoadData(openFileDialog.FileName)) - { - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else - { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - } + listBoxCollection.Items.Add(colName); } - RefreshListBoxItems(); } } - + + 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(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + } + + private void loadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.LoadData(openFileDialog.FileName); + 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); + } + } + RefreshListBoxItems(); + } } + diff --git a/WarmlyShip/WarmlyShip/Program.cs b/WarmlyShip/WarmlyShip/Program.cs index 2dda87b..955b133 100644 --- a/WarmlyShip/WarmlyShip/Program.cs +++ b/WarmlyShip/WarmlyShip/Program.cs @@ -1,17 +1,31 @@ -namespace WarmlyShip +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using System.Drawing; +namespace WarmlyShip; + +internal static class Program { - internal static class Program + + [STAThread] + static void Main() { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() + + ApplicationConfiguration.Initialize(); + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = + services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - Application.Run(new FormShipCollection()); - } + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); } } \ No newline at end of file diff --git a/WarmlyShip/WarmlyShip/WarmlyShip.csproj b/WarmlyShip/WarmlyShip/WarmlyShip.csproj index 244387d..0d75e87 100644 --- a/WarmlyShip/WarmlyShip/WarmlyShip.csproj +++ b/WarmlyShip/WarmlyShip/WarmlyShip.csproj @@ -8,6 +8,13 @@ enable + + + + + + + True @@ -23,4 +30,10 @@ + + + Always + + + \ No newline at end of file diff --git a/WarmlyShip/WarmlyShip/nlog.config b/WarmlyShip/WarmlyShip/nlog.config new file mode 100644 index 0000000..ce9a7ec --- /dev/null +++ b/WarmlyShip/WarmlyShip/nlog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file From 5d986d68299a0f18fb6026c31a1809b7def8f647 Mon Sep 17 00:00:00 2001 From: pnevmoslon1 Date: Tue, 21 May 2024 03:11:17 +0400 Subject: [PATCH 2/3] lab 7 --- .../WarmlyShip/CollectionGenericObjects/AbstractCompany.cs | 2 +- WarmlyShip/WarmlyShip/Entities/EntityWarmlyShip.cs | 2 +- WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/AbstractCompany.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/AbstractCompany.cs index 7030b16..44ad219 100644 --- a/WarmlyShip/WarmlyShip/CollectionGenericObjects/AbstractCompany.cs +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/AbstractCompany.cs @@ -21,7 +21,7 @@ public abstract class AbstractCompany protected ICollectionGenericObjects _collection = null; - private int GetMaxCount => _pictureWidth * _pictureHeight / ((_placeSizeWidth + _placeSizeWidth /2) * _placeSizeHeight) - 1; + private int GetMaxCount => _pictureWidth * _pictureHeight / ((_placeSizeWidth + _placeSizeWidth /2) * _placeSizeHeight) - 2; public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) diff --git a/WarmlyShip/WarmlyShip/Entities/EntityWarmlyShip.cs b/WarmlyShip/WarmlyShip/Entities/EntityWarmlyShip.cs index 546a2cd..6f49cfc 100644 --- a/WarmlyShip/WarmlyShip/Entities/EntityWarmlyShip.cs +++ b/WarmlyShip/WarmlyShip/Entities/EntityWarmlyShip.cs @@ -48,7 +48,7 @@ public class EntityWarmlyShip : EntityShip Pipes = pipes; } - public virtual string[] GetStringRepresentation() + public override string[] GetStringRepresentation() { return new[] { nameof(EntityShip), Speed.ToString(), Weight.ToString(), BodyColor.Name, SeckondColor.Name, FuelHole.ToString(), Pipes.ToString() }; diff --git a/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs b/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs index a2e8501..3ca428c 100644 --- a/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs +++ b/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs @@ -68,7 +68,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(961, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(187, 497); + groupBoxTools.Size = new Size(187, 532); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -245,7 +245,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(961, 497); + pictureBox.Size = new Size(961, 532); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // @@ -294,7 +294,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1148, 521); + ClientSize = new Size(1148, 556); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); From a6e7f208d898edddeac69f5c7c563f8eb4d3873c Mon Sep 17 00:00:00 2001 From: pnevmoslon1 Date: Tue, 21 May 2024 04:38:22 +0400 Subject: [PATCH 3/3] lab8 --- .../AbstractCompany.cs | 4 +- .../CollectionInfo.cs | 76 +++++++++++++++++++ .../ICollectionGenericObjects.cs | 6 +- .../ListGenericObjects.cs | 24 +++++- .../MassiveGenericObjects.cs | 21 ++++- .../StorageCollection.cs | 56 +++++++------- .../Drawnings/DrawningShipCompareByColor.cs | 20 +++++ .../Drawnings/DrawningShipCompareByType.cs | 19 +++++ .../Drawnings/DrawningShipEqutables.cs | 42 ++++++++++ .../Exceptions/ObjectNotUniqeException.cs | 18 +++++ .../WarmlyShip/FormShipCollection.Designer.cs | 50 +++++++++--- WarmlyShip/WarmlyShip/FormShipCollection.cs | 36 ++++++--- 12 files changed, 313 insertions(+), 59 deletions(-) create mode 100644 WarmlyShip/WarmlyShip/CollectionGenericObjects/CollectionInfo.cs create mode 100644 WarmlyShip/WarmlyShip/Drawnings/DrawningShipCompareByColor.cs create mode 100644 WarmlyShip/WarmlyShip/Drawnings/DrawningShipCompareByType.cs create mode 100644 WarmlyShip/WarmlyShip/Drawnings/DrawningShipEqutables.cs create mode 100644 WarmlyShip/WarmlyShip/Exceptions/ObjectNotUniqeException.cs diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/AbstractCompany.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/AbstractCompany.cs index 44ad219..e6d3ca5 100644 --- a/WarmlyShip/WarmlyShip/CollectionGenericObjects/AbstractCompany.cs +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/AbstractCompany.cs @@ -1,5 +1,6 @@ using WarmlyShip.CollectionGenericObjects; using WarmlyShip.Drawnings; +using WarmlyShip.Drawningsp; namespace WarmlyShip.CollectionGenericObjects; @@ -35,7 +36,7 @@ public abstract class AbstractCompany public static int operator +(AbstractCompany company, DrawningShip ship) { - return company._collection.Insert(ship); + return company._collection.Insert(ship, new DrawningShipEqutables()); } public static DrawningShip operator -(AbstractCompany company, int position) @@ -67,6 +68,7 @@ public abstract class AbstractCompany return bitmap; } + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); protected abstract void DrawBackgroud(Graphics g); diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/CollectionInfo.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..62b1f8d --- /dev/null +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,76 @@ +namespace WarmlyShip.CollectionGenericObjects; + +/// +/// Класс, хранящий информацию о коллекции +/// +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + + /// + /// Описание + /// + public string Description { get; private set; } + + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) + { + return null; + } + + return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty); + } + + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/ICollectionGenericObjects.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/ICollectionGenericObjects.cs index 5cf5db0..887afe0 100644 --- a/WarmlyShip/WarmlyShip/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -11,10 +11,10 @@ public interface ICollectionGenericObjects int MaxCount { set; get; } - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); T Remove(int position); @@ -26,4 +26,6 @@ public interface ICollectionGenericObjects IEnumerable GetItems(); + + void CollectionSort(IComparer comparer); } diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/ListGenericObjects.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/ListGenericObjects.cs index c74f037..0fc0806 100644 --- a/WarmlyShip/WarmlyShip/CollectionGenericObjects/ListGenericObjects.cs +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/ListGenericObjects.cs @@ -40,8 +40,16 @@ public class ListGenericObjects : ICollectionGenericObjects where T : clas return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectNotUniqueException(); + } + } + if (Count == _maxCount) { throw new CollectionOverflowException(Count); @@ -50,8 +58,16 @@ public class ListGenericObjects : ICollectionGenericObjects where T : clas return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectNotUniqueException(); + } + } + if (Count == _maxCount) { throw new CollectionOverflowException(Count); @@ -82,4 +98,8 @@ public class ListGenericObjects : ICollectionGenericObjects where T : clas yield return _collection[i]; } } + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs index 5b9a5d8..e4ead91 100644 --- a/WarmlyShip/WarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using WarmlyShip.Exceptions; +using WarmlyShip.Drawnings; +using WarmlyShip.Exceptions; using WarmlyShip.Scripts.Exceptions; namespace WarmlyShip.CollectionGenericObjects; @@ -52,8 +53,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningShip, item as DrawningShip)) + { + throw new ObjectNotUniqueException(); + } + } + } // TODO вставка в свободное место набора for (int i = 0; i < Count; i++) { @@ -67,7 +78,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { if (position < 0 || position >= Count) @@ -127,4 +138,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/WarmlyShip/WarmlyShip/CollectionGenericObjects/StorageCollection.cs b/WarmlyShip/WarmlyShip/CollectionGenericObjects/StorageCollection.cs index 0215be2..51a0371 100644 --- a/WarmlyShip/WarmlyShip/CollectionGenericObjects/StorageCollection.cs +++ b/WarmlyShip/WarmlyShip/CollectionGenericObjects/StorageCollection.cs @@ -8,13 +8,13 @@ namespace WarmlyShip.CollectionGenericObjects; public class StorageCollection where T : DrawningShip { - readonly Dictionary> _storages; + readonly Dictionary> _storages; - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); private readonly string _collectionKey = "CollectionStorage"; - + private readonly string _separatorForKeyValue = "|"; @@ -23,33 +23,36 @@ public class StorageCollection where T : DrawningShip public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } - + public void AddCollection(string name, CollectionType collectionType) { - if (_storages.ContainsKey(name) || collectionType == CollectionType.None) + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + + if (_storages.ContainsKey(collectionInfo) || collectionInfo.CollectionType == CollectionType.None) { return; } - switch (collectionType) + switch (collectionInfo.CollectionType) { case CollectionType.Massive: - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); break; case CollectionType.List: - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); break; } } public void DelCollection(string name) { - if (_storages.ContainsKey(name) && name != null) + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo) && collectionInfo != null) { - _storages.Remove(name); + _storages.Remove(collectionInfo); } } @@ -57,9 +60,10 @@ public class StorageCollection where T : DrawningShip { get { - if (_storages.ContainsKey(name)) + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) { - return _storages[name]; + return _storages[collectionInfo]; } return null; } @@ -79,7 +83,7 @@ public class StorageCollection where T : DrawningShip using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { StringBuilder sb = new(); @@ -92,8 +96,6 @@ public class StorageCollection where T : DrawningShip sb.Append(value.Key); sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); sb.Append(value.Value.MaxCount); sb.Append(_separatorForKeyValue); @@ -111,15 +113,9 @@ public class StorageCollection where T : DrawningShip writer.Write(sb); } - } } - /// - /// Загрузка информации по автомобилям в хранилище из файла - /// - /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных public void LoadData(string filename) { if (!File.Exists(filename)) @@ -146,18 +142,18 @@ public class StorageCollection where T : DrawningShip while ((strs = fs.ReadLine()) != null) { string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? - throw new Exception("Не удалось определить тип коллекции: " + record[1]); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции:" + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось определить тип коллекции: " + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningShip() is T ship) @@ -175,7 +171,7 @@ public class StorageCollection where T : DrawningShip } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/WarmlyShip/WarmlyShip/Drawnings/DrawningShipCompareByColor.cs b/WarmlyShip/WarmlyShip/Drawnings/DrawningShipCompareByColor.cs new file mode 100644 index 0000000..3541a51 --- /dev/null +++ b/WarmlyShip/WarmlyShip/Drawnings/DrawningShipCompareByColor.cs @@ -0,0 +1,20 @@ +namespace WarmlyShip.Drawnings; + + +public class DrawningShipCompareByColor : IComparer +{ + public int Compare(DrawningShip? x, DrawningShip? y) + { + if (x == null || x.EntityShip == null) return 1; + + if (y == null || y.EntityShip == null) return -1; + + var bodycolorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name); + if (bodycolorCompare != 0) return bodycolorCompare; + + var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed); + if (speedCompare != 0) return speedCompare; + + return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight); + } +} diff --git a/WarmlyShip/WarmlyShip/Drawnings/DrawningShipCompareByType.cs b/WarmlyShip/WarmlyShip/Drawnings/DrawningShipCompareByType.cs new file mode 100644 index 0000000..bdfd591 --- /dev/null +++ b/WarmlyShip/WarmlyShip/Drawnings/DrawningShipCompareByType.cs @@ -0,0 +1,19 @@ +namespace WarmlyShip.Drawnings; + + +public class DrawningShipCompareByType : IComparer +{ + public int Compare(DrawningShip? x, DrawningShip? y) + { + if (x == null || x.EntityShip == null) return 1; + + if (y == null || y.EntityShip == null) return -1; + + if (x.GetType().Name != y.GetType().Name) return x.GetType().Name.CompareTo(y.GetType().Name); + + var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed); + if (speedCompare != 0) return speedCompare; + + return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight); + } +} diff --git a/WarmlyShip/WarmlyShip/Drawnings/DrawningShipEqutables.cs b/WarmlyShip/WarmlyShip/Drawnings/DrawningShipEqutables.cs new file mode 100644 index 0000000..4a19627 --- /dev/null +++ b/WarmlyShip/WarmlyShip/Drawnings/DrawningShipEqutables.cs @@ -0,0 +1,42 @@ +using WarmlyShip.Entities; +using System.Diagnostics.CodeAnalysis; +using WarmlyShip.Drawnings; + +namespace WarmlyShip.Drawningsp; + + +public class DrawningShipEqutables : IEqualityComparer +{ + public bool Equals(DrawningShip? x, DrawningShip? y) + { + if (x == null || x.EntityShip == null) return false; + + if (y == null || y.EntityShip == null) return false; + + if (x.GetType().Name != y.GetType().Name) return false; + + if (x.EntityShip.Speed != y.EntityShip.Speed) return false; + + if (x.EntityShip.Weight != y.EntityShip.Weight) return false; + + if (x.EntityShip.BodyColor != y.EntityShip.BodyColor) return false; + + if (x is DrawningWarmlyShip bigX && y is DrawningWarmlyShip bigY) + { + + EntityWarmlyShip _x = (EntityWarmlyShip)x.EntityShip; + EntityWarmlyShip _y = (EntityWarmlyShip)y.EntityShip; + + if (_x.FuelHole != _y.FuelHole) return false; + if (_x.Pipes != _y.Pipes) return false; + if (_x.SeckondColor != _y.SeckondColor) return false; + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningShip obj) + { + return obj.GetHashCode(); + } +} diff --git a/WarmlyShip/WarmlyShip/Exceptions/ObjectNotUniqeException.cs b/WarmlyShip/WarmlyShip/Exceptions/ObjectNotUniqeException.cs new file mode 100644 index 0000000..30828f2 --- /dev/null +++ b/WarmlyShip/WarmlyShip/Exceptions/ObjectNotUniqeException.cs @@ -0,0 +1,18 @@ +using System.Runtime.Serialization; + +namespace WarmlyShip.Exceptions; + + +[Serializable] +internal class ObjectNotUniqueException : ApplicationException +{ + public ObjectNotUniqueException(int i) : base("В коллекции есть такой же элемент на позиции: " + i) { } + + public ObjectNotUniqueException() : base() { } + + public ObjectNotUniqueException(string message) : base(message) { } + + public ObjectNotUniqueException(string message, Exception exception) : base(message, exception) { } + + protected ObjectNotUniqueException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} \ No newline at end of file diff --git a/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs b/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs index 3ca428c..d31dd34 100644 --- a/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs +++ b/WarmlyShip/WarmlyShip/FormShipCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStoreage.SuspendLayout(); @@ -75,15 +77,17 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddShip); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonRemoveShip); panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(6, 292); + panelCompanyTools.Location = new Point(6, 283); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(178, 234); + panelCompanyTools.Size = new Size(178, 249); panelCompanyTools.TabIndex = 4; // // buttonAddShip @@ -100,7 +104,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.None; - buttonRefresh.Location = new Point(0, 198); + buttonRefresh.Location = new Point(3, 162); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(169, 28); buttonRefresh.TabIndex = 7; @@ -110,7 +114,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(3, 87); + maskedTextBoxPosition.Location = new Point(3, 45); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(169, 23); @@ -120,7 +124,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 158); + buttonGoToCheck.Location = new Point(3, 116); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(166, 36); buttonGoToCheck.TabIndex = 6; @@ -131,7 +135,7 @@ // buttonRemoveShip // buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveShip.Location = new Point(3, 116); + buttonRemoveShip.Location = new Point(3, 74); buttonRemoveShip.Name = "buttonRemoveShip"; buttonRemoveShip.Size = new Size(166, 36); buttonRemoveShip.TabIndex = 5; @@ -141,7 +145,7 @@ // // buttonCreateCompany // - buttonCreateCompany.Location = new Point(6, 263); + buttonCreateCompany.Location = new Point(6, 254); buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Size = new Size(175, 23); buttonCreateCompany.TabIndex = 7; @@ -161,12 +165,12 @@ panelStoreage.Dock = DockStyle.Top; panelStoreage.Location = new Point(3, 19); panelStoreage.Name = "panelStoreage"; - panelStoreage.Size = new Size(181, 213); + panelStoreage.Size = new Size(181, 200); panelStoreage.TabIndex = 9; // // buttonCollectionDel // - buttonCollectionDel.Location = new Point(0, 186); + buttonCollectionDel.Location = new Point(0, 171); buttonCollectionDel.Name = "buttonCollectionDel"; buttonCollectionDel.Size = new Size(175, 23); buttonCollectionDel.TabIndex = 6; @@ -180,7 +184,7 @@ listBoxCollection.ItemHeight = 15; listBoxCollection.Location = new Point(3, 101); listBoxCollection.Name = "listBoxCollection"; - listBoxCollection.Size = new Size(175, 79); + listBoxCollection.Size = new Size(175, 64); listBoxCollection.TabIndex = 5; // // buttonCollectionAdd @@ -234,7 +238,7 @@ // comboBoxSelectorCompany // comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); - comboBoxSelectorCompany.Location = new Point(6, 234); + comboBoxSelectorCompany.Location = new Point(6, 225); comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Size = new Size(175, 23); comboBoxSelectorCompany.TabIndex = 8; @@ -290,6 +294,28 @@ openFileDialog.FileName = "openFileDialog1"; openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.None; + buttonSortByType.Location = new Point(3, 196); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(169, 22); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.None; + buttonSortByColor.Location = new Point(3, 221); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(169, 22); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // // FormShipCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -339,5 +365,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/WarmlyShip/WarmlyShip/FormShipCollection.cs b/WarmlyShip/WarmlyShip/FormShipCollection.cs index 57644ae..55ff922 100644 --- a/WarmlyShip/WarmlyShip/FormShipCollection.cs +++ b/WarmlyShip/WarmlyShip/FormShipCollection.cs @@ -1,13 +1,4 @@ using WarmlyShip.CollectionGenericObjects; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; using WarmlyShip.Drawnings; using Microsoft.Extensions.Logging; using WarmlyShip.Exceptions; @@ -70,6 +61,11 @@ public partial class FormShipCollection : Form MessageBox.Show(ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectNotUniqueException ex) + { + MessageBox.Show("Такой объект уже присутствует в коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } @@ -235,7 +231,7 @@ public partial class FormShipCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; + string? colName = _storageCollection.Keys?[i].Name; if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); @@ -279,5 +275,25 @@ public partial class FormShipCollection : Form } RefreshListBoxItems(); } + + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareShips(new DrawningShipCompareByType()); + } + + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareShips(new DrawningShipCompareByColor()); + } + private void CompareShips(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } }