From 74d29aca6b9db298657ef1a7303d12e9c7a92a93 Mon Sep 17 00:00:00 2001 From: rakhaliullov Date: Thu, 16 May 2024 01:57:54 +0300 Subject: [PATCH] lab8 --- .../AbstractCompany.cs | 11 +- .../CollectionInfo.cs | 84 ++++++++ .../ICollectionGenericObjects.cs | 17 +- .../ListGenericObjects.cs | 32 ++- .../MassiveGenericObjects.cs | 36 +++- .../StorageCollection.cs | 184 +++++++++--------- .../DrawningAircraftCompareByColor.cs | 37 ++++ .../DrawningAircraftCompareByType.cs | 33 ++++ .../Drawnings/DrawningAircraftEquitables.cs | 59 ++++++ .../Stormtrooper/Entities/EntityAircraft.cs | 3 +- .../CollectionAlreadyExistsException.cs | 14 ++ .../Exceptions/CollectionInfoException.cs | 13 ++ .../Exceptions/CollectionInsertException.cs | 13 ++ .../Exceptions/CollectionTypeException.cs | 14 ++ .../Exceptions/DrawningEquitablesException.cs | 13 ++ .../Exceptions/EmptyFileExeption.cs | 14 ++ .../Exceptions/FileFormatException.cs | 13 ++ .../Exceptions/FileNotFoundException.cs | 14 ++ .../FormAircraftCollection.Designer.cs | 58 +++++- .../Stormtrooper/FormAircraftCollection.cs | 74 +++++-- .../Stormtrooper/FormAircraftConfig.cs | 7 - 21 files changed, 606 insertions(+), 137 deletions(-) create mode 100644 Stormtrooper/Stormtrooper/CollectionGenericObjects/CollectionInfo.cs create mode 100644 Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftCompareByColor.cs create mode 100644 Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftCompareByType.cs create mode 100644 Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftEquitables.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/CollectionAlreadyExistsException.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/CollectionInfoException.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/CollectionInsertException.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/CollectionTypeException.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/DrawningEquitablesException.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/EmptyFileExeption.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/FileFormatException.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/FileNotFoundException.cs diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs index 380341f..8847177 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs @@ -56,11 +56,12 @@ public abstract class AbstractCompany /// Перегрузка оператора сложения для класса /// /// Компания - /// Добавляемый объект + /// Добавляемый объект /// public static int operator +(AbstractCompany company, DrawningAircraft aircraft) { - return company._collection.Insert(aircraft); + return company._collection?.Insert(aircraft, new DrawningAircraftEquitables()) ?? + throw new DrawningEquitablesException(); } /// @@ -83,7 +84,11 @@ public abstract class AbstractCompany Random rnd = new(); return _collection?.Get(rnd.Next(GetMaxCount)); } - + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); /// /// Вывод всей коллекции /// diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/CollectionInfo.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..7ac7ebb --- /dev/null +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,84 @@ +using Stormtrooper.CollectionGenericObjects; + +namespace Stormtrooper; + +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/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs index 29e71ba..9a9a18d 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -5,7 +5,7 @@ /// /// Параметр: ограничение - ссылочный тип public interface ICollectionGenericObjects -where T : class + where T : class { /// /// Количество объектов в коллекции @@ -22,7 +22,7 @@ where T : class /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -30,14 +30,14 @@ where T : class /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция /// true - удаление прошло удачно, false - удаление не удалось - T? Remove(int position); + T Remove(int position); /// /// Получение объекта по позиции @@ -56,4 +56,11 @@ where T : class /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); -} + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); + +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs index eb0d568..1324c17 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -55,17 +55,39 @@ where T : class 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) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + _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) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + _collection.Insert(position, obj); return position; } @@ -85,5 +107,9 @@ public IEnumerable GetItems() yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index 4819b3b..5879056 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -61,8 +61,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + 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++) { @@ -76,11 +88,22 @@ 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 < 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,11 +136,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - // вставка _collection[position] = obj; return position; } + public T? Remove(int position) { // проверка позиции @@ -129,6 +152,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return temp; } + public IEnumerable GetItems() { for (int i = 0; i < _collection.Length; ++i) @@ -136,4 +160,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + List value = new List(_collection); + value.Sort(comparer); + value.CopyTo(_collection, 0); + } } diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs index 75bf013..d9d35cb 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs @@ -19,11 +19,11 @@ where T : DrawningAircraft /// /// Словарь (хранилище) с коллекциями /// - private Dictionary> _storages; + private Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -45,164 +45,164 @@ where T : DrawningAircraft /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } + /// /// Добавление коллекции в хранилище /// - /// Название коллекции - /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + /// тип коллекции + public void AddCollection(CollectionInfo collectionInfo) { - if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) - return; - switch (collectionType) - { - case CollectionType.List: - _storages.Add(name, new ListGenericObjects()); - break; - case CollectionType.Massive: - _storages.Add(name, new MassiveGenericObjects()); - break; - default: - break; - } + 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); } - /// - /// Доступ к коллекции - /// - /// Название коллекции - /// - public ICollectionGenericObjects? this[string name] + + /// + /// Доступ к коллекции + /// + /// + /// + public ICollectionGenericObjects? this[CollectionInfo collectionInfo] { get { - if (_storages.TryGetValue(name, out ICollectionGenericObjects? value)) - return value; + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } - /// - /// Сохранение информации по самолетам в хранилище в файл - /// - /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных + + /// + /// Сохранение информации по самолетам в файл + /// + /// + /// public void SaveData(string filename) { if (_storages.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + throw new EmptyFileExeption(); } - if (File.Exists(filename)) { File.Delete(filename); } - using FileStream fs = new(filename, FileMode.Create); - using StreamWriter streamWriter = new StreamWriter(fs); - streamWriter.Write(_collectionKey); - - foreach (KeyValuePair> value in _storages) + using (StreamWriter writer = new StreamWriter(filename)) { - streamWriter.Write(Environment.NewLine); - - if (value.Value.Count == 0) + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - continue; - } - - streamWriter.Write(value.Key); - streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.GetCollectionType); - streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.MaxCount); - streamWriter.Write(_separatorForKeyValue); - - - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) + StringBuilder sb = new(); + sb.Append(Environment.NewLine); + if (value.Value.Count == 0) { continue; } + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } - streamWriter.Write(data); - streamWriter.Write(_separatorItems); + sb.Append(data); + sb.Append(_separatorItems); + } + writer.Write(sb); } } } /// - /// Загрузка информации по кораблям в хранилище из файла + /// Загрузка информации по автомобилям в хранилище из файла /// - /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных public void LoadData(string filename) { if (!File.Exists(filename)) { - throw new FileNotFoundException("Файл не существует"); + throw new FileNotFoundException(filename); } - using (StreamReader sr = new StreamReader(filename)) + using (StreamReader fs = File.OpenText(filename)) { - string? str; - str = sr.ReadLine(); - if (str != _collectionKey.ToString()) - throw new FormatException("В файле неверные данные"); - _storages.Clear(); - while ((str = sr.ReadLine()) != null) + string str = fs.ReadLine(); + if (string.IsNullOrEmpty(str)) { - string[] record = str.Split(_separatorForKeyValue); - if (record.Length != 4) + throw new EmptyFileExeption(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 != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); - } - collection.MaxCount = Convert.ToInt32(record[2]); + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]); - 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?.CreateDrawningAircraft() is T aircraft) + if (elem?.CreateDrawningAircraft() is T ship) { try { - if (collection.Insert(aircraft) == -1) - { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(ship); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - throw new CollectionOverflowException("Коллекция переполнена", 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 { diff --git a/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftCompareByColor.cs b/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftCompareByColor.cs new file mode 100644 index 0000000..203d202 --- /dev/null +++ b/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftCompareByColor.cs @@ -0,0 +1,37 @@ +using Stormtrooper.Drawnings; + +namespace Stormtrooper; + +public class DrawningAircraftCompareByColor : IComparer +{ + public int Compare(DrawningAircraft? x, DrawningAircraft? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityAircraft == null) + { + return 1; + } + + if (y == null || y.EntityAircraft == null) + { + return -1; + } + + if (ToHex(x.EntityAircraft.BodyColor) != ToHex(y.EntityAircraft.BodyColor)) + { + return String.Compare(ToHex(x.EntityAircraft.BodyColor), ToHex(y.EntityAircraft.BodyColor), + StringComparison.Ordinal); + } + + var speedCompare = x.EntityAircraft.Speed.CompareTo(y. EntityAircraft.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityAircraft.Weight.CompareTo(y.EntityAircraft.Weight); + } + + private static String ToHex(Color c) + => $"#{c.R:X2}{c.G:X2}{c.B:X2}"; +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftCompareByType.cs b/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftCompareByType.cs new file mode 100644 index 0000000..227d22a --- /dev/null +++ b/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftCompareByType.cs @@ -0,0 +1,33 @@ +using Stormtrooper.Drawnings; + +namespace Stormtrooper; + +public class DrawningAircraftCompareByType : IComparer +{ + public int Compare(DrawningAircraft? x, DrawningAircraft? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityAircraft == null) + { + return 1; + } + + if (y == null || y.EntityAircraft == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityAircraft.Speed.CompareTo(y.EntityAircraft.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityAircraft.Weight.CompareTo(y.EntityAircraft.Weight); + } +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftEquitables.cs b/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftEquitables.cs new file mode 100644 index 0000000..7d0fa11 --- /dev/null +++ b/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraftEquitables.cs @@ -0,0 +1,59 @@ +using Stormtrooper.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace Stormtrooper.Drawnings; + +public class DrawningAircraftEquitables : IEqualityComparer +{ + public bool Equals(DrawningAircraft? x, DrawningAircraft? 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.EntityAircraft != null && y.EntityAircraft != null && x.EntityAircraft.Speed != y.EntityAircraft.Speed) + { + return false; + } + + if (x.EntityAircraft.Weight != y.EntityAircraft.Weight) + { + return false; + } + + if (x.EntityAircraft.BodyColor != y.EntityAircraft.BodyColor) + { + return false; + } + if (x is DrawningStormtrooper && y is DrawningStormtrooper) + { + if (((EntityStormtrooper)x.EntityAircraft).AdditionalColor != + ((EntityStormtrooper)y.EntityAircraft).AdditionalColor) + { + return false; + } + if (((EntityStormtrooper)x.EntityAircraft).Rocket!= + ((EntityStormtrooper)y.EntityAircraft).Rocket) + { + return false; + } + if (((EntityStormtrooper)x.EntityAircraft).Bomb!= + ((EntityStormtrooper)y.EntityAircraft).Bomb) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningAircraft obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Entities/EntityAircraft.cs b/Stormtrooper/Stormtrooper/Entities/EntityAircraft.cs index 81a0be7..928bb63 100644 --- a/Stormtrooper/Stormtrooper/Entities/EntityAircraft.cs +++ b/Stormtrooper/Stormtrooper/Entities/EntityAircraft.cs @@ -55,6 +55,7 @@ public class EntityAircraft return null; } - return new EntityAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + return new EntityAircraft(Convert.ToInt32(strs[1]), + Convert.ToDouble(strs[2]), Color.FromName(strs[3])); } } diff --git a/Stormtrooper/Stormtrooper/Exceptions/CollectionAlreadyExistsException.cs b/Stormtrooper/Stormtrooper/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..4e1204d --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + + +namespace Stormtrooper; + +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) { } +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Exceptions/CollectionInfoException.cs b/Stormtrooper/Stormtrooper/Exceptions/CollectionInfoException.cs new file mode 100644 index 0000000..654e06c --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/CollectionInfoException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace Stormtrooper; + +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/Stormtrooper/Stormtrooper/Exceptions/CollectionInsertException.cs b/Stormtrooper/Stormtrooper/Exceptions/CollectionInsertException.cs new file mode 100644 index 0000000..d58928a --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/CollectionInsertException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; +namespace Stormtrooper; + +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/Stormtrooper/Stormtrooper/Exceptions/CollectionTypeException.cs b/Stormtrooper/Stormtrooper/Exceptions/CollectionTypeException.cs new file mode 100644 index 0000000..9810a72 --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/CollectionTypeException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + + +namespace Stormtrooper; + +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) { } +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Exceptions/DrawningEquitablesException.cs b/Stormtrooper/Stormtrooper/Exceptions/DrawningEquitablesException.cs new file mode 100644 index 0000000..b8aa193 --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/DrawningEquitablesException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace Stormtrooper; + +public class DrawningEquitablesException : Exception +{ + public DrawningEquitablesException() : base("Объекты прорисовки одинаковые") { } + public DrawningEquitablesException(string message) : base(message) { } + public DrawningEquitablesException(string message, Exception exception) : + base(message, exception) { } + protected DrawningEquitablesException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Exceptions/EmptyFileExeption.cs b/Stormtrooper/Stormtrooper/Exceptions/EmptyFileExeption.cs new file mode 100644 index 0000000..050e114 --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/EmptyFileExeption.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace Stormtrooper; + +public class EmptyFileExeption : Exception +{ + public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { } + public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { } + public EmptyFileExeption(string name, string message) : base(message) { } + public EmptyFileExeption(string name, string message, Exception exception) : + base(message, exception) { } + protected EmptyFileExeption(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Exceptions/FileFormatException.cs b/Stormtrooper/Stormtrooper/Exceptions/FileFormatException.cs new file mode 100644 index 0000000..3551586 --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/FileFormatException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace Stormtrooper; + +public class FileFormatException : Exception +{ + public FileFormatException() : base() { } + public FileFormatException(string message) : base(message) { } + public FileFormatException(string name, Exception exception) : + base($"Файл {name} имеет неверный формат. Ошибка: {exception.Message}", exception) { } + protected FileFormatException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Exceptions/FileNotFoundException.cs b/Stormtrooper/Stormtrooper/Exceptions/FileNotFoundException.cs new file mode 100644 index 0000000..f03f323 --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/FileNotFoundException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace Stormtrooper; + +public class FileNotFoundException : Exception +{ + public FileNotFoundException(string name) : base($"Файл {name} не существует ") { } + public FileNotFoundException() : base() { } + public FileNotFoundException(string name, string message) : base(message) { } + public FileNotFoundException(string name, string message, Exception exception) : + base(message, exception) { } + protected FileNotFoundException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs b/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs index 3cc8154..40ae2c1 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs +++ b/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs @@ -30,7 +30,9 @@ { groupBoxTools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); buttonAddAiracft = new Button(); + buttonSortByType = new Button(); buttonRefresh = new Button(); maskedTextBox = new MaskedTextBox(); buttonGoToCheck = new Button(); @@ -52,11 +54,13 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + pictureBox1 = new PictureBox(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); menuStrip.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); SuspendLayout(); // // groupBoxTools @@ -68,7 +72,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(959, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(264, 660); + groupBoxTools.Size = new Size(264, 714); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Tag = ""; @@ -76,7 +80,9 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); panelCompanyTools.Controls.Add(buttonAddAiracft); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonGoToCheck); @@ -84,9 +90,20 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 391); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(258, 262); + panelCompanyTools.Size = new Size(258, 323); panelCompanyTools.TabIndex = 9; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(3, 272); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(252, 41); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // // buttonAddAiracft // buttonAddAiracft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; @@ -98,10 +115,21 @@ buttonAddAiracft.UseVisualStyleBackColor = true; buttonAddAiracft.Click += ButtonAddAircraft_Click; // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(3, 225); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(252, 41); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(0, 207); + buttonRefresh.Location = new Point(3, 178); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(252, 41); buttonRefresh.TabIndex = 6; @@ -112,7 +140,7 @@ // maskedTextBox // maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox.Location = new Point(0, 80); + maskedTextBox.Location = new Point(3, 51); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(252, 27); @@ -122,7 +150,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(0, 160); + buttonGoToCheck.Location = new Point(3, 131); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(252, 41); buttonGoToCheck.TabIndex = 5; @@ -133,7 +161,7 @@ // buttonRemoveAircraft // buttonRemoveAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveAircraft.Location = new Point(0, 113); + buttonRemoveAircraft.Location = new Point(3, 84); buttonRemoveAircraft.Name = "buttonRemoveAircraft"; buttonRemoveAircraft.Size = new Size(252, 41); buttonRemoveAircraft.TabIndex = 4; @@ -250,7 +278,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(959, 660); + pictureBox.Size = new Size(959, 714); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -295,11 +323,21 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // pictureBox1 + // + pictureBox1.Dock = DockStyle.Fill; + pictureBox1.Location = new Point(0, 28); + pictureBox1.Name = "pictureBox1"; + pictureBox1.Size = new Size(959, 714); + pictureBox1.TabIndex = 7; + pictureBox1.TabStop = false; + // // FormAircraftCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1223, 688); + ClientSize = new Size(1223, 742); + Controls.Add(pictureBox1); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -314,6 +352,7 @@ ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); menuStrip.ResumeLayout(false); menuStrip.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); ResumeLayout(false); PerformLayout(); } @@ -344,5 +383,8 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; + private PictureBox pictureBox1; } } \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/FormAircraftCollection.cs b/Stormtrooper/Stormtrooper/FormAircraftCollection.cs index 50b9227..a06a1e5 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftCollection.cs +++ b/Stormtrooper/Stormtrooper/FormAircraftCollection.cs @@ -44,12 +44,18 @@ public partial class FormAircraftCollection : Form private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { - panelCompanyTools.Enabled = false; + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new AircraftHangarService(pictureBox1.Width, pictureBox1.Height, + new MassiveGenericObjects()); + break; + } } /// - /// Добавление автомобиля - /// + /// Добавление самолета + /// /// /// /// private void ButtonAddAircraft_Click(object sender, EventArgs e) @@ -61,7 +67,7 @@ public partial class FormAircraftCollection : Form } /// - /// Добавление автомобиля в коллекцию + /// Добавление самолета в коллекцию /// /// private void SetAircraft(DrawningAircraft aircraft) @@ -75,7 +81,7 @@ public partial class FormAircraftCollection : Form var res = _company + aircraft; MessageBox.Show("Объект добавлен"); _logger.LogInformation($"Объект добавлен под индексом {res}"); - pictureBox.Image = _company.Show(); + pictureBox1.Image = _company.Show(); } catch (Exception ex) { @@ -109,7 +115,7 @@ public partial class FormAircraftCollection : Form var res = _company - pos; MessageBox.Show("Объект удален"); _logger.LogInformation($"Объект удален под индексом {pos}"); - pictureBox.Image = _company.Show(); + pictureBox1.Image = _company.Show(); } catch (Exception ex) { @@ -155,7 +161,7 @@ public partial class FormAircraftCollection : Form return; } - pictureBox.Image = _company.Show(); + pictureBox1.Image = _company.Show(); } /// @@ -184,7 +190,7 @@ public partial class FormAircraftCollection : Form try { - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "2")); _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); } @@ -193,7 +199,6 @@ public partial class FormAircraftCollection : Form MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } - } /// @@ -215,11 +220,13 @@ public partial class FormAircraftCollection : Form return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } + /// /// Создание компании /// @@ -234,7 +241,9 @@ public partial class FormAircraftCollection : Form } ICollectionGenericObjects? collection = - _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + _storageCollection[ + CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? + new CollectionInfo("", CollectionType.None, "")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -244,7 +253,7 @@ public partial class FormAircraftCollection : Form switch (comboBoxSelectorCompany.Text) { case "Хранилище": - _company = new AircraftHangarService(pictureBox.Width, pictureBox.Height, collection); + _company = new AircraftHangarService(pictureBox1.Width, pictureBox1.Height, collection); _logger.LogInformation("Компания создана"); break; } @@ -260,10 +269,10 @@ public partial class FormAircraftCollection : 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); } } } @@ -314,4 +323,39 @@ public partial class FormAircraftCollection : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareAircrafts(new DrawningAircraftCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareAircrafts(new DrawningAircraftCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareAircrafts(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox1.Image = _company.Show(); + } } diff --git a/Stormtrooper/Stormtrooper/FormAircraftConfig.cs b/Stormtrooper/Stormtrooper/FormAircraftConfig.cs index 951a6d2..14400c2 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftConfig.cs +++ b/Stormtrooper/Stormtrooper/FormAircraftConfig.cs @@ -48,14 +48,7 @@ public partial class FormAircraftConfig : Form /// public void AddEvent(Action aircraftDelegate) { - if (AircraftDelegate != null) - { - AircraftDelegate = aircraftDelegate; - } - else - { AircraftDelegate += aircraftDelegate; - } } /// -- 2.25.1