From e59d527bfc511105a813d8549bfb6d9979dc7d87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=B7=D0=B0=D0=BC=D0=B0=D1=82=20=D0=98=D1=88=D1=82?= =?UTF-8?q?=D1=83=D0=B3=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sun, 19 May 2024 22:20:51 +0400 Subject: [PATCH] =?UTF-8?q?8=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 5 +- .../CollectionInfo.cs | 78 +++++++++++++++++++ .../ICollectionGenericObjects.cs | 8 +- .../ListGenericObjects.cs | 23 +++++- .../MassiveGenericObjects.cs | 31 +++++++- .../StorageCollection.cs | 52 +++++++------ .../Drawnings/DrawningBoatCompareByColor.cs | 38 +++++++++ .../Drawnings/DrawningBoatCompareByType.cs | 36 +++++++++ .../Drawnings/DrawningBoatEqutables.cs | 58 ++++++++++++++ .../ObjectAlreadyExistsException.cs | 22 ++++++ .../MotorBoat/FormBoatCollection.Designer.cs | 44 +++++++++-- MotorBoat/MotorBoat/FormBoatCollection.cs | 31 ++++++-- 12 files changed, 382 insertions(+), 44 deletions(-) create mode 100644 MotorBoat/MotorBoat/CollectionGenericObjects/CollectionInfo.cs create mode 100644 MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByColor.cs create mode 100644 MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByType.cs create mode 100644 MotorBoat/MotorBoat/Drawnings/DrawningBoatEqutables.cs create mode 100644 MotorBoat/MotorBoat/Exceptions/ObjectAlreadyExistsException.cs diff --git a/MotorBoat/MotorBoat/CollectionGenericObjects/AbstractCompany.cs b/MotorBoat/MotorBoat/CollectionGenericObjects/AbstractCompany.cs index 626a9df..d5ec72e 100644 --- a/MotorBoat/MotorBoat/CollectionGenericObjects/AbstractCompany.cs +++ b/MotorBoat/MotorBoat/CollectionGenericObjects/AbstractCompany.cs @@ -51,7 +51,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningBoat boat) { - return company._collection.Insert(boat); + return company._collection.Insert(boat, new DrawningBoatEqutables()); } /// /// Перегрузка оператора удаления для класса @@ -90,6 +90,9 @@ public abstract class AbstractCompany } return bitmap; } + + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод заднего фона /// diff --git a/MotorBoat/MotorBoat/CollectionGenericObjects/CollectionInfo.cs b/MotorBoat/MotorBoat/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..2a6868a --- /dev/null +++ b/MotorBoat/MotorBoat/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.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(); + } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs b/MotorBoat/MotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs index a0b9bad..6839284 100644 --- a/MotorBoat/MotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/MotorBoat/MotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -18,15 +18,17 @@ public interface ICollectionGenericObjects /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// Сравнение двух объеков /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция + /// /// Сравнение двух объеков /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции /// @@ -50,4 +52,6 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + void CollectionSort(IComparer comparer); } \ No newline at end of file diff --git a/MotorBoat/MotorBoat/CollectionGenericObjects/ListGenericObjects.cs b/MotorBoat/MotorBoat/CollectionGenericObjects/ListGenericObjects.cs index c2511c2..e6ae4da 100644 --- a/MotorBoat/MotorBoat/CollectionGenericObjects/ListGenericObjects.cs +++ b/MotorBoat/MotorBoat/CollectionGenericObjects/ListGenericObjects.cs @@ -51,17 +51,31 @@ public class ListGenericObjects : ICollectionGenericObjects if (_collection[position] == null) throw new ObjectNotFoundException(); return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyExistsException(); + } + } _collection.Add(obj); return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { if (Count == _maxCount) throw new CollectionOverflowException(Count); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyExistsException(position); + } + } _collection.Insert(position, obj); return position; } @@ -80,4 +94,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/MotorBoat/MotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs b/MotorBoat/MotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs index dcf7e29..64ff66d 100644 --- a/MotorBoat/MotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/MotorBoat/MotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -44,8 +44,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + if (comparer != null) + { + foreach (T? i in _collection) + { + if (comparer.Equals(i, obj)) + { + throw new ObjectAlreadyExistsException(i); + } + } + } for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -56,12 +66,22 @@ public class MassiveGenericObjects : ICollectionGenericObjects } throw new CollectionOverflowException(); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); } + if (comparer != null) + { + foreach (T? i in _collection) + { + if (comparer.Equals(i, obj)) + { + throw new ObjectAlreadyExistsException(i); + } + } + } if (_collection[position] == null) { _collection[position] = obj; @@ -88,7 +108,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } --temp; } - return -1; + throw new CollectionOverflowException(); } public T? Remove(int position) { @@ -106,4 +126,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/MotorBoat/MotorBoat/CollectionGenericObjects/StorageCollection.cs b/MotorBoat/MotorBoat/CollectionGenericObjects/StorageCollection.cs index dd0f08f..9e3a790 100644 --- a/MotorBoat/MotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/MotorBoat/MotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using MotorBoat.Drawnings; using MotorBoat.Exceptions; +using System.Data; namespace MotorBoat.CollectionGenericObjects; @@ -13,7 +14,7 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Ключевое слово, с которого должен начинаться файл @@ -33,14 +34,14 @@ public class StorageCollection /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Конструктор /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -49,17 +50,18 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (name == null || _storages.ContainsKey(name)) + CollectionInfo collectionInfo = new(name, collectionType, string.Empty); + if (name == null || _storages.ContainsKey(collectionInfo)) return; switch (collectionType) { case CollectionType.None: return; case CollectionType.Massive: - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); return; case CollectionType.List: - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); return; default: break; } @@ -71,8 +73,9 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (_storages.ContainsKey(name)) - _storages.Remove(name); + CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); } /// @@ -84,8 +87,9 @@ public class StorageCollection { get { - if (_storages.ContainsKey(name)) - return _storages[name]; + CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } @@ -99,7 +103,7 @@ public class StorageCollection { if (_storages.Count == 0) { - throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); + throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -108,7 +112,7 @@ public class StorageCollection using (StreamWriter writer = new(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { writer.Write(Environment.NewLine); // не сохраняем пустые коллекции @@ -118,8 +122,6 @@ public class StorageCollection } writer.Write(value.Key); writer.Write(_separatorForKeyValue); - writer.Write(value.Value.GetCollectionType); - writer.Write(_separatorForKeyValue); writer.Write(value.Value.MaxCount); writer.Write(_separatorForKeyValue); @@ -164,16 +166,20 @@ public class StorageCollection { string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции" + record[0]); CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? - throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ; - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, - StringSplitOptions.RemoveEmptyEntries); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType); + if (collection == null) + { + throw new InvalidOperationException("Не удалось создать коллекцию"); + } + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningBoat() is T boat) @@ -182,16 +188,16 @@ public class StorageCollection { if (collection.Insert(boat) == -1) { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]); } } catch (CollectionOverflowException ex) { - throw new CollectionOverflowException("Коллекция переполнена", ex); + throw new DataException("Коллекция переполнена", ex); } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByColor.cs b/MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByColor.cs new file mode 100644 index 0000000..d685ff4 --- /dev/null +++ b/MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByColor.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.Drawnings; +/// +/// Сравнение по цвету, скорости и весу +/// +public class DrawningBoatCompareByColor : IComparer +{ + public int Compare(DrawningBoat? x, DrawningBoat? y) + { + if (x == null || x.EntityBoat == null) + { + return 1; + } + + if (y == null || y.EntityBoat == null) + { + return -1; + } + + var bodycolorCompare = x.EntityBoat.BodyColor.Name.CompareTo(y.EntityBoat.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + + var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight); + } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByType.cs b/MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByType.cs new file mode 100644 index 0000000..95ef4dd --- /dev/null +++ b/MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByType.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.Drawnings; +/// +/// Сравнение по типу, скорости и весу +/// +public class DrawningBoatCompareByType : IComparer +{ + public int Compare(DrawningBoat? x, DrawningBoat? y) + { + if (x == null || x.EntityBoat == null) + { + return -1; + } + if (y == null || y.EntityBoat == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight); + } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/Drawnings/DrawningBoatEqutables.cs b/MotorBoat/MotorBoat/Drawnings/DrawningBoatEqutables.cs new file mode 100644 index 0000000..74dc134 --- /dev/null +++ b/MotorBoat/MotorBoat/Drawnings/DrawningBoatEqutables.cs @@ -0,0 +1,58 @@ +using MotorBoat.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace MotorBoat.Drawnings; + +public class DrawningBoatEqutables : IEqualityComparer +{ + public bool Equals(DrawningBoat? x, DrawningBoat? y) + { + if (x == null || x.EntityBoat == null) + { + return false; + } + if (y == null || y.EntityBoat == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityBoat.Speed != y.EntityBoat.Speed) + { + return false; + } + if (x.EntityBoat.Weight != y.EntityBoat.Weight) + { + return false; + } + if (x.EntityBoat.BodyColor != y.EntityBoat.BodyColor) + { + return false; + } + if (x is DrawningMotorBoat && y is DrawningMotorBoat) + { + EntityMotorBoat entityX = (EntityMotorBoat)x.EntityBoat; + EntityMotorBoat entityY = (EntityMotorBoat)y.EntityBoat; + if (entityX.Engine != entityY.Engine) + { + return false; + } + if (entityX.ProtectiveGlass != entityY.ProtectiveGlass) + { + return false; + } + if (entityX.AdditionalColor != entityY.AdditionalColor) + { + return false; + } + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningBoat? obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/Exceptions/ObjectAlreadyExistsException.cs b/MotorBoat/MotorBoat/Exceptions/ObjectAlreadyExistsException.cs new file mode 100644 index 0000000..5f89910 --- /dev/null +++ b/MotorBoat/MotorBoat/Exceptions/ObjectAlreadyExistsException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.Exceptions; + +/// +/// Класс, описывающий ошибку, что в коллекции уже есть такой элемент +/// +[Serializable] +public class ObjectAlreadyExistsException : ApplicationException +{ + public ObjectAlreadyExistsException(object i) : base("В коллекции уже есть такой элемент " + i) { } + public ObjectAlreadyExistsException() : base() { } + public ObjectAlreadyExistsException(string message) : base(message) { } + public ObjectAlreadyExistsException(string message, Exception exception) : base(message, exception) + { } + protected ObjectAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/FormBoatCollection.Designer.cs b/MotorBoat/MotorBoat/FormBoatCollection.Designer.cs index ba88c2a..03c8e45 100644 --- a/MotorBoat/MotorBoat/FormBoatCollection.Designer.cs +++ b/MotorBoat/MotorBoat/FormBoatCollection.Designer.cs @@ -30,6 +30,8 @@ { groupBoxTools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); buttonAddBoat = new Button(); maskedTextBoxPosition = new MaskedTextBox(); buttonRefresh = new Button(); @@ -68,13 +70,15 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(630, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(170, 512); + groupBoxTools.Size = new Size(170, 535); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddBoat); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonRefresh); @@ -83,9 +87,31 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 316); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(164, 193); + panelCompanyTools.Size = new Size(164, 221); panelCompanyTools.TabIndex = 8; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(6, 190); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(158, 25); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(6, 159); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(158, 25); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // buttonAddBoat // buttonAddBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; @@ -99,7 +125,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(3, 70); + maskedTextBoxPosition.Location = new Point(3, 36); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(158, 23); @@ -109,7 +135,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 162); + buttonRefresh.Location = new Point(3, 128); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(158, 25); buttonRefresh.TabIndex = 6; @@ -120,7 +146,7 @@ // buttonRemoveBoat // buttonRemoveBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveBoat.Location = new Point(3, 99); + buttonRemoveBoat.Location = new Point(3, 65); buttonRemoveBoat.Name = "buttonRemoveBoat"; buttonRemoveBoat.Size = new Size(158, 26); buttonRemoveBoat.TabIndex = 4; @@ -131,7 +157,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 131); + buttonGoToCheck.Location = new Point(3, 97); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(158, 25); buttonGoToCheck.TabIndex = 5; @@ -248,7 +274,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(630, 512); + pictureBox.Size = new Size(630, 535); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -297,7 +323,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 536); + ClientSize = new Size(800, 559); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -342,5 +368,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/MotorBoat/MotorBoat/FormBoatCollection.cs b/MotorBoat/MotorBoat/FormBoatCollection.cs index a2b7521..cf4eef3 100644 --- a/MotorBoat/MotorBoat/FormBoatCollection.cs +++ b/MotorBoat/MotorBoat/FormBoatCollection.cs @@ -77,6 +77,11 @@ public partial class FormBoatCollection : Form MessageBox.Show("Не удалось добавить объект"); _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } + catch (ObjectAlreadyExistsException) + { + MessageBox.Show("Такой объект уже существует"); + _logger.LogError("Ошибка: такой объект уже существует {0}", boat); + } } /// /// Удаление лодки @@ -199,10 +204,6 @@ public partial class FormBoatCollection : Form /// private void ButtonCollectionDel_Click(object sender, EventArgs e) { - // TODO прописать логику удаления элемента из коллекции - // нужно убедиться, что есть выбранная коллекция - // спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись - // удалить и обновить ListBox if (listBoxCollection.SelectedIndex < 0) { MessageBox.Show("Коллекция не выбрана"); @@ -227,7 +228,7 @@ public partial class FormBoatCollection : 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); @@ -311,4 +312,24 @@ public partial class FormBoatCollection : Form } } } + + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareBoats(new DrawningBoatCompareByType()); + } + + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareBoats(new DrawningBoatCompareByColor()); + } + + private void CompareBoats(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } }