diff --git a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/CollectionInfo.cs b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..5ab4f8c --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,82 @@ +namespace ProjectBulldozer.CollectionGenericObjects; + +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + + /// + /// Описание + /// + public string Description { get; private set; } + + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string + description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, + StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) + { + return null; + } + + return new CollectionInfo(strs[0], + (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty); + } + + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + + public bool IsEmpty() + { + if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true; + return false; + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/StorageCollection.cs b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/StorageCollection.cs index a6ac75f..dffd990 100644 --- a/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectBulldozer/ProjectBulldozer/CollectionGenericObjects/StorageCollection.cs @@ -19,12 +19,12 @@ internal class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -45,36 +45,36 @@ internal class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище /// - /// Название коллекции - /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + /// тип коллекции + public void AddCollection(CollectionInfo collectionInfo) { // TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO Прописать логику для добавления - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - else if (collectionType == CollectionType.Massive) - _storages[name] = new MassiveGenericObjects(); - else if (collectionType == CollectionType.List) - _storages[name] = new ListGenericObjects(); + if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo); + if (collectionInfo.CollectionType == CollectionType.None) + throw new CollectionTypeException("Пустой тип коллекции"); + if (collectionInfo.CollectionType == CollectionType.Massive) + _storages[collectionInfo] = new MassiveGenericObjects(); + else if (collectionInfo.CollectionType == CollectionType.List) + _storages[collectionInfo] = new ListGenericObjects(); } /// /// Удаление коллекции /// - /// Название коллекции - public void DelCollection(string name) + /// Название коллекции + public void DelCollection(CollectionInfo collectionInfo) { // TODO Прописать логику для удаления коллекции - if (_storages.ContainsKey(name)) - _storages.Remove(name); + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); } /// @@ -82,13 +82,13 @@ internal class StorageCollection /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[CollectionInfo collectionInfo] { get { // TODO Продумать логику получения объекта - if (_storages.ContainsKey(name)) - return _storages[name]; + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } @@ -98,7 +98,7 @@ internal class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { @@ -113,7 +113,7 @@ internal class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { StringBuilder sb = new(); sb.Append(Environment.NewLine); @@ -125,8 +125,6 @@ internal class StorageCollection sb.Append(value.Key); sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); sb.Append(value.Value.MaxCount); sb.Append(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) @@ -144,8 +142,6 @@ internal class StorageCollection writer.Write(sb); } } - - return true; } /// @@ -153,68 +149,11 @@ internal class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; - } - - using (StreamReader fs = File.OpenText(filename)) - { - string str = fs.ReadLine(); - if (string.IsNullOrEmpty(str)) - { - throw new FileNotFoundException(filename); - - } - - if (!str.StartsWith(_collectionKey)) - { - throw new FileFormatException(filename); - } - - _storages.Clear(); - string strs = ""; - while ((strs = fs.ReadLine()) != null) - { - string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) - { - continue; - } - - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); - } - - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) - { - if (elem?.CreateDrawningMachine() is T ship) - { - try - { - collection.Insert(ship); - } - catch (Exception ex) - { - throw new FileFormatException(filename, ex); - } - } - } - - _storages.Add(record[0], collection); - } - - return true; - } - if (!File.Exists(filename)) - { + throw new FileNotFoundException(filename); } using (StreamReader fs = File.OpenText(filename)) @@ -227,6 +166,7 @@ internal class StorageCollection if (!str.StartsWith(_collectionKey)) { + throw new FileFormatException(filename); } _storages.Clear(); @@ -234,41 +174,38 @@ internal class StorageCollection while ((strs = fs.ReadLine()) != null) { string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - } + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]); - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); + + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningMachine() is T ship) + if (elem?.CreateDrawningMachine() is T macine) { try { - if (collection.Insert(ship) == -1) - { - throw new CollectionTypeException("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(macine); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - throw ex.InnerException!; + throw new FileFormatException(filename, ex); } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } - - return true; } } /// @@ -276,7 +213,8 @@ internal class StorageCollection /// /// /// - private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + private static ICollectionGenericObjects? + CreateCollection(CollectionType collectionType) { return collectionType switch { diff --git a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawingMachineCompareByColor.cs b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningMachineCompareByColor.cs similarity index 93% rename from ProjectBulldozer/ProjectBulldozer/Drawnings/DrawingMachineCompareByColor.cs rename to ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningMachineCompareByColor.cs index a749d5d..2c4323b 100644 --- a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawingMachineCompareByColor.cs +++ b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningMachineCompareByColor.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace ProjectBulldozer.Drawnings; -internal class DrawingMachineCompareByColor : IComparer +internal class DrawningMachineCompareByColor : IComparer { public int Compare(DrawningTrackedMachine? x, DrawningTrackedMachine? y) { diff --git a/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionAlreadyExistsException.cs b/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionAlreadyExistsException.cs index ea5965c..5cb79ae 100644 --- a/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionAlreadyExistsException.cs +++ b/ProjectBulldozer/ProjectBulldozer/Exceptions/CollectionAlreadyExistsException.cs @@ -1,13 +1,15 @@ -using System.Runtime.Serialization; +using ProjectBulldozer.CollectionGenericObjects; +using System.Runtime.Serialization; namespace ProjectBulldozer.Exceptions; [Serializable] public class CollectionAlreadyExistsException : Exception { public CollectionAlreadyExistsException() : base() { } - public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { } + public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { } public CollectionAlreadyExistsException(string name, Exception exception) : - base($"Коллекция {name} уже существует!", exception) { } + base($"Коллекция {name} уже существует!", exception) + { } protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } } \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.Designer.cs b/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.Designer.cs index 4c6f226..aa3555d 100644 --- a/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.Designer.cs +++ b/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.Designer.cs @@ -30,6 +30,8 @@ { groupBoxTools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); buttonAddMachine = new Button(); maskedTextBox = new MaskedTextBox(); buttonRefresh = new Button(); @@ -68,13 +70,15 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(749, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(231, 671); + groupBoxTools.Size = new Size(231, 694); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddMachine); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonRefresh); @@ -83,13 +87,33 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 377); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(225, 288); + panelCompanyTools.Size = new Size(225, 311); panelCompanyTools.TabIndex = 9; // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(3, 276); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(219, 29); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Location = new Point(3, 241); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(219, 29); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // buttonAddMachine // buttonAddMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddMachine.Location = new Point(3, 28); + buttonAddMachine.Location = new Point(3, 4); buttonAddMachine.Name = "buttonAddMachine"; buttonAddMachine.Size = new Size(219, 49); buttonAddMachine.TabIndex = 0; @@ -100,7 +124,7 @@ // maskedTextBox // maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox.Location = new Point(3, 114); + maskedTextBox.Location = new Point(3, 77); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(219, 27); @@ -110,7 +134,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 241); + buttonRefresh.Location = new Point(3, 194); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(219, 41); buttonRefresh.TabIndex = 6; @@ -121,9 +145,9 @@ // buttonRemoveMachine // buttonRemoveMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveMachine.Location = new Point(3, 147); + buttonRemoveMachine.Location = new Point(3, 110); buttonRemoveMachine.Name = "buttonRemoveMachine"; - buttonRemoveMachine.Size = new Size(219, 41); + buttonRemoveMachine.Size = new Size(219, 31); buttonRemoveMachine.TabIndex = 2; buttonRemoveMachine.Text = "Удалить машину"; buttonRemoveMachine.UseVisualStyleBackColor = true; @@ -132,9 +156,9 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 194); + buttonGoToCheck.Location = new Point(3, 157); buttonGoToCheck.Name = "buttonGoToCheck"; - buttonGoToCheck.Size = new Size(219, 41); + buttonGoToCheck.Size = new Size(219, 31); buttonGoToCheck.TabIndex = 3; buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.UseVisualStyleBackColor = true; @@ -248,7 +272,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(749, 671); + pictureBox.Size = new Size(749, 694); pictureBox.TabIndex = 5; pictureBox.TabStop = false; // @@ -297,7 +321,7 @@ // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(980, 699); + ClientSize = new Size(980, 722); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -342,5 +366,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.cs b/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.cs index dd498e6..3e05f61 100644 --- a/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.cs +++ b/ProjectBulldozer/ProjectBulldozer/FormMachineCollectoin.cs @@ -64,7 +64,7 @@ public partial class FormMachineCollectoin : Form FormMachineConfig form = new(); form.Show(); form.AddEvent(SetMachine); - + } /// @@ -205,7 +205,7 @@ public partial class FormMachineCollectoin : Form } try { - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ")); _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); } @@ -236,7 +236,9 @@ public partial class FormMachineCollectoin : Form { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); + _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } @@ -248,10 +250,10 @@ public partial class FormMachineCollectoin : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) + CollectionInfo? col = _storageCollection.Keys?[i]; + if (!col!.IsEmpty()) { - listBoxCollection.Items.Add(colName); + listBoxCollection.Items.Add(col); } } } @@ -269,7 +271,10 @@ public partial class FormMachineCollectoin : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = + _storageCollection[ + CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? + new CollectionInfo("", CollectionType.None, "")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -341,5 +346,40 @@ public partial class FormMachineCollectoin : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareCars(new DrawningMachineCompareByType()); + } + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareCars(new DrawningMachineCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareCars(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + } diff --git a/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj b/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj index 7b1485a..e2255c1 100644 --- a/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj +++ b/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj @@ -8,52 +8,31 @@ enable - - - - - - - - - - - - - - - - - - - - - - - - - + + + True + True + Resources.resx + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + + + + + + - - - True - True - Resources.resx - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - - - - - - Always - - \ No newline at end of file