From 58dc4abc49d16ab2248ba18bbba7444ab018dde4 Mon Sep 17 00:00:00 2001 From: artur-kalimullin <144933634+artur-kalimullin@users.noreply.github.com> Date: Sat, 25 May 2024 00:01:15 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=968?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 8 +- .../CollectionInfo.cs | 76 +++++++++++++ .../ICollectionGenericObjects.cs | 13 ++- .../ListGenericObjects.cs | 22 +++- .../MassiveGenericObjects.cs | 34 +++++- .../StorageCollection.cs | 55 +++++----- .../DrawningAirCraftCompareByColor.cs | 27 +++++ .../DrawningAirCraftCompareByType.cs | 31 ++++++ .../Drawnings/DrawningAirCraftEqutables.cs | 68 ++++++++++++ .../ObjectAlreadyExistsException.cs | 16 +++ .../FormAirCraftCollection.Designer.cs | 48 ++++++-- .../FormAirCraftCollection.cs | 103 ++++++++++++------ .../ProjectAirFighter.csproj | 4 +- 13 files changed, 427 insertions(+), 78 deletions(-) create mode 100644 ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftCompareByColor.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftCompareByType.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftEqutables.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectAlreadyExistsException.cs diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs index 0965886..e8f0a22 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs @@ -60,7 +60,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningAirCraft aircraft) { - return company._collection.Insert(aircraft); + return company._collection.Insert(aircraft, new DrawningAirCraftEqutables()); } /// @@ -110,6 +110,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод заднего фона /// diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..6ed31db --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,76 @@ +namespace ProjectAirFighter.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/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs index 826af1b..d712ca8 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -25,16 +25,18 @@ public interface ICollectionGenericObjects /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция + /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -60,5 +62,10 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); -} + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); +} \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs index b7fc4d7..cd54d51 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -48,16 +48,30 @@ 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 + 1 > _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 + 1 > _maxCount) throw new CollectionOverflowException(Count); if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position); + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyExistsException(position); + } + } _collection.Insert(position, obj); return position; } @@ -76,4 +90,8 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index 849f17b..6a308a2 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -57,12 +57,22 @@ 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? i in _collection) + { + if (comparer.Equals(i, obj)) + { + throw new ObjectAlreadyExistsException(i); + } + } + } return Insert(obj, 0); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { if (position < 0 || position >= Count) @@ -70,6 +80,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new PositionOutOfCollectionException(); } + if (comparer != null) + { + foreach (T? i in _collection) + { + if (comparer.Equals(i, obj)) + { + throw new ObjectAlreadyExistsException(i); + } + } + } + if (_collection[position] != null) { bool pushed = false; @@ -122,4 +143,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + List lst = [.. _collection]; + lst.Sort(comparer.Compare); + for (int i = 0; i < _collection.Length; ++i) + { + _collection[i] = lst[i]; + } + } } \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs index 1937879..7439aa5 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs @@ -15,12 +15,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -42,7 +42,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -52,13 +52,13 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - - if (_storages.ContainsKey(name)) return; + CollectionInfo collectionInfo = new(name, collectionType, string.Empty); + if (_storages.ContainsKey(collectionInfo)) return; if (collectionType == CollectionType.None) return; else if (collectionType == CollectionType.Massive) - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); else if (collectionType == CollectionType.List) - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); } /// @@ -67,8 +67,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); } /// @@ -80,8 +81,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; } } @@ -105,7 +107,7 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { StringBuilder sb = new(); sb.Append(Environment.NewLine); @@ -118,10 +120,9 @@ public class StorageCollection sb.Append(value.Key); sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); sb.Append(value.Value.MaxCount); sb.Append(_separatorForKeyValue); + foreach (T? item in value.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; @@ -134,6 +135,7 @@ public class StorageCollection } writer.Write(sb); } + } } @@ -145,7 +147,7 @@ public class StorageCollection { if (!File.Exists(filename)) { - throw new FileNotFoundException($"{filename} не существует"); + throw new FileNotFoundException("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) @@ -153,29 +155,31 @@ public class StorageCollection string str = fs.ReadLine(); if (str == null || str.Length == 0) { - throw new FileFormatException("Файл не подходит"); + throw new ArgumentException("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - throw new IOException("В файле неверные данные"); + throw new InvalidDataException("В файле неверные данные"); } _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) { string[] record = strs.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); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType); if (collection == null) { - throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); + throw new InvalidOperationException("Не удалось создать коллекцию"); } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningAirCraft() is T aircraft) @@ -184,7 +188,7 @@ public class StorageCollection { if (collection.Insert(aircraft) == -1) { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]); } } catch (CollectionOverflowException ex) @@ -193,7 +197,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } @@ -212,5 +216,4 @@ public class StorageCollection _ => null, }; } -} - +} \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftCompareByColor.cs b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftCompareByColor.cs new file mode 100644 index 0000000..026613c --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftCompareByColor.cs @@ -0,0 +1,27 @@ +namespace ProjectAirFighter.Drawnings; +public class DrawningAirCraftCompareByColor : IComparer +{ + public int Compare(DrawningAirCraft? x, DrawningAirCraft? y) + { + if (x == null || x.EntityAirCraft == null) + { + return 1; + } + + if (y == null || y.EntityAirCraft == null) + { + return -1; + } + var bodycolorCompare = x.EntityAirCraft.BodyColor.Name.CompareTo(y.EntityAirCraft.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityAirCraft.Speed.CompareTo(y.EntityAirCraft.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityAirCraft.Weight.CompareTo(y.EntityAirCraft.Weight); + } +} \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftCompareByType.cs b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftCompareByType.cs new file mode 100644 index 0000000..9f71754 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftCompareByType.cs @@ -0,0 +1,31 @@ +using ProjectAirFighter.Drawnings; + +public class DrawingAirCraftCompareByType : IComparer +{ + public int Compare(DrawningAirCraft? x, DrawningAirCraft? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityAirCraft == null) + { + return 1; + } + + if (y == null || y.EntityAirCraft == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityAirCraft.Speed.CompareTo(y.EntityAirCraft.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityAirCraft.Weight.CompareTo(y.EntityAirCraft.Weight); + } +} \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftEqutables.cs b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftEqutables.cs new file mode 100644 index 0000000..3efc0fb --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirCraftEqutables.cs @@ -0,0 +1,68 @@ +using ProjectAirFighter.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectAirFighter.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningAirCraftEqutables : IEqualityComparer +{ + public bool Equals(DrawningAirCraft? x, DrawningAirCraft? y) + { + if (x == null || x.EntityAirCraft == null) + { + return false; + } + + if (y == null || y.EntityAirCraft == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityAirCraft.Speed != y.EntityAirCraft.Speed) + { + return false; + } + + if (x.EntityAirCraft.Weight != y.EntityAirCraft.Weight) + { + return false; + } + + if (x.EntityAirCraft.BodyColor != y.EntityAirCraft.BodyColor) + { + return false; + } + + if (x is DrawningAirFighter && y is DrawningAirFighter) + { + EntityAirFighter entityX = (EntityAirFighter)x.EntityAirCraft; + EntityAirFighter entityY = (EntityAirFighter)y.EntityAirCraft; + if (entityX.Pgo != entityY.Pgo) + { + return false; + } + if (entityX.Rockets != entityY.Rockets) + { + return false; + } + if (entityX.AdditionalColor != entityY.AdditionalColor) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningAirCraft obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectAlreadyExistsException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectAlreadyExistsException.cs new file mode 100644 index 0000000..4101bb3 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectAlreadyExistsException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectAirFighter.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) { } +} diff --git a/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.Designer.cs b/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.Designer.cs index fd19444..79ddab0 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.Designer.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBoxTools.SuspendLayout(); panelStorage.SuspendLayout(); panelCompanyTools.SuspendLayout(); @@ -68,7 +70,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(828, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(215, 594); + groupBoxTools.Size = new Size(215, 657); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -76,7 +78,7 @@ // buttonCreateCompany // buttonCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonCreateCompany.Location = new Point(17, 316); + buttonCreateCompany.Location = new Point(17, 311); buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Size = new Size(186, 35); buttonCreateCompany.TabIndex = 8; @@ -180,6 +182,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddAirCraft); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonRefresh); @@ -188,13 +192,13 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(6, 352); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(203, 270); + panelCompanyTools.Size = new Size(203, 299); panelCompanyTools.TabIndex = 9; // // buttonAddAirCraft // buttonAddAirCraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddAirCraft.Location = new Point(11, 21); + buttonAddAirCraft.Location = new Point(11, 5); buttonAddAirCraft.Name = "buttonAddAirCraft"; buttonAddAirCraft.Size = new Size(186, 49); buttonAddAirCraft.TabIndex = 1; @@ -204,7 +208,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(11, 85); + maskedTextBoxPosition.Location = new Point(11, 60); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(186, 27); @@ -214,7 +218,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(11, 203); + buttonRefresh.Location = new Point(11, 178); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(186, 31); buttonRefresh.TabIndex = 6; @@ -225,7 +229,7 @@ // buttonRemoveAirCraft // buttonRemoveAirCraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveAirCraft.Location = new Point(11, 118); + buttonRemoveAirCraft.Location = new Point(11, 93); buttonRemoveAirCraft.Name = "buttonRemoveAirCraft"; buttonRemoveAirCraft.Size = new Size(186, 38); buttonRemoveAirCraft.TabIndex = 4; @@ -236,7 +240,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(11, 162); + buttonGoToCheck.Location = new Point(11, 137); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(186, 35); buttonGoToCheck.TabIndex = 5; @@ -249,7 +253,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(828, 594); + pictureBox.Size = new Size(828, 657); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -294,11 +298,33 @@ // openFileDialog.Filter = "txt file|*.txt"; // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(11, 215); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(186, 35); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(11, 256); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(186, 35); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // // FormAirCraftCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1043, 622); + ClientSize = new Size(1043, 685); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -343,5 +369,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/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs b/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs index df39433..11d59fb 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs @@ -2,6 +2,7 @@ using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings; using ProjectAirFighter.Exceptions; +using System.Xml.Linq; namespace ProjectAirFighter; @@ -77,7 +78,12 @@ public partial class FormAirCraftCollection : Form catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); - _logger.LogError($"Не удалось добавить объект: {ex.Message}"); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); + } + catch (ObjectAlreadyExistsException) + { + MessageBox.Show("Такой объект уже существует"); + _logger.LogError("Ошибка: такой объект уже существует {0}", aircraft); } } @@ -90,7 +96,7 @@ public partial class FormAirCraftCollection : Form { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { - _logger.LogError("Удаление объекта из несуществующей коллекции"); + _logger.LogWarning("Удаление объекта из несуществующей коллекции"); return; } @@ -104,18 +110,18 @@ public partial class FormAirCraftCollection : Form { object decrementObject = _company - pos; MessageBox.Show("Объект удален"); - _logger.LogInformation($"Удален объект по позиции {pos}"); + _logger.LogInformation($"Удален по позиции {pos}"); pictureBox.Image = _company.Show(); } - catch (ObjectNotFoundException) + catch (ObjectNotFoundException ex) { MessageBox.Show("Объект не найден"); - _logger.LogError($"Удаление не найденного объекта в позиции {pos} "); + _logger.LogWarning($"Удаление не найденного объекта в позиции {pos} "); } - catch (PositionOutOfCollectionException) + catch (PositionOutOfCollectionException ex) { MessageBox.Show("Удаление вне рамках коллекции"); - _logger.LogError($"Удаление объекта за пределами коллекции {pos} "); + _logger.LogWarning($"Удаление объекта за пределами коллекции {pos} "); } } @@ -130,33 +136,29 @@ public partial class FormAirCraftCollection : Form { return; } - try + + DrawningAirCraft? aircraft = null; + int counter = 100; + while (aircraft == null) { - DrawningAirCraft? aircraft = null; - int counter = 100; - while (aircraft == null) + aircraft = _company.GetRandomObject(); + counter--; + if (counter <= 0) { - aircraft = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } + break; } - if (aircraft == null) - { - return; - } - FormAirFighter form = new() - { - SetAirCraft = aircraft - }; - form.ShowDialog(); } - catch (ObjectNotFoundException) + + if (aircraft == null) { - _logger.LogError("Ошибка при передаче объекта на FormAirFighter"); + return; } + + FormAirFighter form = new() + { + SetAirCraft = aircraft + }; + form.ShowDialog(); } /// @@ -184,7 +186,7 @@ public partial class FormAirCraftCollection : Form if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Не заполненная коллекция"); + _logger.LogWarning("Не заполненная коллекция"); return; } @@ -213,7 +215,7 @@ public partial class FormAirCraftCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); - _logger.LogError("Удаление невыбранной коллекции"); + _logger.LogWarning("Удаление невыбранной коллекции"); return; } string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty; @@ -234,7 +236,7 @@ public partial class FormAirCraftCollection : 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); @@ -251,7 +253,7 @@ public partial class FormAirCraftCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); - _logger.LogError("Создание компании невыбранной коллекции"); + _logger.LogWarning("Создание компании невыбранной коллекции"); return; } @@ -259,7 +261,7 @@ public partial class FormAirCraftCollection : Form if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); - _logger.LogError("Не удалось инициализировать коллекцию"); + _logger.LogWarning("Не удалось инициализировать коллекцию"); return; } @@ -320,4 +322,39 @@ public partial class FormAirCraftCollection : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareAirCraft(new DrawingAirCraftCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareAirCraft(new DrawningAirCraftCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareAirCraft(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj b/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj index d5a50d2..c99afc3 100644 --- a/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj +++ b/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj @@ -1,5 +1,7 @@  - + + preview + WinExe net7.0-windows -- 2.25.1 From a053dafaeae7ccb5653343ae172e40f689b2e364 Mon Sep 17 00:00:00 2001 From: artur-kalimullin <144933634+artur-kalimullin@users.noreply.github.com> Date: Sat, 25 May 2024 00:18:24 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CollectionGenericObjects/StorageCollection.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs index 7439aa5..6a92a15 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs @@ -147,7 +147,7 @@ public class StorageCollection { if (!File.Exists(filename)) { - throw new FileNotFoundException("Файл не существует"); + throw new FileNotFoundException($"{filename} не существует"); } using (StreamReader fs = File.OpenText(filename)) @@ -155,11 +155,11 @@ public class StorageCollection string str = fs.ReadLine(); if (str == null || str.Length == 0) { - throw new ArgumentException("В файле нет данных"); + throw new FileFormatException("Файл не подходит"); } if (!str.StartsWith(_collectionKey)) { - throw new InvalidDataException("В файле неверные данные"); + throw new IOException("В файле неверные данные"); } _storages.Clear(); string strs = ""; -- 2.25.1 From 621db43a11070e54113821422273054a0baf7579 Mon Sep 17 00:00:00 2001 From: artur-kalimullin <144933634+artur-kalimullin@users.noreply.github.com> Date: Sat, 25 May 2024 10:02:12 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FormAirCraftCollection.cs | 61 ++++++++++--------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs b/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs index 11d59fb..2a8613c 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs @@ -2,7 +2,6 @@ using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings; using ProjectAirFighter.Exceptions; -using System.Xml.Linq; namespace ProjectAirFighter; @@ -78,7 +77,7 @@ public partial class FormAirCraftCollection : Form catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); - _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); + _logger.LogError($"Не удалось добавить объект: {ex.Message}"); } catch (ObjectAlreadyExistsException) { @@ -96,7 +95,7 @@ public partial class FormAirCraftCollection : Form { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { - _logger.LogWarning("Удаление объекта из несуществующей коллекции"); + _logger.LogError("Удаление объекта из несуществующей коллекции"); return; } @@ -110,18 +109,18 @@ public partial class FormAirCraftCollection : Form { object decrementObject = _company - pos; MessageBox.Show("Объект удален"); - _logger.LogInformation($"Удален по позиции {pos}"); + _logger.LogInformation($"Удален объект по позиции {pos}"); pictureBox.Image = _company.Show(); } - catch (ObjectNotFoundException ex) + catch (ObjectNotFoundException) { MessageBox.Show("Объект не найден"); - _logger.LogWarning($"Удаление не найденного объекта в позиции {pos} "); + _logger.LogError($"Удаление не найденного объекта в позиции {pos} "); } - catch (PositionOutOfCollectionException ex) + catch (PositionOutOfCollectionException) { MessageBox.Show("Удаление вне рамках коллекции"); - _logger.LogWarning($"Удаление объекта за пределами коллекции {pos} "); + _logger.LogError($"Удаление объекта за пределами коллекции {pos} "); } } @@ -136,29 +135,33 @@ public partial class FormAirCraftCollection : Form { return; } - - DrawningAirCraft? aircraft = null; - int counter = 100; - while (aircraft == null) + try { - aircraft = _company.GetRandomObject(); - counter--; - if (counter <= 0) + DrawningAirCraft? aircraft = null; + int counter = 100; + while (aircraft == null) { - break; + aircraft = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + if (aircraft == null) + { + return; + } + FormAirFighter form = new() + { + SetAirCraft = aircraft + }; + form.ShowDialog(); } - - if (aircraft == null) + catch (ObjectNotFoundException) { - return; + _logger.LogError("Ошибка при передаче объекта на FormAirFighter"); } - - FormAirFighter form = new() - { - SetAirCraft = aircraft - }; - form.ShowDialog(); } /// @@ -186,7 +189,7 @@ public partial class FormAirCraftCollection : Form if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogWarning("Не заполненная коллекция"); + _logger.LogError("Не заполненная коллекция"); return; } @@ -215,7 +218,7 @@ public partial class FormAirCraftCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); - _logger.LogWarning("Удаление невыбранной коллекции"); + _logger.LogError("Удаление невыбранной коллекции"); return; } string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty; @@ -253,7 +256,7 @@ public partial class FormAirCraftCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); - _logger.LogWarning("Создание компании невыбранной коллекции"); + _logger.LogError("Создание компании невыбранной коллекции"); return; } @@ -261,7 +264,7 @@ public partial class FormAirCraftCollection : Form if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); - _logger.LogWarning("Не удалось инициализировать коллекцию"); + _logger.LogError("Не удалось инициализировать коллекцию"); return; } -- 2.25.1