From e210c12c20befd6442f4e0d1e90866baf7627b76 Mon Sep 17 00:00:00 2001 From: Esenia12 <148366616+Esenia12@users.noreply.github.com> Date: Mon, 13 May 2024 10:03:48 +0400 Subject: [PATCH] =?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=208?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 13 +- .../CollectionInfo.cs | 84 +++++++++++++ .../ICollectionGenericObjects.cs | 17 ++- .../ListGenericObjects.cs | 68 ++++++---- .../MassiveGenericObjects.cs | 37 +++++- .../StorageCollection.cs | 119 +++++++++--------- .../Drawnings/DrawningTrackEqutables.cs | 69 ++++++++++ .../Drawnings/TrackCompareByColor.cs | 30 +++++ .../Drawnings/TrackCompareByType.cs | 26 ++++ .../CollectionAlreadyExistsException.cs | 17 +++ .../Exceptions/CollectionInfoException.cs | 15 +++ .../Exceptions/CollectionInsertException.cs | 16 +++ .../Exceptions/CollectionTypeException.cs | 18 +++ .../Exceptions/DrawningEqutablesException.cs | 16 +++ .../Exceptions/EmptyFileException.cs | 16 +++ .../FormTrackCollection.Designer.cs | 48 +++++-- .../ProjectDumpTruck/FormTrackCollection.cs | 59 ++++++++- .../ProjectDumpTruck/FormTrackCollection.resx | 3 + .../ProjectDumpTruck/ProjectDumpTruck.csproj | 1 + 19 files changed, 568 insertions(+), 104 deletions(-) create mode 100644 ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTrackEqutables.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Drawnings/TrackCompareByColor.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Drawnings/TrackCompareByType.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionAlreadyExistsException.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionInfoException.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionInsertException.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionTypeException.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Exceptions/DrawningEqutablesException.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Exceptions/EmptyFileException.cs diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/AbstractCompany.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/AbstractCompany.cs index eb0dd5b..91339c8 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,6 @@ using ProjectDumpTrack.Drawnings; +using ProjectDumpTruck.Exceptions; + namespace ProjectDumpTruck.CollectionGenericObjects; public abstract class AbstractCompany @@ -53,9 +55,9 @@ public abstract class AbstractCompany /// Компания /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningTrack car) + public static int operator +(AbstractCompany company, DrawningTrack track) { - return company._collection.Insert(car); + return company._collection.Insert(track, new DrawningTrackEqutables()) ; } /// @@ -69,6 +71,13 @@ public abstract class AbstractCompany return company._collection.Remove(position); } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => + _collection?.CollectionSort(comparer); + /// /// Получение случайного объекта из коллекции /// diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/CollectionInfo.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..6b2879f --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,84 @@ + + +namespace ProjectDumpTruck.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 bool IsEmpty() + { + if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true; + return false; + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ICollectionGenericObjects.cs index ee3833f..cf60fb2 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectDumpTrack.Drawnings; + namespace ProjectDumpTruck.CollectionGenericObjects; @@ -23,16 +25,18 @@ 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); /// /// Удаление объекта из коллекции с конкретной позиции @@ -58,4 +62,13 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); + void CollectionSort(Comparison comparison) where T : DrawningTrack; } + + diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ListGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ListGenericObjects.cs index dcd514d..e282f41 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ListGenericObjects.cs @@ -8,21 +8,21 @@ namespace ProjectDumpTruck.CollectionGenericObjects; /// /// Параметр: ограничение - ссылочный тип public class ListGenericObjects : ICollectionGenericObjects - where T : class + where T : class { - /// - /// Список объектов, которые храним - /// - private readonly List _collection; + /// + /// Список объектов, которые храним + /// + private readonly List _collection; - /// - /// Максимально допустимое число объектов в списке - /// - public int _maxCount; + /// + /// Максимально допустимое число объектов в списке + /// + public int _maxCount; - public int Count => _collection.Count; + public int Count => _collection.Count; - public int MaxCount + public int MaxCount { get { @@ -43,30 +43,47 @@ public class ListGenericObjects : ICollectionGenericObjects /// Конструктор /// public ListGenericObjects() - { - _collection = new(); - } + { + _collection = new(); + } - public T Get(int position) - { + public T Get(int position) + { //TODO выброс ошибки если выход за границу 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) { - - // TODO выброс ошибки если переполнение - if (Count == _maxCount) throw new CollectionOverflowException(Count); - _collection.Add(obj); - return Count; + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new CollectionInsertException(); + } + } + if (Count == _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); + return Count; + } + // TODO выброс ошибки если переполнение + + + - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // TODO выброс ошибки если переполнение // TODO выброс ошибки если за границу if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new CollectionInsertException(); + } + } if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); return position; @@ -88,5 +105,10 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/MassiveGenericObjects.cs index 4f57f68..0962cdd 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectDumpTruck.Exceptions; +using ProjectDumpTrack.Drawnings; +using ProjectDumpTruck.Exceptions; namespace ProjectDumpTruck.CollectionGenericObjects; internal class MassiveGenericObjects : ICollectionGenericObjects @@ -52,11 +53,23 @@ internal class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - + // TODO выброс ошибки если переполнение + { + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningTrack, item as DrawningTrack)) + throw new CollectionInsertException("An item with the same value already exists in the collection: ProjectDumpTrack.Drawnings.DrawningTrack"); + } + + } + } + int index = 0; while (index < _collection.Length - 1) { @@ -67,13 +80,22 @@ internal class MassiveGenericObjects : ICollectionGenericObjects } index++; } + + throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - + // TODO выброс ошибки если выход за границу + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningTrack, item as DrawningTrack)) { throw new CollectionInsertException($"An item with the same value already exists in the collection: {obj}"); } + } + } if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { @@ -121,6 +143,11 @@ internal class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/StorageCollection.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/StorageCollection.cs index 5c2449c..3bc9555 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/StorageCollection.cs @@ -1,35 +1,35 @@ using ProjectDumpTrack.Drawnings; using System.Text; using ProjectDumpTruck.Exceptions; +using ProjectDumpTruck.Drawnings; + namespace ProjectDumpTruck.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// -public class StorageCollection +public class StorageCollection where T : DrawningTrack { /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// - /// Ключевое слово, с которого должен начинаться файл - /// - private readonly string _collectionKey = "CollectionsStorage"; - + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; /// /// Разделитель для записи ключа и значения элемента словаря /// private readonly string _separatorForKeyValue = "|"; - /// /// Разделитель для записей коллекции данных в файл /// @@ -41,35 +41,36 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище /// - /// Название коллекции - /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + /// тип коллекции + public void AddCollection(CollectionInfo collectionInfo) { // TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO Прописать логику для добавления - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - else if (collectionType == CollectionType.Massive) - _storages[name] = new MassiveGenericObjects(); - else if (collectionType == CollectionType.List) - _storages[name] = new ListGenericObjects(); + if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo); + if (collectionInfo.CollectionType == CollectionType.None) + throw new CollectionTypeException("Пустой тип коллекции"); + if (collectionInfo.CollectionType == CollectionType.Massive) + _storages[collectionInfo] = new MassiveGenericObjects(); + else if (collectionInfo.CollectionType == CollectionType.List) + _storages[collectionInfo] = new ListGenericObjects(); + } /// /// Удаление коллекции /// - /// Название коллекции - public void DelCollection(string name) + /// Название коллекции + public void DelCollection(CollectionInfo collectionInfo) { // TODO Прописать логику для удаления коллекции - if (_storages.ContainsKey(name)) - _storages.Remove(name); + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); } /// @@ -77,13 +78,13 @@ public class StorageCollection /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[CollectionInfo collectionInfo] { get { // TODO Продумать логику получения объекта - if (_storages.ContainsKey(name)) - return _storages[name]; + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } @@ -97,27 +98,29 @@ public class StorageCollection { if (_storages.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + throw new EmptyFileException(); } + if (File.Exists(filename)) { File.Delete(filename); } + 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); + // не сохраняем пустые коллекции if (value.Value.Count == 0) { continue; } + 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()) @@ -127,14 +130,14 @@ public class StorageCollection { continue; } + sb.Append(data); sb.Append(_separatorItems); } + writer.Write(sb); } - } - } /// @@ -146,66 +149,68 @@ public class StorageCollection { if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + throw new FileNotFoundException(filename); } + using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); - if (str == null || str.Length == 0) + if (string.IsNullOrEmpty(str)) { - throw new Exception("В файле нет данных"); + throw new EmptyFileException(filename); } + if (!str.StartsWith(_collectionKey)) { - throw new Exception("В файле неверные данные"); + throw new FileFormatException(filename); } + _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; } - 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 CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]); + + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); + + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningTrack() is T track) { try { - if (collection.Insert(track) == -1) - { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(track); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - throw new Exception("Коллекция переполнена", ex); + throw new FileFormatException(filename, ex); } } } - _storages.Add(record[0], collection); + + _storages.Add(collectionInfo, collection); } - } } - /// /// Создание коллекции по типу /// /// /// - private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + private static ICollectionGenericObjects? + CreateCollection(CollectionType collectionType) { return collectionType switch { @@ -214,6 +219,6 @@ public class StorageCollection _ => null, }; } -} - \ No newline at end of file + +} \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTrackEqutables.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTrackEqutables.cs new file mode 100644 index 0000000..dea86a7 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTrackEqutables.cs @@ -0,0 +1,69 @@ +using ProjectDumpTrack.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectDumpTrack.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningTrackEqutables : IEqualityComparer +{ + public bool Equals(DrawningTrack? x, DrawningTrack? y) + { + if (x == null || x.EntityTrack == null) + { + return false; + } + + if (y == null || y.EntityTrack == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityTrack.Speed != y.EntityTrack.Speed) + { + return false; + } + + if (x.EntityTrack.Weight != y.EntityTrack.Weight) + { + return false; + } + + if (x.EntityTrack.BodyColor != y.EntityTrack.BodyColor) + { + return false; + } + + if (x is DrawningDumpTrack && y is DrawningDumpTrack) + { + // TODO доделать логику сравнения дополнительных параметров + EntityDumpTrack xDumpTruck = (EntityDumpTrack)x.EntityTrack; + EntityDumpTrack yDumpTruck = (EntityDumpTrack)y.EntityTrack; + + if (xDumpTruck.AdditionalColor != yDumpTruck.AdditionalColor) + return false; + + if (xDumpTruck.AdditionalAwningColor != yDumpTruck.AdditionalAwningColor) + return false; + + if (xDumpTruck.Awning != yDumpTruck.Awning) + return false; + + if (xDumpTruck.Bodywork != yDumpTruck.Bodywork) + return false; + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningTrack obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/TrackCompareByColor.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/TrackCompareByColor.cs new file mode 100644 index 0000000..6741237 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/TrackCompareByColor.cs @@ -0,0 +1,30 @@ + +using ProjectDumpTrack.Drawnings; + +namespace ProjectDumpTruck.Drawnings; +internal class TrackCompareByColor : IComparer +{ + public int Compare(DrawningTrack? x, DrawningTrack? y) + { + if (x == null || x.EntityTrack == null) + { + return 1; + } + + if (y == null || y.EntityTrack == null) + { + return -1; + } + var bodycolorCompare = x.EntityTrack.BodyColor.Name.CompareTo(y.EntityTrack.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityTrack.Speed.CompareTo(y.EntityTrack.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityTrack.Weight.CompareTo(y.EntityTrack.Weight); + } +} \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/TrackCompareByType.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/TrackCompareByType.cs new file mode 100644 index 0000000..5bc7f55 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/TrackCompareByType.cs @@ -0,0 +1,26 @@ +using ProjectDumpTrack.Drawnings; +namespace ProjectDumpTruck.Drawnings; +internal class TrackCompareByType : IComparer +{ + public int Compare(DrawningTrack? x, DrawningTrack? y) + { + if (x == null || x.EntityTrack == null) + { + return -1; + } + if (y == null || y.EntityTrack == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityTrack.Speed.CompareTo(y.EntityTrack.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityTrack.Weight.CompareTo(y.EntityTrack.Weight); + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionAlreadyExistsException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..62acaf0 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,17 @@ +using ProjectDumpTruck.CollectionGenericObjects; +using System.Runtime.Serialization; + + +namespace ProjectDumpTruck.Exceptions; + +[Serializable] +public class CollectionAlreadyExistsException : Exception +{ + public CollectionAlreadyExistsException() : base() { } + public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { } + public CollectionAlreadyExistsException(string name, Exception exception) : + base($"Коллекция {name} уже существует!", exception) + { } + protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionInfoException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionInfoException.cs new file mode 100644 index 0000000..0b57ae9 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionInfoException.cs @@ -0,0 +1,15 @@ + +using System.Runtime.Serialization; + +namespace ProjectDumpTruck.Exceptions; + +public class CollectionInfoException : Exception +{ + public CollectionInfoException() : base() { } + public CollectionInfoException(string message) : base(message) { } + public CollectionInfoException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionInfoException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionInsertException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionInsertException.cs new file mode 100644 index 0000000..cf238e4 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionInsertException.cs @@ -0,0 +1,16 @@ + +using System.Runtime.Serialization; + +namespace ProjectDumpTruck.Exceptions; +[Serializable] +public class CollectionInsertException : Exception + + +{ + public CollectionInsertException(int i) : base("В коллекции содержится равный элемент: " + i) { } + public CollectionInsertException() : base() { } + public CollectionInsertException(string message) : base(message) { } + public CollectionInsertException(string message, Exception exception) : base(message, exception) { } + protected CollectionInsertException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} + diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionTypeException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionTypeException.cs new file mode 100644 index 0000000..1db2b56 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionTypeException.cs @@ -0,0 +1,18 @@ + + +using System.Runtime.Serialization; + +namespace ProjectDumpTruck.Exceptions; + +[Serializable] + +public class CollectionTypeException : Exception +{ + public CollectionTypeException() : base() { } + public CollectionTypeException(string message) : base(message) { } + public CollectionTypeException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionTypeException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/DrawningEqutablesException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/DrawningEqutablesException.cs new file mode 100644 index 0000000..10fc50e --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/DrawningEqutablesException.cs @@ -0,0 +1,16 @@ + + +using System.Runtime.Serialization; + +namespace ProjectDumpTruck.Exceptions; + +public class DrawningEqutablesException : Exception +{ + public DrawningEqutablesException() : base("Объекты прорисовки одинаковые") { } + public DrawningEqutablesException(string message) : base(message) { } + public DrawningEqutablesException(string message, Exception exception) : + base(message, exception) + { } + protected DrawningEqutablesException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/EmptyFileException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/EmptyFileException.cs new file mode 100644 index 0000000..296941e --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/EmptyFileException.cs @@ -0,0 +1,16 @@ + + +using System.Runtime.Serialization; + +namespace ProjectDumpTruck.Exceptions; +public class EmptyFileException : Exception +{ + public EmptyFileException(string name) : base($"Файл {name} пустой ") { } + public EmptyFileException() : base("В хранилище отсутствуют коллекции для сохранения") { } + public EmptyFileException(string name, string message) : base(message) { } + public EmptyFileException(string name, string message, Exception exception) : + base(message, exception) + { } + protected EmptyFileException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.Designer.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.Designer.cs index edf11c2..74ba8ea 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.Designer.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -66,15 +68,17 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(790, 24); + groupBoxTools.Location = new Point(470, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(216, 538); + groupBoxTools.Size = new Size(216, 712); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddTrack); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBox); @@ -82,12 +86,12 @@ panelCompanyTools.Controls.Add(buttonDelTrack); panelCompanyTools.Location = new Point(3, 354); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(210, 231); + panelCompanyTools.Size = new Size(210, 358); panelCompanyTools.TabIndex = 9; // // buttonAddTrack // - buttonAddTrack.Location = new Point(9, 14); + buttonAddTrack.Location = new Point(9, 32); buttonAddTrack.Name = "buttonAddTrack"; buttonAddTrack.Size = new Size(192, 30); buttonAddTrack.TabIndex = 1; @@ -97,7 +101,7 @@ // // buttonRefresh // - buttonRefresh.Location = new Point(9, 197); + buttonRefresh.Location = new Point(9, 219); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(192, 25); buttonRefresh.TabIndex = 6; @@ -116,7 +120,7 @@ // // buttonGoToCheck // - buttonGoToCheck.Location = new Point(9, 162); + buttonGoToCheck.Location = new Point(9, 184); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(192, 29); buttonGoToCheck.TabIndex = 5; @@ -243,7 +247,7 @@ pictureBox.Enabled = false; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(790, 538); + pictureBox.Size = new Size(470, 712); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -252,7 +256,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1006, 24); + menuStrip.Size = new Size(686, 24); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip1"; // @@ -286,12 +290,33 @@ // openFileDialog // openFileDialog.Filter = "txt file | *.txt"; + // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(9, 309); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(192, 37); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Location = new Point(9, 268); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(192, 35); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // FormTrackCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1006, 562); + ClientSize = new Size(686, 736); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -310,6 +335,9 @@ PerformLayout(); } + + + #endregion private GroupBox groupBoxTools; @@ -336,5 +364,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/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.cs index c1bf927..3d2c429 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.cs @@ -3,6 +3,8 @@ using Microsoft.Extensions.Logging; using ProjectDumpTruck.CollectionGenericObjects; using ProjectDumpTrack.Drawnings; using ProjectDumpTruck.Exceptions; +using ProjectDumpTruck.Drawnings; + namespace ProjectDumpTruck; /// @@ -94,6 +96,11 @@ public partial class FormTrackCollection : Form MessageBox.Show("Не удалось добавить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (CollectionInsertException ex) + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// @@ -226,7 +233,7 @@ public partial class FormTrackCollection : Form { collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "")); RerfreshListBoxItems(); _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } @@ -245,10 +252,10 @@ public partial class FormTrackCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) + CollectionInfo? col = _storageCollection.Keys?[i]; + if (!col!.IsEmpty()) { - listBoxCollection.Items.Add(colName); + listBoxCollection.Items.Add(col); } } @@ -277,7 +284,9 @@ public partial class FormTrackCollection : Form { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); + RerfreshListBoxItems(); _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); } @@ -301,7 +310,10 @@ public partial class FormTrackCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = + _storageCollection[ + CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? + new CollectionInfo("", CollectionType.None, "")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -362,6 +374,41 @@ public partial class FormTrackCollection : Form } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareCars(new TrackCompareByType()); + } + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareCars(new TrackCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareCars(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + } diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.resx b/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.resx index 8b1dfa1..ca20953 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.resx +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTrackCollection.resx @@ -126,4 +126,7 @@ 261, 17 + + 25 + \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj b/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj index 7c56274..921f95e 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj +++ b/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj @@ -6,6 +6,7 @@ enable true enable + preview -- 2.25.1