diff --git a/AirFighter/AirFighter/CollectionGenericObjects/AbstractCompany.cs b/AirFighter/AirFighter/CollectionGenericObjects/AbstractCompany.cs index 268c3d5..1e6c381 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/AbstractCompany.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/AbstractCompany.cs @@ -48,7 +48,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/AirFighter/AirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs b/AirFighter/AirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs index 37a865f..75d1b0e 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -15,7 +15,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -45,4 +45,15 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } \ No newline at end of file diff --git a/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs b/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs index daf6f3c..c582091 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -19,7 +19,19 @@ public class ListGenericObjects : ICollectionGenericObjects public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get => _maxCount; + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -57,4 +69,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return pos; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index 45f854a..ccda1cf 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -14,8 +14,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -32,6 +36,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -105,4 +111,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/AirFighter/AirFighter/CollectionGenericObjects/StorageCollection.cs b/AirFighter/AirFighter/CollectionGenericObjects/StorageCollection.cs index c1cc672..d8f62c5 100644 --- a/AirFighter/AirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/AirFighter/AirFighter/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,15 @@ -namespace ProjectAirFighter.CollectionGenericObjects; +using ProjectAirFighter.Drawnings; +using System.Text; + +namespace ProjectAirFighter.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningMilitaryAircraft + { /// /// Словарь (хранилище) с коллекциями @@ -17,12 +21,26 @@ public class StorageCollection /// public List Keys => _storages.Keys.ToList(); + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// public StorageCollection() { - _storages = new Dictionary>(); //вот тут какое-то свойство + _storages = new Dictionary>(); } /// @@ -70,4 +88,147 @@ public class StorageCollection return _storages[name]; } } + + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filename)) + { + File.Delete(filename); + } + + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.Write(_collectionKey); + + foreach (KeyValuePair> value in _storages) + { + StringBuilder sb = new(); + + sb.Append(Environment.NewLine); + + if (value.Value.Count == 0) + { + continue; + } + + 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()) + { + string data = item?.GetDataForSave() ?? string.Empty; + + if (string.IsNullOrEmpty(data)) + { + continue; + } + sb.Append(data); + sb.Append(_separatorItems); + } + writer.Write(sb); + } + + } + + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + + // + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + using (StreamReader fs = File.OpenText(filename)) + { + string str = fs.ReadLine(); + + if (str == null || str.Length == 0) + { + return false; + } + + if (!str.StartsWith(_collectionKey)) + { + return false; + } + + _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) + { + return false; + } + + collection.MaxCount = Convert.ToInt32(record[2]); + + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + + foreach (string elem in set) + { + if (elem?.CreateDrawningMilitaryAircraft() is T militaryAircraft) + { + if (collection.Insert(militaryAircraft) == -1) + { + return false; + } + } + } + _storages.Add(record[0], collection); + } + return true; + } + } + + /// + /// Создание коллекции по типу + /// + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } \ No newline at end of file diff --git a/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs b/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs index 1e6fea7..ae5699a 100644 --- a/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs +++ b/AirFighter/AirFighter/FormMilitaryAircraftCollection.cs @@ -1,5 +1,6 @@ using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings; +using System.Windows.Forms; namespace ProjectAirFighter; @@ -226,4 +227,45 @@ public partial class FormMilitaryAircraftCollection : Form panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + /// + /// Обработка нажатия "Загрузка" + /// + /// + /// + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RerfreshListBoxItems(); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } }