diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/CollectionInfo.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..d87de09 --- /dev/null +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,76 @@ +using ProjectStormTrooper.CollectionGenericObjects; + +/// +/// Класс, хранящиий информацию по коллекции +/// +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + + /// + /// Описание + /// + public string Description { get; private set; } + + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) + { + return null; + } + + return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty); + } + + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs index 2fdbafd..8702f6f 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -61,6 +61,10 @@ public class ListGenericObjects : ICollectionGenericObjects { throw new CollectionOverflowException(); } + if(_collection.Contains(obj,comparer)) + { + throw new ObjectExistsException(); + } _collection.Add(obj); return true; @@ -76,6 +80,10 @@ public class ListGenericObjects : ICollectionGenericObjects { throw new PositionOutOfCollectionException(); } + if (_collection.Contains(obj, comparer)) + { + throw new ObjectExistsException(); + } _collection.Insert(position, obj); return true; } diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs index 357bf1f..8435c93 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -66,6 +66,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects { int index = Array.IndexOf(_collection, null); + if (_collection.Contains(obj, comparer)) + { + throw new ObjectExistsException(); + } if(index >= 0) { _collection[index] = obj; @@ -82,7 +86,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects { throw new PositionOutOfCollectionException(); } - for(int i = position; i < _collection.Length; i++) + if (_collection.Contains(obj, comparer)) + { + throw new ObjectExistsException(); + } + for (int i = position; i < _collection.Length; i++) { if (_collection[i] == null) { @@ -131,7 +139,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects if(_collection?.Length > 0) { Array.Sort(_collection, comparer); - //Array.Reverse(_collection); + Array.Reverse(_collection); } } diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs index df03328..4e7a099 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs @@ -1,6 +1,7 @@ using ProjectStormTrooper.CollectionGenericObjects; using ProjectStormTrooper.Drawnings; using ProjectStormTrooper.Exceptions; +using System.Collections.Generic; using System.Text; /// @@ -13,12 +14,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл /// @@ -40,7 +41,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -50,17 +51,18 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if(name == null || _storages.ContainsKey(name)) { return; } - switch(collectionType) + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo) ){ return; } + switch(collectionInfo.CollectionType) { case CollectionType.None: return; case CollectionType.Massive: - _storages.Add(name, new MassiveGenericObjects { }); + _storages.Add(collectionInfo, new MassiveGenericObjects { }); return; case CollectionType.List: - _storages.Add(name, new ListGenericObjects { }); + _storages.Add(collectionInfo, new ListGenericObjects { }); return; } @@ -72,8 +74,9 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (name == null || !_storages.ContainsKey(name)) { return; } - _storages.Remove(name); + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (collectionInfo.Name == null || !_storages.ContainsKey(collectionInfo)) { return; } + _storages.Remove(collectionInfo); } /// @@ -81,12 +84,13 @@ public class StorageCollection /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[string collectionName] { get { - if (name == null || !_storages.ContainsKey(name)) { return null; } - return _storages[name]; + CollectionInfo collectionInfo = new CollectionInfo(collectionName,CollectionType.None,""); + if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; } + return _storages[collectionInfo]; } } /// @@ -111,7 +115,7 @@ public class StorageCollection using FileStream fs = new(filename, FileMode.Create); using StreamWriter streamWriter = new StreamWriter(fs); streamWriter.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { streamWriter.Write(Environment.NewLine); // не сохраняем пустые коллекции @@ -122,8 +126,6 @@ public class StorageCollection streamWriter.Write(value.Key); streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.GetCollectionType); - streamWriter.Write(_separatorForKeyValue); streamWriter.Write(value.Value.MaxCount); streamWriter.Write(_separatorForKeyValue); @@ -171,18 +173,17 @@ public class StorageCollection while (!streamReader.EndOfStream) { string[] record = streamReader.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - if(record.Length != 4) + if(record.Length != 3) { continue; } - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? - throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ; + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции:" + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); - - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningWarPlane() is T warPlane) @@ -201,7 +202,7 @@ public class StorageCollection } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } diff --git a/ProjectStormTrooper/ProjectStormTrooper/Exceptions/ObjectExistsException.cs b/ProjectStormTrooper/ProjectStormTrooper/Exceptions/ObjectExistsException.cs new file mode 100644 index 0000000..e5a5957 --- /dev/null +++ b/ProjectStormTrooper/ProjectStormTrooper/Exceptions/ObjectExistsException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectStormTrooper.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class ObjectExistsException : ApplicationException +{ + public ObjectExistsException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + + public ObjectExistsException() : base() { } + + public ObjectExistsException(string message) : base(message) { } + + public ObjectExistsException(string message, Exception exception) : base(message, exception) { } + + protected ObjectExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs index 3374702..9e723c7 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs @@ -64,6 +64,11 @@ namespace ProjectStormTrooper _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } + catch(ObjectExistsException ex) + { + MessageBox.Show("Такой объект есть в коллекции"); + _logger.LogWarning($"Добавление существующего объекта: {ex.Message}"); + } } @@ -202,7 +207,6 @@ namespace ProjectStormTrooper { collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}"); RerfreshListBoxItems(); @@ -240,7 +244,7 @@ namespace ProjectStormTrooper listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; + string? colName = _storageCollection.Keys?[i].Name; if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName);