From 89b32379e656953e1f9a58415e1f5a70e0df011c Mon Sep 17 00:00:00 2001 From: ShuryginDima Date: Mon, 6 May 2024 21:45:47 +0300 Subject: [PATCH] =?UTF-8?q?6=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 13 +- .../ListGenericObjects.cs | 24 +++- .../MassiveGenericObjects.cs | 17 ++- .../StorageCollection.cs | 129 +++++++++++++++++- .../Drawnings/DrawningPlane.cs | 5 + .../Drawnings/DrawningSeaplane.cs | 4 + .../Drawnings/ExtentionDrawningPlane.cs | 52 +++++++ .../ProjectSeaplane/Entities/EntityPlane.cs | 25 +++- .../Entities/EntitySeaplane.cs | 23 ++++ .../FormPlaneCollection.Designer.cs | 70 +++++++++- .../ProjectSeaplane/FormPlaneCollection.cs | 41 ++++++ .../ProjectSeaplane/FormPlaneCollection.resx | 9 ++ 13 files changed, 401 insertions(+), 13 deletions(-) create mode 100644 ProjectSeaplane/ProjectSeaplane/Drawnings/ExtentionDrawningPlane.cs diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs index 77409f4..f4f0aac 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectSeaplane/ProjectSeaplane/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/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ICollectionGenericObjects.cs index 63be330..7daf4cc 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/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/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs index 3e94174..57b551a 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs @@ -17,7 +17,21 @@ public class ListGenericObjects : ICollectionGenericObjects /// private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount { + get + { + return _collection.Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -57,4 +71,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs index 840ea93..ccedd1b 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs @@ -16,8 +16,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } + set { if (value > 0) @@ -34,6 +39,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -105,4 +112,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects } return null; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs index 5950c32..f8fc453 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,14 @@ -namespace ProjectSeaplane.CollectionGenericObjects; +using ProjectSeaplane.Drawnings; +using System.Text; + +namespace ProjectSeaplane.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningPlane { /// /// Словарь (хранилище) с коллекциями @@ -17,6 +20,21 @@ public class StorageCollection /// public List Keys => _storage.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -82,4 +100,111 @@ public class StorageCollection } } } + + /// + /// Сохранение информации по самолётам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + + if (_storage.Count == 0) + { + return false; + } + + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.WriteLine(_collectionKey); + foreach (KeyValuePair> value in _storage) + { + writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}"); + writer.Write(_separatorItems); + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (!string.IsNullOrEmpty(data)) + { + writer.Write(data + _separatorItems); + } + } + writer.WriteLine(); + } + } + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) return false; + using (StreamReader reader = new StreamReader(filename)) + { + string line = reader.ReadLine(); + if (line == null || !line.Equals(_collectionKey)) + { + return false; + } + + _storage.Clear(); + while (line != null) + { + string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + line = reader.ReadLine(); + 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?.CreateDrawningPlane() is T plane) + { + if (collection.Insert(plane) == -1) + { + return false; + } + } + } + _storage.Add(record[0], collection); + line = reader.ReadLine(); + } + } + 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/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlane.cs b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlane.cs index adb5ead..00751a4 100644 --- a/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlane.cs +++ b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlane.cs @@ -92,6 +92,11 @@ public class DrawningPlane _drawningPlaneHeight = drawningPlaneHeight; } + public DrawningPlane(EntityPlane plane) + { + EntityPlane = plane; + } + /// /// Установка границ поля /// diff --git a/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningSeaplane.cs b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningSeaplane.cs index 68f7500..c18857f 100644 --- a/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningSeaplane.cs +++ b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningSeaplane.cs @@ -20,6 +20,10 @@ public class DrawningSeaplane : DrawningPlane EntityPlane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, floats, boat); } + public DrawningSeaplane(EntityPlane plane) : base(plane) + { + } + public override void DrawTransport(Graphics g) { if (EntityPlane == null || EntityPlane is not EntitySeaplane seaplane || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectSeaplane/ProjectSeaplane/Drawnings/ExtentionDrawningPlane.cs b/ProjectSeaplane/ProjectSeaplane/Drawnings/ExtentionDrawningPlane.cs new file mode 100644 index 0000000..cff230a --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Drawnings/ExtentionDrawningPlane.cs @@ -0,0 +1,52 @@ +using ProjectSeaplane.Entities; +namespace ProjectSeaplane.Drawnings; + +/// +/// Расширение для класса EntityPlane +/// +public static class ExtentionDrawningPlane +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningPlane? CreateDrawningPlane(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityPlane? plane = EntitySeaplane.CreateEntitySeaplane(strs); + if (plane != null) + { + return new DrawningSeaplane(plane); + } + + plane = EntityPlane.CreateEntityPlane(strs); + if (plane != null) + { + return new DrawningPlane(plane); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningPlane drawningPlane) + { + string[]? array = drawningPlane?.EntityPlane?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Entities/EntityPlane.cs b/ProjectSeaplane/ProjectSeaplane/Entities/EntityPlane.cs index 99484a4..91331d4 100644 --- a/ProjectSeaplane/ProjectSeaplane/Entities/EntityPlane.cs +++ b/ProjectSeaplane/ProjectSeaplane/Entities/EntityPlane.cs @@ -42,4 +42,27 @@ public class EntityPlane { BodyColor = bobycolor; } -} + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityPlane), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityPlane? CreateEntityPlane(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityPlane)) + { + return null; + } + return new EntityPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Entities/EntitySeaplane.cs b/ProjectSeaplane/ProjectSeaplane/Entities/EntitySeaplane.cs index 7e367ba..1a31b04 100644 --- a/ProjectSeaplane/ProjectSeaplane/Entities/EntitySeaplane.cs +++ b/ProjectSeaplane/ProjectSeaplane/Entities/EntitySeaplane.cs @@ -38,4 +38,27 @@ public class EntitySeaplane : EntityPlane { AdditionalColor = color; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntitySeaplane), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Floats.ToString(), Boat.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntitySeaplane? CreateEntitySeaplane(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntitySeaplane)) + { + return null; + } + return new EntitySeaplane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } } diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs index d9fe289..5eee03e 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs @@ -46,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + loadFileDialog = new OpenFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -59,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(793, 0); + groupBoxTools.Location = new Point(793, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(144, 571); + groupBoxTools.Size = new Size(144, 575); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -75,7 +82,7 @@ panelCompanyTools.Controls.Add(buttonRemovePlane); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 320); + panelCompanyTools.Location = new Point(3, 324); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(138, 248); panelCompanyTools.TabIndex = 10; @@ -238,19 +245,61 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(793, 571); + pictureBox.Size = new Size(793, 575); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(937, 24); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(48, 20); + файлToolStripMenuItem.Text = "Файл"; + // + // SaveToolStripMenuItem + // + saveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(181, 22); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // LoadToolStripMenuItem + // + loadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(181, 22); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + loadFileDialog.Filter = "txt file | *.txt"; + // // FormPlaneCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(937, 571); + ClientSize = new Size(937, 599); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormPlaneCollection"; Text = "Коллекция самолётов"; groupBoxTools.ResumeLayout(false); @@ -259,7 +308,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -282,5 +334,11 @@ private Button buttonCollectionDel; private Button buttonCreateCompany; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog loadFileDialog; } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs index 01eee37..9c45682 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs @@ -242,4 +242,45 @@ public partial class FormPlaneCollection : Form panelCompanyTools.Enabled = true; RefreshListBoxItems(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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 (loadFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(loadFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RefreshListBoxItems(); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx index af32865..8b1dfa1 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 261, 17 + \ No newline at end of file -- 2.25.1