diff --git a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/AbstractCompany.cs b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/AbstractCompany.cs index c770f34..c8b0747 100644 --- a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/AbstractCompany.cs @@ -1,5 +1,6 @@ using ProjectBulldozer.Drawnings; using ProjectBulldozer.Exceptions; +using ProjectElectroTrans.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -63,7 +64,8 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningTrackedMachine trackedMachine) { - return company._collection.Insert(trackedMachine); + return company._collection?.Insert(trackedMachine, new DrawiningMachineEqutables()) ?? + throw new DrawingEquitablesException(); } /// @@ -77,6 +79,13 @@ public abstract class AbstractCompany return company._collection.Remove(position); } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => + _collection?.CollectionSort(comparer); + /// /// Получение случайного объекта из коллекции /// diff --git a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/CollectionInfo.cs b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..5ab4f8c --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,82 @@ +namespace ProjectBulldozer.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(); + } +} \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/ICollectionGenericObjects.cs index a6abb17..0df6f61 100644 --- a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -24,7 +24,7 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -32,7 +32,7 @@ public interface ICollectionGenericObjects /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -52,10 +52,17 @@ public interface ICollectionGenericObjects /// Получение типа коллекции /// CollectionType GetCollectionType { get; } + /// /// Получение объектов коллекции по одному /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/ListGenericObjects.cs b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/ListGenericObjects.cs index ce165e9..1a6c33a 100644 --- a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ using ProjectBulldozer.Exceptions; +using ProjectElectroTrans.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -48,28 +49,47 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { // TODO проверка позиции - if (position >= Count || position < 0) return null; + 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 проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } - if (Count + 1 > _maxCount) return -1; _collection.Add(obj); return Count; } - public int Insert(T obj, int position) + + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO проверка позиции - // TODO вставка по позиции if (Count == _maxCount) throw new CollectionOverflowException(Count); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + _collection.Insert(position, obj); return position; } + public T? Remove(int position) { // TODO проверка позиции @@ -87,4 +107,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/MassiveGenericObjects.cs index 14b3822..c3e155c 100644 --- a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ using ProjectBulldozer.Exceptions; +using ProjectElectroTrans.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -6,6 +7,10 @@ using System.Text; using System.Threading.Tasks; namespace ProjectBulldozer.CollectionGenericObjects; +/// +/// Параметризованный набор объектов +/// +/// Параметр: ограничение - ссылочный тип internal class MassiveGenericObjects : ICollectionGenericObjects where T : class @@ -58,9 +63,21 @@ internal class MassiveGenericObjects : ICollectionGenericObjects if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - // TODO вставка в свободное место набора + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + + + // вставка в свободное место набора for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -69,18 +86,26 @@ internal class MassiveGenericObjects : ICollectionGenericObjects return i; } } + throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - // TODO проверка позиции - // TODO проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет туда - // если нет после, ищем до - // TODO вставка + // проверка позиции if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + if (_collection[position] != null) { bool pushed = false; @@ -113,7 +138,6 @@ internal class MassiveGenericObjects : ICollectionGenericObjects } } - // вставка _collection[position] = obj; return position; } @@ -138,6 +162,15 @@ internal class MassiveGenericObjects : ICollectionGenericObjects } } + public void CollectionSort(IComparer comparer) + { + List lst = [.. _collection]; + lst.Sort(comparer.Compare); + for (int i = 0; i < _collection.Length; ++i) + { + _collection[i] = lst[i]; + } + } } diff --git a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/StorageCollection.cs b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/StorageCollection.cs index a6ac75f..dffd990 100644 --- a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/StorageCollection.cs @@ -19,12 +19,12 @@ internal class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -45,36 +45,36 @@ internal 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); } /// @@ -82,13 +82,13 @@ internal 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; } } @@ -98,7 +98,7 @@ internal class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { @@ -113,7 +113,7 @@ internal 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); @@ -125,8 +125,6 @@ internal 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()) @@ -144,8 +142,6 @@ internal class StorageCollection writer.Write(sb); } } - - return true; } /// @@ -153,68 +149,11 @@ internal class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; - } - - using (StreamReader fs = File.OpenText(filename)) - { - string str = fs.ReadLine(); - if (string.IsNullOrEmpty(str)) - { - throw new FileNotFoundException(filename); - - } - - if (!str.StartsWith(_collectionKey)) - { - throw new FileFormatException(filename); - } - - _storages.Clear(); - string strs = ""; - while ((strs = fs.ReadLine()) != null) - { - string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) - { - continue; - } - - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); - } - - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) - { - if (elem?.CreateDrawningMachine() is T ship) - { - try - { - collection.Insert(ship); - } - catch (Exception ex) - { - throw new FileFormatException(filename, ex); - } - } - } - - _storages.Add(record[0], collection); - } - - return true; - } - if (!File.Exists(filename)) - { + throw new FileNotFoundException(filename); } using (StreamReader fs = File.OpenText(filename)) @@ -227,6 +166,7 @@ internal class StorageCollection if (!str.StartsWith(_collectionKey)) { + throw new FileFormatException(filename); } _storages.Clear(); @@ -234,41 +174,38 @@ internal class StorageCollection 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) - { - } + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]); - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + 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?.CreateDrawningMachine() is T ship) + if (elem?.CreateDrawningMachine() is T macine) { try { - if (collection.Insert(ship) == -1) - { - throw new CollectionTypeException("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(macine); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - throw ex.InnerException!; + throw new FileFormatException(filename, ex); } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } - - return true; } } /// @@ -276,7 +213,8 @@ internal class StorageCollection /// /// /// - private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + private static ICollectionGenericObjects? + CreateCollection(CollectionType collectionType) { return collectionType switch { diff --git a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawiningMachineEqutables.cs b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawiningMachineEqutables.cs new file mode 100644 index 0000000..7c33b6f --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawiningMachineEqutables.cs @@ -0,0 +1,67 @@ +using ProjectBulldozer.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +{ + public bool Equals(DrawningTrackedMachine? x, DrawningTrackedMachine? y) + { + if (ReferenceEquals(x, null)) return false; + if (ReferenceEquals(y, null)) return false; + if (x.GetType() != y.GetType()) return false; + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityTrackedMachine != null && y.EntityTrackedMachine != null && x.EntityTrackedMachine.Speed != y.EntityTrackedMachine.Speed) + { + return false; + } + + if (x.EntityTrackedMachine.Weight != y.EntityTrackedMachine.Weight) + { + return false; + } + + if (x.EntityTrackedMachine.BodyColor != y.EntityTrackedMachine.BodyColor) + { + return false; + } + if (x is DrawningBulldozer && y is DrawningBulldozer) + { + // TODO доделать логику сравнения дополнительных параметров + if (((EntityBulldozer)x.EntityTrackedMachine).AdditionalColor != + ((EntityBulldozer)y.EntityTrackedMachine).AdditionalColor) + { + return false; + } + if (((EntityBulldozer)x.EntityTrackedMachine).AdditionalOtval != + ((EntityBulldozer)y.EntityTrackedMachine).AdditionalOtval) + { + return false; + } + if (((EntityBulldozer)x.EntityTrackedMachine).AdditionalRihl != + ((EntityBulldozer)y.EntityTrackedMachine).AdditionalRihl) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawningTrackedMachine obj) + { + return obj.GetHashCode(); + } + +} diff --git a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningMachineCompareByColor.cs b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningMachineCompareByColor.cs new file mode 100644 index 0000000..2c4323b --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningMachineCompareByColor.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.Drawnings; + +internal class DrawningMachineCompareByColor : IComparer +{ + public int Compare(DrawningTrackedMachine? x, DrawningTrackedMachine? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityTrackedMachine == null) + { + return 1; + } + + if (y == null || y.EntityTrackedMachine == null) + { + return -1; + } + + if (ToHex(x.EntityTrackedMachine.BodyColor) != ToHex(y.EntityTrackedMachine.BodyColor)) + { + return String.Compare(ToHex(x.EntityTrackedMachine.BodyColor), ToHex(y.EntityTrackedMachine.BodyColor), + StringComparison.Ordinal); + } + + var speedCompare = x.EntityTrackedMachine.Speed.CompareTo(y.EntityTrackedMachine.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityTrackedMachine.Weight.CompareTo(y.EntityTrackedMachine.Weight); + } + + private static String ToHex(Color c) + => $"#{c.R:X2}{c.G:X2}{c.B:X2}"; +} diff --git a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningMachineCompareByType.cs b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningMachineCompareByType.cs new file mode 100644 index 0000000..2dcdf5a --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningMachineCompareByType.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.Drawnings; + +internal class DrawningMachineCompareByType : IComparer +{ + public int Compare(DrawningTrackedMachine? x, DrawningTrackedMachine? y) + { + if (x == null || x.EntityTrackedMachine == null) + { + return -1; + } + if (y == null || y.EntityTrackedMachine == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityTrackedMachine.Speed.CompareTo(y.EntityTrackedMachine.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityTrackedMachine.Weight.CompareTo(y.EntityTrackedMachine.Weight); + } +} diff --git a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningTrackedMachine.cs b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningTrackedMachine.cs index 405d712..a078812 100644 --- a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningTrackedMachine.cs +++ b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningTrackedMachine.cs @@ -77,10 +77,7 @@ public class DrawningTrackedMachine public DrawningTrackedMachine(int speed, double weight, Color bodyColor) : this() { EntityTrackedMachine = new EntityTrackedMachine(speed, weight, bodyColor); - _pictureWidth = null; - _pictureHeight = null; - _startPosX = null; - _startPosY = null; + } diff --git a/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionAlreadyExistsException.cs b/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionAlreadyExistsException.cs index ea5965c..5cb79ae 100644 --- a/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionAlreadyExistsException.cs +++ b/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionAlreadyExistsException.cs @@ -1,13 +1,15 @@ -using System.Runtime.Serialization; +using ProjectBulldozer.CollectionGenericObjects; +using System.Runtime.Serialization; namespace ProjectBulldozer.Exceptions; [Serializable] public class CollectionAlreadyExistsException : Exception { public CollectionAlreadyExistsException() : base() { } - public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { } + public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { } public CollectionAlreadyExistsException(string name, Exception exception) : - base($"Коллекция {name} уже существует!", exception) { } + base($"Коллекция {name} уже существует!", exception) + { } protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } } \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionInfoException.cs b/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionInfoException.cs new file mode 100644 index 0000000..e53be8b --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionInfoException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace ProjectElectroTrans.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) { } +} \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionInsertException.cs b/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionInsertException.cs new file mode 100644 index 0000000..d89c5de --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionInsertException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; +using ProjectBulldozer.Drawnings; + +namespace ProjectElectroTrans.Exceptions; + +public class CollectionInsertException : Exception +{ + public CollectionInsertException(object obj) : base($"Объект {obj} не удволетворяет уникальности") { } + 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) { } +} \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/Exceptions/DrawingEquitablesException.cs b/ProjectBulldozer/ProjectBulldozer/Exceptions/DrawingEquitablesException.cs new file mode 100644 index 0000000..dfd6159 --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/Exceptions/DrawingEquitablesException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace ProjectElectroTrans.Exceptions; + +public class DrawingEquitablesException : Exception +{ + public DrawingEquitablesException() : base("Объекты прорисовки одинаковые") { } + public DrawingEquitablesException(string message) : base(message) { } + public DrawingEquitablesException(string message, Exception exception) : + base(message, exception) { } + protected DrawingEquitablesException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.Designer.cs b/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.Designer.cs index 4c6f226..aa3555d 100644 --- a/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.Designer.cs +++ b/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.Designer.cs @@ -30,6 +30,8 @@ { groupBoxTools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); buttonAddMachine = new Button(); maskedTextBox = new MaskedTextBox(); buttonRefresh = new Button(); @@ -68,13 +70,15 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(749, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(231, 671); + groupBoxTools.Size = new Size(231, 694); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddMachine); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonRefresh); @@ -83,13 +87,33 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 377); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(225, 288); + panelCompanyTools.Size = new Size(225, 311); panelCompanyTools.TabIndex = 9; // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(3, 276); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(219, 29); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Location = new Point(3, 241); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(219, 29); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // buttonAddMachine // buttonAddMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddMachine.Location = new Point(3, 28); + buttonAddMachine.Location = new Point(3, 4); buttonAddMachine.Name = "buttonAddMachine"; buttonAddMachine.Size = new Size(219, 49); buttonAddMachine.TabIndex = 0; @@ -100,7 +124,7 @@ // maskedTextBox // maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox.Location = new Point(3, 114); + maskedTextBox.Location = new Point(3, 77); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(219, 27); @@ -110,7 +134,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 241); + buttonRefresh.Location = new Point(3, 194); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(219, 41); buttonRefresh.TabIndex = 6; @@ -121,9 +145,9 @@ // buttonRemoveMachine // buttonRemoveMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveMachine.Location = new Point(3, 147); + buttonRemoveMachine.Location = new Point(3, 110); buttonRemoveMachine.Name = "buttonRemoveMachine"; - buttonRemoveMachine.Size = new Size(219, 41); + buttonRemoveMachine.Size = new Size(219, 31); buttonRemoveMachine.TabIndex = 2; buttonRemoveMachine.Text = "Удалить машину"; buttonRemoveMachine.UseVisualStyleBackColor = true; @@ -132,9 +156,9 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 194); + buttonGoToCheck.Location = new Point(3, 157); buttonGoToCheck.Name = "buttonGoToCheck"; - buttonGoToCheck.Size = new Size(219, 41); + buttonGoToCheck.Size = new Size(219, 31); buttonGoToCheck.TabIndex = 3; buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.UseVisualStyleBackColor = true; @@ -248,7 +272,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(749, 671); + pictureBox.Size = new Size(749, 694); pictureBox.TabIndex = 5; pictureBox.TabStop = false; // @@ -297,7 +321,7 @@ // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(980, 699); + ClientSize = new Size(980, 722); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -342,5 +366,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/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.cs b/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.cs index 20be16e..3e05f61 100644 --- a/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.cs +++ b/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.cs @@ -2,13 +2,6 @@ using ProjectBulldozer.CollectionGenericObjects; using ProjectBulldozer.Drawnings; 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; namespace ProjectBulldozer; @@ -71,7 +64,7 @@ public partial class FormMachineCollectoin : Form FormMachineConfig form = new(); form.Show(); form.AddEvent(SetMachine); - + } /// @@ -212,7 +205,7 @@ public partial class FormMachineCollectoin : Form } try { - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ")); _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); } @@ -243,7 +236,9 @@ public partial class FormMachineCollectoin : Form { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); + _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } @@ -255,10 +250,10 @@ public partial class FormMachineCollectoin : 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); } } } @@ -276,7 +271,10 @@ public partial class FormMachineCollectoin : 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("Коллекция не проинициализирована"); @@ -348,5 +346,40 @@ public partial class FormMachineCollectoin : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareCars(new DrawningMachineCompareByType()); + } + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareCars(new DrawningMachineCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareCars(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + } diff --git a/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj b/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj index 7b1485a..e2255c1 100644 --- a/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj +++ b/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj @@ -8,52 +8,31 @@ enable - - - - - - - - - - - - - - - - - - - - - - - - - + + + True + True + Resources.resx + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + + + + + + - - - True - True - Resources.resx - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - - - - - - Always - - \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/serilog.json b/ProjectBulldozer/ProjectBulldozer/serilog.json index ca7cac4..4a72a85 100644 --- a/ProjectBulldozer/ProjectBulldozer/serilog.json +++ b/ProjectBulldozer/ProjectBulldozer/serilog.json @@ -15,7 +15,8 @@ ], "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], "Properties": { - "Application": "Locomotives" + "Application": "Bulldozer" } } } +