From c1149954f4597bd9694df1ae25bcb13b970d284b Mon Sep 17 00:00:00 2001 From: mar-va Date: Mon, 10 Jun 2024 00:58:29 +0400 Subject: [PATCH] Lab8 --- .../AbstractCompany.cs | 8 +- .../CollectionInfo.cs | 77 ++++++++ .../ICollectionGenericObjects.cs | 10 +- .../ListGenericObjects.cs | 56 ++++-- .../MassiveGenericObjects.cs | 77 +++++--- .../StorageCollection.cs | 155 ++++++++------- .../Drawnings/DrawningBusCompareByColor.cs | 33 ++++ .../Drawnings/DrawningBusCompareByType.cs | 38 ++++ .../Drawnings/DrawningBusEqutables.cs | 80 ++++++++ .../Entities/EntityAccordionBus.cs | 5 +- .../ProjectAccordionBus/Entities/EntityBus.cs | 6 +- .../Exceptions/ObjectNotUniqueException.cs | 20 ++ .../FormBusCollection.Designer.cs | 51 +++-- .../ProjectAccordionBus/FormBusCollection.cs | 181 +++++++----------- 14 files changed, 561 insertions(+), 236 deletions(-) create mode 100644 ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusCompareByColor.cs create mode 100644 ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusCompareByType.cs create mode 100644 ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusEqutables.cs create mode 100644 ProjectAccordionBus/ProjectAccordionBus/Exceptions/ObjectNotUniqueException.cs diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs index 7e66306..053dff6 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs @@ -33,7 +33,7 @@ public abstract class AbstractCompany public static int operator +(AbstractCompany company, DrawningBus bus) { - return company._collection.Insert(bus); + return company._collection.Insert(bus, new DrawningBusEqutables()); } public static DrawningBus operator -(AbstractCompany company, int position) @@ -53,7 +53,6 @@ public abstract class AbstractCompany Graphics graphics = Graphics.FromImage(bitmap); DrawBackground(graphics); - for (int i = 0; i < (_collection?.Count ?? 0); i++) { DrawningBus? obj = _collection?.Get(i); @@ -64,6 +63,11 @@ public abstract class AbstractCompany return bitmap; } + public void Sort(IComparer comparer) + { + _collection?.CollectionSort(comparer); + } + protected abstract void DrawBackground(Graphics g); protected abstract void SetObjectPosition(int position, int MaxPos, DrawningBus? bus); diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/CollectionInfo.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..6c214f8 --- /dev/null +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,77 @@ +namespace ProjectAccordionBus.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/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs index 927d76b..ac8c2f5 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -29,14 +29,14 @@ public interface ICollectionGenericObjects /// /// /// - 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); /// /// Удаление объекта из коллекции с конкретной позиции @@ -62,5 +62,11 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs index 3c42b3f..303f6d3 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs @@ -1,9 +1,5 @@ using ProjectAccordionBus.Exceptions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using ProjectAirbus.Exceptions; namespace ProjectAccordionBus.CollectionGenericObjects; @@ -14,7 +10,7 @@ public class ListGenericObjects : ICollectionGenericObjects private int _maxCount; public int MaxCount { - get => _maxCount; + get =>_maxCount; set { if (value > 0) @@ -36,28 +32,57 @@ public class ListGenericObjects : ICollectionGenericObjects public T Get(int position) { - if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } 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 ObjectNotUniqueException(); + } + } + if (Count == _maxCount) + { + throw new CollectionOverflowException(Count); + } _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 ObjectNotUniqueException(); + } + } + if (Count == _maxCount) + { + throw new CollectionOverflowException(Count); + } + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } _collection.Insert(position, obj); return position; } public T? Remove(int position) { - if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } T obj = _collection[position]; _collection.RemoveAt(position); return obj; @@ -70,4 +95,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs index 3b4397a..d1e890e 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,9 +1,6 @@ using ProjectAccordionBus.Exceptions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using ProjectAirbus.Exceptions; +using ProjectAccordionBus.Drawnings; namespace ProjectAccordionBus.CollectionGenericObjects; @@ -61,8 +58,19 @@ 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 DrawningBus, item as DrawningBus)) + { + throw new ObjectNotUniqueException(); + } + } + } + // TODO вставка в свободное место набора for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -75,44 +83,56 @@ 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 >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) { _collection[position] = obj; return position; } - int index = position + 1; - while (index < _collection.Length) + else { - if (_collection[index] == null) + for (int i = position + 1; i < Count; i++) { - _collection[index] = obj; - return index; + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } } - ++index; - } - index = position - 1; - while (index >= 0) - { - if (_collection[index] == null) + + for (int i = 0; i < position; i++) { - _collection[index] = obj; - return index; + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } } - --index; } + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) throw new ObjectNotFoundException(position); - T? temp = _collection[position]; + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } + + T? obj = _collection[position]; + if (obj == null) + { + throw new ObjectNotFoundException(position); + } _collection[position] = null; - return temp; + return obj; } public IEnumerable GetItems() @@ -122,5 +142,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs index 9c8f4c8..c1df02f 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs @@ -1,10 +1,6 @@ using ProjectAccordionBus.Drawnings; using ProjectAccordionBus.CollectionGenericObjects; -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; using ProjectAccordionBus.Exceptions; namespace ProjectAccordionBus.CollectionGenericObjects; @@ -15,12 +11,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; - + readonly Dictionary> _storages; + /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -41,7 +37,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -51,19 +47,21 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (name == null || _storages.ContainsKey(name)) - return; - switch (collectionType) + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + + if (_storages.ContainsKey(collectionInfo) || collectionInfo.CollectionType == CollectionType.None) + { + return; + } + + switch (collectionInfo.CollectionType) { - case CollectionType.None: - return; case CollectionType.Massive: - _storages[name] = new MassiveGenericObjects(); - return; + _storages[collectionInfo] = new MassiveGenericObjects(); + break; case CollectionType.List: - _storages[name] = new ListGenericObjects(); - return; - default: break; + _storages[collectionInfo] = new ListGenericObjects(); + break; } } /// @@ -72,8 +70,11 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (_storages.ContainsKey(name)) - _storages.Remove(name); + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo) && collectionInfo != null) + { + _storages.Remove(collectionInfo); + } } /// @@ -85,11 +86,12 @@ public class StorageCollection { get { - if (name == "") + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) { - return null; + return _storages[collectionInfo]; } - return _storages[name]; + return null; } } @@ -97,29 +99,32 @@ public class StorageCollection { if (_storages.Count == 0) { - throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } + if (File.Exists(filename)) { File.Delete(filename); } - using (StreamWriter writer = new(filename)) + + using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { - writer.Write(Environment.NewLine); + StringBuilder sb = new(); + + sb.Append(Environment.NewLine); // не сохраняем пустые коллекции if (value.Value.Count == 0) { continue; } - writer.Write(value.Key); - writer.Write(_separatorForKeyValue); - writer.Write(value.Value.GetCollectionType); - writer.Write(_separatorForKeyValue); - writer.Write(value.Value.MaxCount); - writer.Write(_separatorForKeyValue); + + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) { @@ -128,56 +133,65 @@ public class StorageCollection { continue; } - writer.Write(data); - writer.Write(_separatorItems); + + sb.Append(data); + sb.Append(_separatorItems); } + + writer.Write(sb); } } } + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла public void LoadData(string filename) { if (!File.Exists(filename)) { - throw new FileNotFoundException($"{filename} не существует"); + throw new FileNotFoundException("Файл не существует"); } - using (StreamReader reader = new(filename)) - { - string line = reader.ReadLine(); - if (line == null || line.Length == 0) - { - throw new IOException("Файл не подходит"); - } - if (!line.Equals(_collectionKey)) - { + using (StreamReader fs = File.OpenText(filename)) + { + string str = fs.ReadLine(); + + if (str == null || str.Length == 0) + { + throw new IOException("В файле нет данных"); + } + + if (!str.StartsWith(_collectionKey)) + { throw new IOException("В файле неверные данные"); } + _storages.Clear(); - while ((line = reader.ReadLine()) != null) + string strs = ""; + while ((strs = fs.ReadLine()) != null) { - string[] record = line.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new Exception("Не удалось создать коллекцию"); - } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, - StringSplitOptions.RemoveEmptyEntries); + + 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]); + + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBus() is T armoredCar) + if (elem?.CreateDrawningBus() is T airbus) { try { - if (collection.Insert(armoredCar) == -1) + if (collection.Insert(airbus) == -1) { throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); } @@ -188,24 +202,23 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } /// - /// Создание коллекции по типу + /// Создание коллекции по типа /// /// /// - private static ICollectionGenericObjects? - CreateCollection(CollectionType collectionType) + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch { - return collectionType switch - { - CollectionType.Massive => new MassiveGenericObjects(), - CollectionType.List => new ListGenericObjects(), - _ => null, - }; - } + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null + }; + } } diff --git a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusCompareByColor.cs b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusCompareByColor.cs new file mode 100644 index 0000000..2aba2b3 --- /dev/null +++ b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusCompareByColor.cs @@ -0,0 +1,33 @@ +namespace ProjectAccordionBus.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningBusCompareByColor : IComparer +{ + public int Compare(DrawningBus? x, DrawningBus? y) + { + if (x == null || x.EntityBus == null) + { + return 1; + } + + if (y == null || y.EntityBus == null) + { + return -1; + } + + var bodycolorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + + var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight); + } +} diff --git a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusCompareByType.cs b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusCompareByType.cs new file mode 100644 index 0000000..625f2cc --- /dev/null +++ b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusCompareByType.cs @@ -0,0 +1,38 @@ +namespace ProjectAccordionBus.Drawnings; + +/// +/// Сравнение по типу, скорости и весу +/// +public class DrawningBusCompareByType : IComparer +{ + public int Compare(DrawningBus? x, DrawningBus? y) + { + if (x == null && y == null) + { + return 0; + } + + if (x == null || x.EntityBus == null) + { + return 1; + } + + if (y == null || y.EntityBus == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight); + } +} diff --git a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusEqutables.cs b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusEqutables.cs new file mode 100644 index 0000000..0bb08f4 --- /dev/null +++ b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBusEqutables.cs @@ -0,0 +1,80 @@ +using ProjectAccordionBus.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAccordionBus.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningBusEqutables : IEqualityComparer +{ + public bool Equals(DrawningBus? x, DrawningBus? y) + { + if (x == null || x.EntityBus == null) + { + return false; + } + + if (y == null || y.EntityBus == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityBus.Speed != y.EntityBus.Speed) + { + return false; + } + + if (x.EntityBus.Weight != y.EntityBus.Weight) + { + return false; + } + + if (x.EntityBus.BodyColor != y.EntityBus.BodyColor) + { + return false; + } + + if (x is DrawningAccordionBus && y is DrawningAccordionBus) + { + // TODO доделать логику сравнения дополнительных параметров + EntityAccordionBus _x = (EntityAccordionBus)x.EntityBus; + EntityAccordionBus _y = (EntityAccordionBus)y.EntityBus; + + if (_x.Compartment != _y.Compartment) + { + if (_x.Entrance != _y.Entrance) + { + return false; + } + if (_x.Windows != _y.Windows) + { + return false; + } + return false; + } + + if (_x.AdditionalColor != _y.AdditionalColor) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningBus obj) + { + return obj.GetHashCode(); + } +} + diff --git a/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityAccordionBus.cs b/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityAccordionBus.cs index 2b3efb6..d415290 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityAccordionBus.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityAccordionBus.cs @@ -12,7 +12,10 @@ public class EntityAccordionBus : EntityBus { public Color AdditionalColor { get; private set; } - public void SetAdditionalColor(Color color) => AdditionalColor = color; + public void SetAdditionalColor(Color color) + { + AdditionalColor = color; + } public bool Compartment { get; private set; } diff --git a/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityBus.cs b/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityBus.cs index d96c987..4289354 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityBus.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityBus.cs @@ -14,8 +14,10 @@ public class EntityBus public Color BodyColor { get; private set; } - public void SetBodyColor(Color color) => BodyColor = color; - + public void SetBodyColor(Color color) + { + BodyColor = color; + } public double Step => Speed * 50 / Weight; /// diff --git a/ProjectAccordionBus/ProjectAccordionBus/Exceptions/ObjectNotUniqueException.cs b/ProjectAccordionBus/ProjectAccordionBus/Exceptions/ObjectNotUniqueException.cs new file mode 100644 index 0000000..0cb8c43 --- /dev/null +++ b/ProjectAccordionBus/ProjectAccordionBus/Exceptions/ObjectNotUniqueException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectAirbus.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/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.Designer.cs b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.Designer.cs index 1690db7..f441cc8 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.Designer.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.Designer.cs @@ -30,6 +30,8 @@ { groupBoxTools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); buttonDeleteBus = new Button(); maskedTextBox = new MaskedTextBox(); buttonRefresh = new Button(); @@ -73,6 +75,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonDeleteBus); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonRefresh); @@ -80,15 +84,37 @@ panelCompanyTools.Controls.Add(buttonAddBus); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 317); + panelCompanyTools.Location = new Point(3, 304); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(169, 191); + panelCompanyTools.Size = new Size(169, 204); panelCompanyTools.TabIndex = 10; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(6, 180); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(160, 21); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(6, 157); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(160, 21); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // buttonDeleteBus // buttonDeleteBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonDeleteBus.Location = new Point(6, 109); + buttonDeleteBus.Location = new Point(6, 72); buttonDeleteBus.Name = "buttonDeleteBus"; buttonDeleteBus.Size = new Size(160, 23); buttonDeleteBus.TabIndex = 5; @@ -99,18 +125,17 @@ // maskedTextBox // maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox.Location = new Point(6, 80); + maskedTextBox.Location = new Point(6, 43); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(160, 23); maskedTextBox.TabIndex = 5; maskedTextBox.ValidatingType = typeof(int); - maskedTextBox.MaskInputRejected += maskedTextBox_MaskInputRejected; // // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(6, 167); + buttonRefresh.Location = new Point(6, 130); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(160, 21); buttonRefresh.TabIndex = 7; @@ -121,7 +146,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(6, 138); + buttonGoToCheck.Location = new Point(6, 101); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(160, 23); buttonGoToCheck.TabIndex = 6; @@ -132,7 +157,7 @@ // buttonAddBus // buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddBus.Location = new Point(6, 17); + buttonAddBus.Location = new Point(6, 0); buttonAddBus.Name = "buttonAddBus"; buttonAddBus.Size = new Size(160, 37); buttonAddBus.TabIndex = 2; @@ -154,7 +179,7 @@ panelStorage.Dock = DockStyle.Top; panelStorage.Location = new Point(3, 19); panelStorage.Name = "panelStorage"; - panelStorage.Size = new Size(169, 291); + panelStorage.Size = new Size(169, 282); panelStorage.TabIndex = 8; // // buttonCollectionDel @@ -178,7 +203,7 @@ // // buttonCollectionAdd // - buttonCollectionAdd.Location = new Point(3, 81); + buttonCollectionAdd.Location = new Point(6, 81); buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Size = new Size(163, 23); buttonCollectionAdd.TabIndex = 4; @@ -236,7 +261,6 @@ comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Size = new Size(160, 23); comboBoxSelectorCompany.TabIndex = 1; - comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged; // // labelCollectionName // @@ -246,7 +270,6 @@ labelCollectionName.Size = new Size(122, 15); labelCollectionName.TabIndex = 0; labelCollectionName.Text = "Название коллекции"; - labelCollectionName.Click += labelCollectionName_Click; // // pictureBox // @@ -347,5 +370,9 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button button2; + private Button button1; + private Button buttonSortByType; + private Button buttonSortByColor; } } \ No newline at end of file diff --git a/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.cs b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.cs index fb51e0e..b8e901e 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.cs @@ -2,15 +2,7 @@ using ProjectAccordionBus.CollectionGenericObjects; using ProjectAccordionBus.Drawnings; using ProjectAccordionBus.Exceptions; -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 ProjectAirbus.Exceptions; namespace ProjectAccordionBus; @@ -52,61 +44,6 @@ public partial class FormBusCollection : Form form.AddEvent(SetBus); } - /// - /// Создание объекта класса-перемещения - /// - /// Тип создания объекта - private void CreateObject(string type) - { - if (_company == null) - { - return; - } - - Random random = new(); - DrawningBus drawningBus; - switch (type) - { - case nameof(DrawningBus): - drawningBus = new DrawningBus(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); - break; - case nameof(DrawningAccordionBus): - drawningBus = new DrawningAccordionBus(random.Next(100, 300), random.Next(1000, 3000), GetColor(random), GetColor(random), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - break; - default: - return; - } - - if (_company + drawningBus != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } - - /// - /// Выбор цвета - /// - /// - /// - private static Color GetColor(Random random) - { - Color color = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)); - ColorDialog dialog = new(); - if (dialog.ShowDialog() == DialogResult.OK) - { - color = dialog.Color; - } - - return color; - } - private void buttonAddBus_Click(object sender, EventArgs e) { FormBusConfig form = new(); @@ -122,18 +59,26 @@ public partial class FormBusCollection : Form { return; } + if (_company + bus != -1) { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave()); + _logger.LogInformation("Добавлен объект: " + bus.GetDataForSave()); } - + } + catch (ObjectNotFoundException ex) + { } catch (CollectionOverflowException ex) { MessageBox.Show(ex.Message); - _logger.LogError($"Ошибка: {ex.Message}"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (ObjectNotUniqueException ex) + { + MessageBox.Show("Такой объект уже присутствует в коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -215,43 +160,33 @@ public partial class FormBusCollection : Form pictureBox.Image = _company.Show(); } - private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) - { - panelCompanyTools.Enabled = false; - } - - private void maskedTextBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) - { - - } - - private void labelCollectionName_Click(object sender, EventArgs e) - { - - } - private void buttonCollectionAdd_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || - (!radioButtonList.Checked && !radioButtonMassive.Checked)) + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogWarning("Не заполненная коллекция"); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) + try { - collectionType = CollectionType.Massive; + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RefreshListBoxItems(); + _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } - else if (radioButtonList.Checked) + catch (Exception ex) { - collectionType = CollectionType.List; + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}"); - RefreshListBoxItems(); } private void RefreshListBoxItems() @@ -259,7 +194,7 @@ public partial class FormBusCollection : 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); @@ -270,20 +205,31 @@ public partial class FormBusCollection : Form private void buttonCollectionDel_Click(object sender, EventArgs e) { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) - { - MessageBox.Show("Коллекция не выбрана"); - _logger.LogWarning("Удаление невыбранной коллекции"); - return; - } - string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty; - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - _logger.LogInformation($"Удалена коллекция: {name}"); - RefreshListBoxItems(); + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + + int pos = Convert.ToInt32(maskedTextBox.Text); + try + { + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удален объект по позиции " + pos); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } private void buttonCreateCompany_Click(object sender, EventArgs e) @@ -349,4 +295,25 @@ public partial class FormBusCollection : Form } } } + + private void CompareBus(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareBus(new DrawningBusCompareByType()); + } + + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareBus(new DrawningBusCompareByColor()); + } } -- 2.25.1