diff --git a/Sailboat/Sailboat/BoatsGenericCollection.cs b/Sailboat/Sailboat/BoatsGenericCollection.cs index ec32012..8ba60f6 100644 --- a/Sailboat/Sailboat/BoatsGenericCollection.cs +++ b/Sailboat/Sailboat/BoatsGenericCollection.cs @@ -41,6 +41,8 @@ namespace Sailboat.Generics /// Получение объектов коллекции /// public IEnumerable GetBoats => _collection.GetBoats(); + public void Sort(IComparer comparer) => _collection.SortSet(comparer); + /// /// Конструктор /// @@ -60,13 +62,13 @@ namespace Sailboat.Generics /// /// /// - public static bool operator +(BoatsGenericCollection collect, T? obj) + public static int operator +(BoatsGenericCollection collect, T? obj) { if (obj == null) { - return false; + return -1; } - return (bool)collect?._collection.Insert(obj); + return collect._collection.Insert(obj, new DrawingBoatEqutables()); } /// /// Перегрузка оператора вычитания @@ -74,14 +76,11 @@ namespace Sailboat.Generics /// /// /// - public static bool operator -(BoatsGenericCollection collect, int pos) + public static T? operator -(BoatsGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - } collect._collection.Remove(pos); - return false; + return obj; } /// diff --git a/Sailboat/Sailboat/BoatsGenericStorage.cs b/Sailboat/Sailboat/BoatsGenericStorage.cs index 33f26c8..b939182 100644 --- a/Sailboat/Sailboat/BoatsGenericStorage.cs +++ b/Sailboat/Sailboat/BoatsGenericStorage.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using Sailboat.DrawingObjects; using Sailboat.MovementStrategy; +using Sailboat.Exceptions; namespace Sailboat.Generics { @@ -13,11 +14,11 @@ namespace Sailboat.Generics /// /// Словарь (хранилище) /// - readonly Dictionary> _boatStorages; + readonly Dictionary> _boatStorages; /// /// Возвращение списка названий наборов /// - public List Keys => _boatStorages.Keys.ToList(); + public List Keys => _boatStorages.Keys.ToList(); /// /// Ширина окна отрисовки /// @@ -45,8 +46,7 @@ namespace Sailboat.Generics /// public BoatsGenericStorage(int pictureWidth, int pictureHeight) { - _boatStorages = new Dictionary>(); + _boatStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } @@ -56,11 +56,7 @@ namespace Sailboat.Generics /// Название набора public void AddSet(string name) { - if (_boatStorages.ContainsKey(name)) - { - return; - } - _boatStorages[name] = new BoatsGenericCollection(_pictureWidth, _pictureHeight); + _boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), new BoatsGenericCollection(_pictureWidth, _pictureHeight)); } /// /// Удаление набора @@ -68,26 +64,22 @@ namespace Sailboat.Generics /// Название набора public void DelSet(string name) { - if (!_boatStorages.ContainsKey(name)) - { + if (!_boatStorages.ContainsKey(new BoatsCollectionInfo(name, string.Empty))) return; - } - _boatStorages.Remove(name); + _boatStorages.Remove(new BoatsCollectionInfo(name, string.Empty)); } /// /// Доступ к набору /// /// /// - public BoatsGenericCollection? - this[string ind] + public BoatsGenericCollection? this[string ind] { get { - if (_boatStorages.ContainsKey(ind)) - { - return _boatStorages[ind]; - } + BoatsCollectionInfo indObj = new BoatsCollectionInfo(ind, string.Empty); + if (_boatStorages.ContainsKey(indObj)) + return _boatStorages[indObj]; return null; } } @@ -96,32 +88,36 @@ namespace Sailboat.Generics /// Сохранение информации по лодкам в хранилище в файл /// /// Путь и имя файла - public bool SaveData(string filename) + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } + StringBuilder data = new(); - foreach (KeyValuePair> record in _boatStorages) + foreach (KeyValuePair> record in _boatStorages) { StringBuilder records = new(); foreach (DrawingBoat? elem in record.Value.GetBoats) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } - data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}"); + } if (data.Length == 0) { - throw new Exception("Невалидная операция, нет данных для сохранения"); + throw new InvalidOperationException("Файл не найден, невалидная операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { - writer.Write($"SailboatStorage{Environment.NewLine}{data}"); + writer.WriteLine("BoatStorage"); + writer.Write(data.ToString()); } - return true; } + /// /// Загрузка информации по лодкам в хранилище из файла /// @@ -131,55 +127,43 @@ namespace Sailboat.Generics { if (!File.Exists(filename)) { - throw new Exception("Файл не найден"); + throw new FileNotFoundException("Файл не найден"); } - - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader sr = new(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) + string str = sr.ReadLine(); + if (str == null || str.Length == 0) { - bufferTextFromFile += temp.GetString(b); + throw new NullReferenceException("Нет данных для загрузки"); } - } - var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, - StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - throw new Exception("Нет данных для загрузки"); - } - if (!strs[0].StartsWith("BoatStorage")) - { - //если нет такой записи, то это не те данные - throw new Exception("Неверный формат данных"); - } - - _boatStorages.Clear(); - foreach (string data in strs) - { - string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) + if (!str.StartsWith("BoatStorage")) { - continue; + throw new InvalidDataException("Неверный формат данных"); } - BoatsGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + _boatStorages.Clear(); + while ((str = sr.ReadLine()) != null) { - DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); - if (boat != null) + string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) { - if (!(collection + boat)) + continue; + } + BoatsGenericCollection collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set.Reverse()) + { + DrawingBoat? truck = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); + if (truck != null) { - throw new Exception("Ошибка добавления в коллекцию"); + if (collection + truck == -1) + { + throw new ApplicationException("Ошибка добавления в коллекцию"); + } } } + _boatStorages.Add(new BoatsCollectionInfo(record[0], string.Empty), collection); } - _boatStorages.Add(record[0], collection); } - } } } \ No newline at end of file diff --git a/Sailboat/Sailboat/FormBoatCollection.Designer.cs b/Sailboat/Sailboat/FormBoatCollection.Designer.cs index ba990d9..dc339b9 100644 --- a/Sailboat/Sailboat/FormBoatCollection.Designer.cs +++ b/Sailboat/Sailboat/FormBoatCollection.Designer.cs @@ -77,6 +77,7 @@ namespace Sailboat panelTools.Name = "panelTools"; panelTools.Size = new Size(183, 542); panelTools.TabIndex = 1; + this.panelTools.TabIndex = 1; // // panelCollection // @@ -182,6 +183,7 @@ namespace Sailboat menuStrip.Padding = new Padding(5, 2, 0, 2); menuStrip.Size = new Size(183, 24); menuStrip.TabIndex = 5; + this.menuStrip.TabIndex = 5; // // toolStripMenuItem1 // @@ -194,6 +196,8 @@ namespace Sailboat ToolStripMenuItem.Name = "ToolStripMenuItem"; ToolStripMenuItem.Size = new Size(48, 20); ToolStripMenuItem.Text = "Файл"; + this.ToolStripMenuItem.Size = new System.Drawing.Size(59, 24); + this.ToolStripMenuItem.Text = "Файл"; // // SaveToolStripMenuItem // @@ -218,6 +222,26 @@ namespace Sailboat // saveFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + this.buttonSortByType.Location = new System.Drawing.Point(20, 448); + this.buttonSortByType.Name = "buttonSortByType"; + this.buttonSortByType.Size = new System.Drawing.Size(180, 34); + this.buttonSortByType.TabIndex = 6; + this.buttonSortByType.Text = "Сортировать по типу"; + this.buttonSortByType.UseVisualStyleBackColor = true; + this.buttonSortByType.Click += new System.EventHandler(this.buttonSortByType_Click); + // + // buttonSortByColor + // + this.buttonSortByColor.Location = new System.Drawing.Point(20, 488); + this.buttonSortByColor.Name = "buttonSortByColor"; + this.buttonSortByColor.Size = new System.Drawing.Size(180, 34); + this.buttonSortByColor.TabIndex = 7; + this.buttonSortByColor.Text = "Сортировать по цвету"; + this.buttonSortByColor.UseVisualStyleBackColor = true; + this.buttonSortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click); + // // FormBoatCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -260,5 +284,7 @@ namespace Sailboat private ToolStripMenuItem LoadToolStripMenuItem; private OpenFileDialog openFileDialog; private SaveFileDialog saveFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/Sailboat/Sailboat/FormBoatCollection.cs b/Sailboat/Sailboat/FormBoatCollection.cs index d935a9a..00050b0 100644 --- a/Sailboat/Sailboat/FormBoatCollection.cs +++ b/Sailboat/Sailboat/FormBoatCollection.cs @@ -8,10 +8,11 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Extensions.Logging; + using Sailboat.DrawingObjects; -using Sailboat.Exceptions; using Sailboat.Generics; using Sailboat.MovementStrategy; +using Sailboat.Exceptions; namespace Sailboat { @@ -30,12 +31,10 @@ namespace Sailboat { int index = listBoxStorages.SelectedIndex; listBoxStorages.Items.Clear(); - for (int i = 0; i < _storage.Keys.Count; i++) { - listBoxStorages.Items.Add(_storage.Keys[i]); + listBoxStorages.Items.Add(_storage.Keys[i].Name); } - if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count)) { @@ -78,20 +77,16 @@ namespace Sailboat _logger.LogWarning("Добавление пустого объекта"); return; } - try + if (obj + drawingBoat != -1) { - if (obj + drawingBoat) - { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowBoats(); - _logger.LogInformation($"Объект {obj.GetType()} добавлен"); - - } + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowBoats(); + _logger.LogInformation($"Объект {obj.GetType()} добавлен"); } - catch (StorageOverflowException ex) + else { - MessageBox.Show(ex.Message); - _logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation($"Не удалось добавить объект"); } } @@ -132,6 +127,8 @@ namespace Sailboat MessageBox.Show(ex.Message); _logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}"); } + + } private void buttonRefreshCollection_Click(object sender, EventArgs e) @@ -140,7 +137,8 @@ namespace Sailboat { return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? + string.Empty]; if (obj == null) { return; @@ -194,7 +192,6 @@ namespace Sailboat _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}"); - } catch (Exception ex) { @@ -222,5 +219,25 @@ namespace Sailboat } } } + + private void buttonSortByType_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByType()); + + private void buttonSortByColor_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByColor()); + + private void CompareBoats(IComparer comparer) + { + if (listBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? + string.Empty]; + if (obj == null) + { + return; + } + obj.Sort(comparer); + pictureBoxCollection.Image = obj.ShowBoats(); + } } } diff --git a/Sailboat/Sailboat/FormSailboat.Designer.cs b/Sailboat/Sailboat/FormSailboat.Designer.cs index a7469f0..a8eefa0 100644 --- a/Sailboat/Sailboat/FormSailboat.Designer.cs +++ b/Sailboat/Sailboat/FormSailboat.Designer.cs @@ -174,6 +174,9 @@ this.buttonSelectBoat.Text = "Выбрать лодку"; this.buttonSelectBoat.UseVisualStyleBackColor = true; this.buttonSelectBoat.Click += new System.EventHandler(this.buttonSelectBoat_Click); + // + // FormSailboat + // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(882, 453); diff --git a/Sailboat/Sailboat/FormSailboat.cs b/Sailboat/Sailboat/FormSailboat.cs index 3cf3272..bd6e458 100644 --- a/Sailboat/Sailboat/FormSailboat.cs +++ b/Sailboat/Sailboat/FormSailboat.cs @@ -129,7 +129,6 @@ namespace Sailboat { SelectedBoat = _drawingBoat; DialogResult = DialogResult.OK; - } } -} \ No newline at end of file +} \ No newline at end of file diff --git a/Sailboat/Sailboat/FormSailboat.resx b/Sailboat/Sailboat/FormSailboat.resx index c84c464..6d82dad 100644 --- a/Sailboat/Sailboat/FormSailboat.resx +++ b/Sailboat/Sailboat/FormSailboat.resx @@ -1,64 +1,4 @@ - - - +