From e31a0b24a5e1708b3dfca64f618e37bd35a0cdb7 Mon Sep 17 00:00:00 2001 From: MorozovDanil Date: Mon, 29 Apr 2024 01:03:50 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B3=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=20=D0=BA?= =?UTF-8?q?=20=D1=81=D0=B4=D0=B0=D1=87=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 13 +- .../ListGenericObjects.cs | 22 ++- .../MassiveGenericObjects.cs | 16 ++- .../StorageCollection.cs | 136 +++++++++++++++++- .../Drawnings/DrawningContainerShip.cs | 10 ++ .../Drawnings/DrawningShip.cs | 11 +- .../Drawnings/ExtentionDrawningShip.cs | 51 +++++++ .../Entities/EntityContainerShip.cs | 24 ++++ .../Entities/EntityShip.cs | 24 ++++ .../FormShipCollection.Designer.cs | 69 ++++++++- .../FormShipCollection.cs | 42 ++++++ .../FormShipCollection.resx | 9 ++ 13 files changed, 417 insertions(+), 12 deletions(-) create mode 100644 ProjectContainerShip/ProjectContainerShip/Drawnings/ExtentionDrawningShip.cs diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs index 4a20e8c..8e8a1da 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs @@ -47,7 +47,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs index 2dc17b3..0d261d8 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -12,7 +12,7 @@ public interface ICollectionGenericObjects /// /// Установка макс кол-ва элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -42,4 +42,15 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs index ea12df5..140aea1 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs @@ -25,7 +25,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; /// /// Конструктор @@ -75,4 +87,12 @@ public class ListGenericObjects : ICollectionGenericObjects return obj; } + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } + } diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs index c94b54c..b188f28 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/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; + /// /// Конструктор /// @@ -97,4 +103,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/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs index 0703004..e66e577 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using ProjectContainerShip.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -11,7 +12,7 @@ namespace ProjectContainerShip.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningShip { /// /// Словарь (хранилище) с коллекциями @@ -24,6 +25,22 @@ public class StorageCollection /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + + /// /// Конструктор /// @@ -86,4 +103,119 @@ public class StorageCollection return null; } } + + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filename)) + { + File.Delete(filename); + } + + StringBuilder sb = new(); + + using (StreamWriter sw = new StreamWriter(filename)) + { + sw.WriteLine(_collectionKey.ToString()); + foreach (KeyValuePair> kvpair in _storages) + { + // не сохраняем пустые коллекции + if (kvpair.Value.Count == 0) + continue; + sb.Append(kvpair.Key); + sb.Append(_separatorForKeyValue); + sb.Append(kvpair.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(kvpair.Value.MaxCount); + sb.Append(_separatorForKeyValue); + foreach (T? item in kvpair.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + continue; + sb.Append(data); + sb.Append(_separatorItems); + } + sw.WriteLine(sb.ToString()); + sb.Clear(); + } + } + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (StreamReader sr = new StreamReader(filename)) + { + string? str; + str = sr.ReadLine(); + if (str != _collectionKey.ToString()) + return false; + _storages.Clear(); + while ((str = sr.ReadLine()) != null) + { + string[] record = str.Split(_separatorForKeyValue); + 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?.CreateDrawningShip() is T boat) + { + if (collection.Insert(boat) == -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, + }; + } + } diff --git a/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningContainerShip.cs b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningContainerShip.cs index 4c9e6b5..17b8e0b 100644 --- a/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningContainerShip.cs +++ b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningContainerShip.cs @@ -22,6 +22,16 @@ public class DrawningContainerShip : DrawningShip EntityShip = new EntityContainerShip(speed, weight, bodyColor, additionalColor, crane, container); } /// true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах + + /// + /// Конструктор через сущность + /// + /// Объект класса-сущность + public DrawningContainerShip(EntityShip entityShip) : base() + { + EntityShip = entityShip; + } + public override void DrawTransport(Graphics g) { if (EntityShip == null || EntityShip is not EntityContainerShip containerShip || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShip.cs b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShip.cs index bd9d263..bc3d77b 100644 --- a/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShip.cs +++ b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShip.cs @@ -66,7 +66,7 @@ public class DrawningShip /// /// Пустой конструктор /// - private DrawningShip() + protected DrawningShip() { _pictureWidth = null; _pictureHeight = null; @@ -96,6 +96,15 @@ public class DrawningShip _pictureHeight = drawningShipHeight; } + /// + /// Конструктор через сущность + /// + /// Объект класса-сущность + public DrawningShip(EntityShip entityShip) : base() + { + EntityShip = entityShip; + } + /// /// Установка границ поля /// diff --git a/ProjectContainerShip/ProjectContainerShip/Drawnings/ExtentionDrawningShip.cs b/ProjectContainerShip/ProjectContainerShip/Drawnings/ExtentionDrawningShip.cs new file mode 100644 index 0000000..f6d89fb --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Drawnings/ExtentionDrawningShip.cs @@ -0,0 +1,51 @@ +using ProjectContainerShip.Entities; + +namespace ProjectContainerShip.Drawnings; + +public static class ExtentionDrawningShip +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningShip? CreateDrawningShip(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityShip? ship = EntityContainerShip.CreateEntityContainerShip(strs); + if (ship != null) + { + return new DrawningContainerShip(ship); + } + + ship = EntityShip.CreateEntityShip(strs); + if (ship != null) + { + return new DrawningShip(ship); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningShip drawningShip) + { + string[]? array = drawningShip?.EntityShip?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/Entities/EntityContainerShip.cs b/ProjectContainerShip/ProjectContainerShip/Entities/EntityContainerShip.cs index 3fe15a1..ff703b1 100644 --- a/ProjectContainerShip/ProjectContainerShip/Entities/EntityContainerShip.cs +++ b/ProjectContainerShip/ProjectContainerShip/Entities/EntityContainerShip.cs @@ -37,4 +37,28 @@ public class EntityContainerShip : EntityShip Crane = crane; Container = container; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityContainerShip), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Crane.ToString(), Container.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityContainerShip? CreateEntityContainerShip(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityContainerShip)) + { + return null; + } + return new EntityContainerShip(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), + Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } } \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/Entities/EntityShip.cs b/ProjectContainerShip/ProjectContainerShip/Entities/EntityShip.cs index 90a3fd0..842cdc3 100644 --- a/ProjectContainerShip/ProjectContainerShip/Entities/EntityShip.cs +++ b/ProjectContainerShip/ProjectContainerShip/Entities/EntityShip.cs @@ -41,4 +41,28 @@ public class EntityShip Weight = weight; BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityShip), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityShip? CreateEntityShip(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityShip)) + { + return null; + } + + return new EntityShip(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs index fe7acee..7271c74 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.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(); + openFileDialog = 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(930, 0); + groupBoxTools.Location = new Point(935, 25); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(206, 638); + groupBoxTools.Size = new Size(206, 644); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -242,19 +249,62 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 25); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(930, 638); + pictureBox.Size = new Size(935, 644); 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(1141, 25); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(50, 21); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(192, 22); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(192, 22); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file | *.txt"; + // // FormShipCollection // AutoScaleDimensions = new SizeF(7F, 17F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1136, 638); + ClientSize = new Size(1141, 669); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormShipCollection"; Text = "Коллекция кораблей"; groupBoxTools.ResumeLayout(false); @@ -263,7 +313,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -286,5 +339,11 @@ private ListBox listBoxCollection; private Button buttonCollectionAdd; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; } } \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs index e4dbdc4..8126fc4 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs @@ -1,5 +1,6 @@ using ProjectContainerShip.CollectionGenericObjects; using ProjectContainerShip.Drawnings; +using System.Windows.Forms; namespace ProjectContainerShip @@ -245,5 +246,46 @@ namespace ProjectContainerShip 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 (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + RefreshListBoxItems(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.resx b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.resx index 8c82215..175cc4f 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.resx +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.resx @@ -117,6 +117,15 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 131, 17 + + + 276, 17 + 79