diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/AbstractCompany.cs similarity index 88% rename from ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs rename to ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/AbstractCompany.cs index b290193..8d7601b 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/AbstractCompany.cs @@ -54,9 +54,10 @@ public abstract class AbstractCompany /// Компания /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningBoat boat) + public static int operator +(AbstractCompany company, DrawningBoat aircraft) { - return company._collection?.Insert(boat) ?? -1; + return company._collection?.Insert(aircraft, new DrawningBoatEqutables()) ?? + throw new DrawningEquitablesException(); } /// /// Перегрузка оператора удаления для класса @@ -77,6 +78,13 @@ public abstract class AbstractCompany Random rnd = new(); return _collection?.Get(rnd.Next(GetMaxCount)); } + + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод всей коллекции /// @@ -85,7 +93,7 @@ public abstract class AbstractCompany { Bitmap bitmap = new(_pictureWidth, _pictureHeight); Graphics graphics = Graphics.FromImage(bitmap); - DrawBackgound(graphics); + DrawBackground(graphics); SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) @@ -106,7 +114,7 @@ public abstract class AbstractCompany /// Вывод заднего фона /// /// - protected abstract void DrawBackgound(Graphics g); + protected abstract void DrawBackground(Graphics g); /// /// Расстановка объектов /// diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/BoatHarborService.cs similarity index 97% rename from ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs rename to ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/BoatHarborService.cs index 288b017..4fa4efd 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/BoatHarborService.cs @@ -24,7 +24,7 @@ public class BoatHarborService : AbstractCompany { } - protected override void DrawBackgound(Graphics g) + protected override void DrawBackground(Graphics g) { int width = _pictureWidth / _placeSizeWidth; int height = _pictureHeight / _placeSizeHeight; diff --git a/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/CollectionInfo.cs b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..26ba21e --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.CollectiongGenericObjects; + +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/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/CollectionType .cs b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/CollectionType .cs similarity index 100% rename from ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/CollectionType .cs rename to ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/CollectionType .cs diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ICollectionGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/ICollectionGenericObjects.cs similarity index 81% rename from ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ICollectionGenericObjects.cs rename to ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/ICollectionGenericObjects.cs index 113edbc..30a494c 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -27,15 +27,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); /// /// Удаление объекта из коллекции с конкретной позиции /// @@ -59,4 +62,10 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/ListGenericObjects.cs similarity index 70% rename from ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs rename to ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/ListGenericObjects.cs index 7e700ea..e69ebed 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/ListGenericObjects.cs @@ -35,18 +35,40 @@ public class ListGenericObjects : ICollectionGenericObjects if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (comparer != null) + { + 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; } @@ -66,4 +88,9 @@ public class ListGenericObjects : ICollectionGenericObjects } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/MassiveGenericObjects.cs similarity index 77% rename from ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs rename to ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/MassiveGenericObjects.cs index 2666ad8..e23f212 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/MassiveGenericObjects.cs @@ -19,6 +19,10 @@ namespace ProjectCatamaran.CollectiongGenericObjects; /// private T?[] _collection; public int Count => _collection.Length; + + /// + /// Установка максимального кол-ва объектов + /// public int MaxCount { get @@ -58,9 +62,18 @@ namespace ProjectCatamaran.CollectiongGenericObjects; if (_collection[position] == null) throw new ObjectNotFoundException(position); 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++) { if (_collection[i] == null) @@ -71,16 +84,25 @@ namespace ProjectCatamaran.CollectiongGenericObjects; } 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; int index; @@ -134,4 +156,11 @@ namespace ProjectCatamaran.CollectiongGenericObjects; yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + List value = new List(_collection); + value.Sort(comparer); + value.CopyTo(_collection, 0); + } } diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/StorageCollection.cs similarity index 52% rename from ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs rename to ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/StorageCollection.cs index 85a7fb3..abf5b54 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectionGenericObjects/StorageCollection.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; namespace ProjectCatamaran.CollectiongGenericObjects; @@ -19,11 +18,11 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -45,48 +44,43 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище /// /// Название коллекции /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(CollectionInfo collectionInfo) { - if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)) - { - if (collectionType == CollectionType.List) - { - _storages.Add(name, new ListGenericObjects()); - } - else if (collectionType == CollectionType.Massive) - { - _storages.Add(name, new MassiveGenericObjects()); - } - } + 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) { - 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.ContainsKey(name)) - { - return _storages[name]; - } + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } @@ -99,51 +93,43 @@ public class StorageCollection { 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); } } } @@ -158,56 +144,58 @@ public class StorageCollection { if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + throw new Exceptions.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 Exception("В файле нет данных"); + string str = fs.ReadLine(); + if (string.IsNullOrEmpty(str)) + { + throw new EmptyFileExeption(filename); + } + + if (!str.StartsWith(_collectionKey)) + { + throw new Exceptions.FileFormatException(filename); + } _storages.Clear(); - - while ((str = sr.ReadLine()) != null) + string strs = ""; + while ((strs = fs.ReadLine()) != null) { - string[] record = str.Split(_separatorForKeyValue); - - if (record.Length != 4) + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new Exception("Не удалось создать коллекцию"); - } + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]); - collection.MaxCount = Convert.ToInt32(record[2]); + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBoat() is T boat) + if (elem?.CreateDrawningBoat() is T ship) { try { - if (collection.Insert(boat) == -1) - { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(ship); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - throw new Exception("Коллекция переполнена", ex); + throw new Exceptions.FileFormatException(filename, ex); } } } - _storages.Add(record[0], collection); + + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoatCompareByColor.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoatCompareByColor.cs new file mode 100644 index 0000000..b54487e --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoatCompareByColor.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Drawnings; +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningBoatCompareByColor : IComparer +{ + public int Compare(DrawningBoat? x, DrawningBoat? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityBoat == null) + { + return 1; + } + + if (y == null || y.EntityBoat == null) + { + return -1; + } + + if (ToHex(x.EntityBoat.BodyColor) != ToHex(y.EntityBoat.BodyColor)) + { + return String.Compare(ToHex(x.EntityBoat.BodyColor), ToHex(y.EntityBoat.BodyColor), + StringComparison.Ordinal); + } + + var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight); + } + + private static String ToHex(Color c) + => $"#{c.R:X2}{c.G:X2}{c.B:X2}"; +} diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoatCompareByType.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoatCompareByType.cs new file mode 100644 index 0000000..d70b089 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoatCompareByType.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Drawnings; +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningBoatCompareByType : IComparer +{ + public int Compare(DrawningBoat? x, DrawningBoat? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityBoat == null) + { + return 1; + } + + if (y == null || y.EntityBoat == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight); + } +} diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoatEqutables.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoatEqutables.cs new file mode 100644 index 0000000..b73752e --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoatEqutables.cs @@ -0,0 +1,72 @@ +using ProjectCatamaran.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Drawnings; + +/// +/// Реализация сравнения двух объектов класс-прорисовки +/// +internal class DrawningBoatEqutables : IEqualityComparer +{ + public bool Equals(DrawningBoat? x, DrawningBoat? 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.EntityBoat!= null && y.EntityBoat != null && x.EntityBoat.Speed != y.EntityBoat.Speed) + { + return false; + } + + if (x.EntityBoat.Weight != y.EntityBoat.Weight) + { + return false; + } + + if (x.EntityBoat.BodyColor != y.EntityBoat.BodyColor) + { + return false; + } + if (x is DrawningCatamaran && y is DrawningCatamaran) + { + if (((EntityCatamaran)x.EntityBoat).AdditionalColor != + ((EntityCatamaran)y.EntityBoat).AdditionalColor) + { + return false; + } + if (((EntityCatamaran)x.EntityBoat).Sail != + ((EntityCatamaran)y.EntityBoat).Sail) + { + return false; + } + if (((EntityCatamaran)x.EntityBoat).Leftfloater != + ((EntityCatamaran)y.EntityBoat).Leftfloater) + { + return false; + } + if (((EntityCatamaran)x.EntityBoat).Rightfloater != + ((EntityCatamaran)y.EntityBoat).Rightfloater) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningBoat obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionAlreadyExistsException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..99f327f --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,20 @@ +using ProjectCatamaran.CollectiongGenericObjects; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Exceptions; + +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/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionInfoException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionInfoException.cs new file mode 100644 index 0000000..7d4224c --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionInfoException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.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/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionInsertException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionInsertException.cs new file mode 100644 index 0000000..4211568 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionInsertException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.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/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionTypeException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionTypeException.cs new file mode 100644 index 0000000..c1ba365 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionTypeException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Exceptions; + +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/ProjectCatamaran/ProjectCatamaran/Exceptions/DrawningEquitablesException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/DrawningEquitablesException.cs new file mode 100644 index 0000000..959fe80 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/DrawningEquitablesException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Exceptions; + +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) { } +} diff --git a/ProjectCatamaran/ProjectCatamaran/Exceptions/EmptyFileExeption.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/EmptyFileExeption.cs new file mode 100644 index 0000000..555d742 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/EmptyFileExeption.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Exceptions; + +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) { } +} diff --git a/ProjectCatamaran/ProjectCatamaran/Exceptions/FileFormatException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/FileFormatException.cs new file mode 100644 index 0000000..159ea60 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/FileFormatException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; + + +namespace ProjectCatamaran.Exceptions; + +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/ProjectCatamaran/ProjectCatamaran/Exceptions/FileNotFoundException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/FileNotFoundException.cs new file mode 100644 index 0000000..9cbf3b0 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/FileNotFoundException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + + +namespace ProjectCatamaran.Exceptions; + +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/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.Designer.cs b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.Designer.cs index 1917bea..23d2a92 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.Designer.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.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(863, 28); + groupBoxTools.Location = new Point(876, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(279, 626); + groupBoxTools.Size = new Size(279, 666); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddBoat); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonRefresh); @@ -82,9 +86,9 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 394); + panelCompanyTools.Location = new Point(3, 388); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(273, 229); + panelCompanyTools.Size = new Size(273, 275); panelCompanyTools.TabIndex = 8; // // buttonAddBoat @@ -101,7 +105,7 @@ // maskedTextBoxPosition // maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBoxPosition.Location = new Point(3, 80); + maskedTextBoxPosition.Location = new Point(3, 41); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(267, 27); @@ -111,7 +115,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 181); + buttonRefresh.Location = new Point(4, 142); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(267, 31); buttonRefresh.TabIndex = 6; @@ -122,7 +126,7 @@ // buttonRemoveBoat // buttonRemoveBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveBoat.Location = new Point(3, 113); + buttonRemoveBoat.Location = new Point(3, 74); buttonRemoveBoat.Name = "buttonRemoveBoat"; buttonRemoveBoat.Size = new Size(267, 27); buttonRemoveBoat.TabIndex = 4; @@ -133,7 +137,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(4, 146); + buttonGoToCheck.Location = new Point(4, 107); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(266, 29); buttonGoToCheck.TabIndex = 5; @@ -249,7 +253,7 @@ pictureBoxBoat.Dock = DockStyle.Fill; pictureBoxBoat.Location = new Point(0, 28); pictureBoxBoat.Name = "pictureBoxBoat"; - pictureBoxBoat.Size = new Size(863, 626); + pictureBoxBoat.Size = new Size(876, 666); pictureBoxBoat.TabIndex = 1; pictureBoxBoat.TabStop = false; // @@ -259,7 +263,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1142, 28); + menuStrip.Size = new Size(1155, 28); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip"; // @@ -294,11 +298,33 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(4, 232); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(267, 31); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(4, 197); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(266, 29); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // FormBoatCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1142, 654); + ClientSize = new Size(1155, 694); Controls.Add(pictureBoxBoat); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -343,5 +369,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs index e4da5eb..949a319 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs @@ -25,7 +25,7 @@ public partial class FormBoatCollection : Form /// /// Компания /// - private AbstractCompany? _company = null; + private AbstractCompany? _company; /// /// Конструктор @@ -37,7 +37,6 @@ public partial class FormBoatCollection : Form InitializeComponent(); _storageCollection = new(); _logger = logger; - _logger.LogInformation("Форма загрузилась"); } /// @@ -47,7 +46,13 @@ public partial class FormBoatCollection : Form /// private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { - panelCompanyTools.Enabled = false; + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new BoatHarborService(pictureBoxBoat.Width, pictureBoxBoat.Height, + new MassiveGenericObjects()); + break; + } } @@ -70,11 +75,11 @@ public partial class FormBoatCollection : Form /// private void SetBoat(DrawningBoat boat) { - if (_company == null || boat == null) - { - return; - } - try + if (_company == null || boat == null) + { + return; + } + try { var res = _company + boat; MessageBox.Show("Объект добавлен"); @@ -138,32 +143,24 @@ public partial class FormBoatCollection : Form DrawningBoat? boat = null; int counter = 100; - try + while (boat == null) { - while (boat == null) + boat = _company.GetRandomObject(); + counter--; + if (counter <= 0) { - boat = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } + break; } - if (boat == null) - { - return; - } - FormCatamaran form = new() - { - SetBoat = boat - }; - form.ShowDialog(); } - catch (Exception ex) - + if (boat == null) { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; } + FormCatamaran form = new() + { + SetBoat = boat + }; + form.ShowDialog(); } /// @@ -188,33 +185,34 @@ public partial class FormBoatCollection : Form /// private void ButtonCollectionAdd_Click(object sender, EventArgs e) { - - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || + (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } + + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + try { - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) - { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "2")); + _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); - _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } catch (Exception ex) { - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } - RerfreshListBoxItems(); } /// @@ -224,26 +222,22 @@ public partial class FormBoatCollection : Form /// private void ButtonCollectionDel_Click(object sender, EventArgs e) { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - try + + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { - return; - } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); - _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); - } - catch (Exception ex) - { - _logger.LogError("Ошибка: {Message}", ex.Message); + return; } + + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); + _logger.LogInformation("Коллекция удалена"); + RerfreshListBoxItems(); } /// @@ -259,7 +253,10 @@ public partial class FormBoatCollection : 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("Коллекция не проинициализирована"); @@ -270,12 +267,12 @@ public partial class FormBoatCollection : Form { case "Хранилище": _company = new BoatHarborService(pictureBoxBoat.Width, pictureBoxBoat.Height, collection); + _logger.LogInformation("Компания создана"); break; } panelCompanyTools.Enabled = true; RerfreshListBoxItems(); - } /// /// Обновление списка в listBoxCollection @@ -285,10 +282,10 @@ public partial class FormBoatCollection : 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); } } } @@ -340,4 +337,39 @@ public partial class FormBoatCollection : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareBoat(new DrawningBoatCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareBoat(new DrawningBoatCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareBoat(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBoxBoat.Image = _company.Show(); + } }