From b0c28643fd498244a889e2006027c5543be60b08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9E=D0=BB=D0=B5=D0=B3=20=D0=9A=D1=83=D0=B4=D1=80=D0=B8?= =?UTF-8?q?=D0=BD=D1=81=D0=BA=D0=B8=D0=B9?= Date: Mon, 22 Apr 2024 01:47:33 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=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=20=E2=84=966?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 18 ++- .../ListGenericObjects.cs | 27 +++- .../MassiveGenericObjects.cs | 20 ++- .../StorageCollection.cs | 137 +++++++++++++++++- .../Drawings/DrawningContainerShip.cs | 5 + .../Drawings/DrawningShip.cs | 5 + .../Drawings/ExtentionDrawningShip.cs | 45 ++++++ .../Entities/EntityContainerShip.cs | 27 +++- .../Entities/EntityShip.cs | 23 +++ .../FormShipCollection.Designer.cs | 71 ++++++++- .../FormShipCollection.cs | 46 ++++++ .../FormShipCollection.resx | 12 ++ 13 files changed, 418 insertions(+), 20 deletions(-) create mode 100644 ProjectContainerShip/ProjectContainerShip/Drawings/ExtentionDrawningShip.cs diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs index 4a88d53..04860eb 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs @@ -47,7 +47,7 @@ namespace ProjectContainerShip.CollectionGenericObjects; _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs index 86652f3..4b643c8 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -11,7 +11,7 @@ /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -41,12 +41,16 @@ /// Позиция /// Объект T? Get(int position); - } -} -namespace ProjectContainerShip.CollectionGenericObjects -{ - internal interface ICollectionGenericObjects - { + /// + /// Получение типа коллекции + /// + CollectionType GetColectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементный вывод элементов коллекции + IEnumerable GetItems(); } } diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs index 6f92313..073a871 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs @@ -12,7 +12,24 @@ 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 Count; + } + + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetColectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -53,4 +70,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs index 7d42884..8eecafe 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectContainerShip.CollectionGenericObjects + +namespace ProjectContainerShip.CollectionGenericObjects { public class MassiveGenericObjects : ICollectionGenericObjects where T : class @@ -9,8 +10,13 @@ private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } + set { if (value > 0) @@ -27,6 +33,8 @@ } } + public CollectionType GetColectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -104,5 +112,13 @@ _collection[position] = null; return obj; } + + public IEnumerable GetItems() + { + for(int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } } diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs index 1c97ef8..609def5 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,14 @@ -namespace ProjectContainerShip.CollectionGenericObjects; +using ProjectContainerShip.Drawings; +using System.Text; + +namespace ProjectContainerShip.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection -where T : class +where T : DrawningShip { /// /// Словарь (хранилище) с коллекциями @@ -17,6 +20,21 @@ where T : class /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionStorage"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -73,6 +91,121 @@ where T : class return null; } } + + /// + /// Сохранение информации по кораблям в хранилище в файл + /// + /// Путь и имя файла + /// 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.GetColectionType); + 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; + + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) + { + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) bufferTextFromFile += temp.GetString(b); + } + + string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + + if (strs == null || strs.Length == 0) return false; + if (!strs[0].Equals(_collectionKey)) + // Если нет такой записи, то это не те данные + return false; + + _storages.Clear(); + foreach (string data in strs) + { + string[] record = data.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?.CreateDrawningShip() is T ship) + { + if (collection.Insert(ship) == -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/Drawings/DrawningContainerShip.cs b/ProjectContainerShip/ProjectContainerShip/Drawings/DrawningContainerShip.cs index 4dfaa2d..076de8d 100644 --- a/ProjectContainerShip/ProjectContainerShip/Drawings/DrawningContainerShip.cs +++ b/ProjectContainerShip/ProjectContainerShip/Drawings/DrawningContainerShip.cs @@ -21,6 +21,11 @@ public class DrawningContainerShip : DrawningShip EntityShip = new EntityContainerShip(speed, weight, bodycolor, additionalcolor, crane, container); } + public DrawningContainerShip(EntityContainerShip ship) : base(120, 40) + { + EntityShip = new EntityContainerShip(ship.Speed, ship.Weight, ship.BodyColor, ship.AdditionalColor, ship.Crane, ship.Container); + } + public override void DrawTransport(Graphics g) { if (EntityShip == null || EntityShip is not EntityContainerShip containerShip || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectContainerShip/ProjectContainerShip/Drawings/DrawningShip.cs b/ProjectContainerShip/ProjectContainerShip/Drawings/DrawningShip.cs index 8d15fa6..89d760f 100644 --- a/ProjectContainerShip/ProjectContainerShip/Drawings/DrawningShip.cs +++ b/ProjectContainerShip/ProjectContainerShip/Drawings/DrawningShip.cs @@ -97,6 +97,11 @@ public class DrawningShip _drawningContainerShipHeight = drawningContainerShipHeight; } + public DrawningShip(EntityShip ship) : this() + { + EntityShip = new EntityShip(ship.Speed, ship.Weight, ship.BodyColor); + } + /// /// Установка границ поля /// diff --git a/ProjectContainerShip/ProjectContainerShip/Drawings/ExtentionDrawningShip.cs b/ProjectContainerShip/ProjectContainerShip/Drawings/ExtentionDrawningShip.cs new file mode 100644 index 0000000..84eed0f --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Drawings/ExtentionDrawningShip.cs @@ -0,0 +1,45 @@ +using ProjectContainerShip.Entities; + +namespace ProjectContainerShip.Drawings; + +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((EntityContainerShip)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); + } +} diff --git a/ProjectContainerShip/ProjectContainerShip/Entities/EntityContainerShip.cs b/ProjectContainerShip/ProjectContainerShip/Entities/EntityContainerShip.cs index dbbca20..e90022e 100644 --- a/ProjectContainerShip/ProjectContainerShip/Entities/EntityContainerShip.cs +++ b/ProjectContainerShip/ProjectContainerShip/Entities/EntityContainerShip.cs @@ -1,4 +1,6 @@ -namespace ProjectContainerShip.Entities; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + +namespace ProjectContainerShip.Entities; /// /// Класс-сущность Контейнеровоз @@ -38,4 +40,27 @@ public class EntityContainerShip : EntityShip 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])); + } } diff --git a/ProjectContainerShip/ProjectContainerShip/Entities/EntityShip.cs b/ProjectContainerShip/ProjectContainerShip/Entities/EntityShip.cs index 8cbf4de..a9116fe 100644 --- a/ProjectContainerShip/ProjectContainerShip/Entities/EntityShip.cs +++ b/ProjectContainerShip/ProjectContainerShip/Entities/EntityShip.cs @@ -39,4 +39,27 @@ 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])); + } } diff --git a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs index 6cbaf21..f380d34 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 @@ -60,9 +67,9 @@ groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; groupBoxTools.ForeColor = Color.Black; - groupBoxTools.Location = new Point(1601, 0); + groupBoxTools.Location = new Point(1601, 40); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(388, 1112); + groupBoxTools.Size = new Size(388, 1072); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -78,13 +85,13 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 598); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(382, 511); + panelCompanyTools.Size = new Size(382, 471); panelCompanyTools.TabIndex = 10; // // buttonAddShip // buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddShip.Location = new Point(3, 35); + buttonAddShip.Location = new Point(3, 70); buttonAddShip.Name = "buttonAddShip"; buttonAddShip.Size = new Size(370, 77); buttonAddShip.TabIndex = 1; @@ -240,12 +247,53 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 40); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1601, 1112); + pictureBox.Size = new Size(1601, 1072); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(32, 32); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1989, 40); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(90, 36); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(361, 44); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(361, 44); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormShipCollection // AutoScaleDimensions = new SizeF(13F, 32F); @@ -253,6 +301,8 @@ ClientSize = new Size(1989, 1112); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormShipCollection"; Text = "Коллекция кораблей"; groupBoxTools.ResumeLayout(false); @@ -261,7 +311,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -284,5 +337,11 @@ private Button buttonCreateCompany; private RadioButton radioButtonMassive; 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 34a4f11..a11b369 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs @@ -245,4 +245,50 @@ public partial class FormShipCollection : 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); + } + } + } } diff --git a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.resx b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.resx index af32865..9340a84 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.resx +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 204, 17 + + + 447, 17 + + + 25 + \ No newline at end of file