diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs b/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs index 9aec61a..314d3b0 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs @@ -73,6 +73,11 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects { return Name.GetHashCode(); } + public bool IsEmpty() + { + if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true; + return false; + } } } diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs index 88ce44a..b2a00c1 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -42,7 +42,7 @@ where T : DrawningLocomotive // TODO Прописать логику для добавления if (_storages.ContainsKey(collectionInfo)) throw new CollectionExistsException(collectionInfo); if (collectionInfo.CollectionType == CollectionType.None) - throw new CollectionNoTypeException("Пустой тип коллекции"); + throw new CollectionNoTypeException("Отсутсвует тип коллекции"); if (collectionInfo.CollectionType == CollectionType.Massive) _storages[collectionInfo] = new MassiveGenericObjects(); else if (collectionInfo.CollectionType == CollectionType.List) @@ -53,28 +53,24 @@ where T : DrawningLocomotive /// Удаление коллекции /// /// Название коллекции - public void DelCollection(string name) + public void DelCollection(CollectionInfo collectionInfo) { - if (_storages.ContainsKey(name)) - { - _storages.Remove(name); - } // TODO Прописать логику для удаления коллекции + 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]; - } // TODO Продумать логику получения объекта + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } @@ -107,41 +103,46 @@ where T : DrawningLocomotive { if (_storages.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + throw new EmptyFileExeption(); } + if (File.Exists(filename)) { File.Delete(filename); } - StringBuilder sb = new(); - sb.Append(_collectionKey); - foreach (KeyValuePair> - value in _storages) + + using (StreamWriter writer = new StreamWriter(filename)) { - sb.Append(Environment.NewLine); - // не сохраняем пустые коллекции - if (value.Value.Count == 0) + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - 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)) + StringBuilder sb = new(); + sb.Append(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } - sb.Append(data); - sb.Append(_separatorItems); + + 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; + } + + sb.Append(data); + sb.Append(_separatorItems); + } + + writer.Write(sb); } } - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); } /// @@ -151,23 +152,24 @@ where T : DrawningLocomotive // /// true - загрузка прошла успешно, false - ошибка при загрузке данных public void LoadData(string filename) { - if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + throw new FileNotFoundException(filename); } + using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); - if (str == null || str.Length == 0) + if (string.IsNullOrEmpty(str)) { - throw new Exception("В файле нет данных"); - + throw new EmptyFileExeption(filename); } + if (!str.StartsWith(_collectionKey)) { - throw new Exception("В файле неверные данные"); + throw new FileFormatException(filename); } + _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) @@ -177,34 +179,33 @@ where T : DrawningLocomotive { continue; } - - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new Exception("Не удалось создать коллекцию"); - } + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new CollectionNoInfoException("Не удалось определить информацию коллекции:" + record[0]); + + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new CollectionNoTypeException("Не удалось определить тип коллекции:" + record[1]); collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningLocomotive() is T locomotive) + if (elem?.CreateDrawningLocomotive() is T macine) { try { - if (collection.Insert(locomotive) == -1) - { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(macine); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - throw new Exception("Коллекция переполнена", ex); - + throw new FileFormatException(filename, ex); } } } - _storages.Add(record[0], collection); + + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectElectricLocomotive/Exceptions/CollectionExistsException.cs b/ProjectElectricLocomotive/Exceptions/CollectionExistsException.cs new file mode 100644 index 0000000..e361e03 --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/CollectionExistsException.cs @@ -0,0 +1,21 @@ +using ProjectElectricLocomotive.CollectionGenericObjects; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions +{ + [Serializable] + public class CollectionExistsException : Exception + { + public CollectionExistsException() : base() { } + public CollectionExistsException(CollectionInfo collectionInfo) : base("Коллекция " + collectionInfo + " уже создана") { } + public CollectionExistsException(string name, Exception exception) : base("Коллекция " + name + " уже создана", exception) + { } + protected CollectionExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/ProjectElectricLocomotive/Exceptions/CollectionNoInfoException.cs b/ProjectElectricLocomotive/Exceptions/CollectionNoInfoException.cs new file mode 100644 index 0000000..4880ce2 --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/CollectionNoInfoException.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 ProjectElectricLocomotive.Exceptions +{ + public class CollectionNoInfoException : Exception + { + public CollectionNoInfoException() : base() { } + public CollectionNoInfoException(string message) : base(message) { } + public CollectionNoInfoException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionNoInfoException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } + } +} \ No newline at end of file diff --git a/ProjectElectricLocomotive/Exceptions/CollectionNoTypeException.cs b/ProjectElectricLocomotive/Exceptions/CollectionNoTypeException.cs new file mode 100644 index 0000000..783122f --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/CollectionNoTypeException.cs @@ -0,0 +1,22 @@ +using ProjectElectricLocomotive.CollectionGenericObjects; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions +{ + [Serializable] + + public class CollectionNoTypeException : Exception + { + public CollectionNoTypeException() : base() { } + public CollectionNoTypeException(string message) : base(message) { } + public CollectionNoTypeException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionNoTypeException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ProjectElectricLocomotive/Exceptions/EmptyFileExeption.cs b/ProjectElectricLocomotive/Exceptions/EmptyFileExeption.cs new file mode 100644 index 0000000..1e414b8 --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/EmptyFileExeption.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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/ProjectElectricLocomotive/FormLocomotiveCollection.cs b/ProjectElectricLocomotive/FormLocomotiveCollection.cs index 6c1b65d..f4e54a7 100644 --- a/ProjectElectricLocomotive/FormLocomotiveCollection.cs +++ b/ProjectElectricLocomotive/FormLocomotiveCollection.cs @@ -195,14 +195,13 @@ public partial class FormLocomotiveCollection : Form /// private void RerfreshListBoxItems() { - 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); } } } @@ -219,18 +218,21 @@ public partial class FormLocomotiveCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } + ICollectionGenericObjects? collection = - _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + _storageCollection[ + CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? + new CollectionInfo("", CollectionType.None, "")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); return; } + switch (comboBoxSelectorCompany.Text) { - case "Депо": - _company = new LocomotiveDepo(pictureBox.Width, - pictureBox.Height, collection); + case "Хранилище": + _company = new LocomotiveDepo(pictureBox.Width, pictureBox.Height, collection); break; } panelCompanyTools.Enabled = true; @@ -246,25 +248,23 @@ public partial class FormLocomotiveCollection : Form /// private void buttonCollectionDel_Click(object sender, EventArgs e) { + // TODO прописать логику удаления элемента из коллекции + // нужно убедиться, что есть выбранная коллекция + // спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись + // удалить и обновить ListBox if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - try + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { - 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(); } /// @@ -276,27 +276,29 @@ public partial class FormLocomotiveCollection : Form { 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, "ХЗ")); + _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); } }