From 0588c9c4aaefa50eaa7aaceebd321a5d0d6c426d Mon Sep 17 00:00:00 2001 From: Evgehil Date: Sat, 13 Apr 2024 15:55:31 +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=206?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 13 +- .../ListGenericObjects.cs | 32 +++- .../MassiveGenericObjects.cs | 18 +- .../StorageCollection.cs | 162 +++++++++++++++++- .../Project_airbus/Drawings/DrawingAirbus.cs | 9 + .../Project_airbus/Drawings/DrawingAirplan.cs | 9 + .../Drawings/ExtentionDrawingAirplan.cs | 52 ++++++ .../Project_airbus/Entities/EntityAirbus.cs | 25 +++ .../Project_airbus/Entities/EntityAirplan.cs | 24 +++ .../FormAirplanCollection.Designer.cs | 67 +++++++- .../Project_airbus/FormAirplanCollection.cs | 44 +++++ .../Project_airbus/FormAirplanCollection.resx | 9 + 13 files changed, 453 insertions(+), 13 deletions(-) create mode 100644 Project_airbus/Project_airbus/Drawings/ExtentionDrawingAirplan.cs diff --git a/Project_airbus/Project_airbus/CollectionGenericObjects/AbstractCompany.cs b/Project_airbus/Project_airbus/CollectionGenericObjects/AbstractCompany.cs index 8c6f12a..5fb0c76 100644 --- a/Project_airbus/Project_airbus/CollectionGenericObjects/AbstractCompany.cs +++ b/Project_airbus/Project_airbus/CollectionGenericObjects/AbstractCompany.cs @@ -44,7 +44,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/Project_airbus/Project_airbus/CollectionGenericObjects/ICollectionGenericObjects.cs b/Project_airbus/Project_airbus/CollectionGenericObjects/ICollectionGenericObjects.cs index fcd5723..144d5a9 100644 --- a/Project_airbus/Project_airbus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Project_airbus/Project_airbus/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/Project_airbus/Project_airbus/CollectionGenericObjects/ListGenericObjects.cs b/Project_airbus/Project_airbus/CollectionGenericObjects/ListGenericObjects.cs index 76a4186..48eec23 100644 --- a/Project_airbus/Project_airbus/CollectionGenericObjects/ListGenericObjects.cs +++ b/Project_airbus/Project_airbus/CollectionGenericObjects/ListGenericObjects.cs @@ -19,12 +19,27 @@ public class ListGenericObjects : ICollectionGenericObjects 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 GetCollectionType => CollectionType.List; /// - /// Конструктор - /// - public ListGenericObjects() + /// Конструктор + /// + public ListGenericObjects() { _collection = new(); } @@ -57,4 +72,13 @@ 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/Project_airbus/Project_airbus/CollectionGenericObjects/MassiveGenericObjects.cs b/Project_airbus/Project_airbus/CollectionGenericObjects/MassiveGenericObjects.cs index 11cc6c9..85fa85c 100644 --- a/Project_airbus/Project_airbus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Project_airbus/Project_airbus/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; + /// /// Конструктор /// @@ -100,4 +106,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return removeObj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } + + } diff --git a/Project_airbus/Project_airbus/CollectionGenericObjects/StorageCollection.cs b/Project_airbus/Project_airbus/CollectionGenericObjects/StorageCollection.cs index fc492e3..807da31 100644 --- a/Project_airbus/Project_airbus/CollectionGenericObjects/StorageCollection.cs +++ b/Project_airbus/Project_airbus/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,14 @@ -namespace Project_airbus.CollectionGenericObjects; +using Project_airbus.Drawings; +using System.Text; + +namespace Project_airbus.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawingAirplan { /// /// Словарь (хранилище) с коллекциями @@ -17,6 +20,21 @@ public class StorageCollection /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -65,4 +83,144 @@ 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(); + + sb.Append(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + 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); + } + } + + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); + 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?.CreateDrawingAirplan() is T airplan) + { + if (collection.Insert(airplan) == -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/Project_airbus/Project_airbus/Drawings/DrawingAirbus.cs b/Project_airbus/Project_airbus/Drawings/DrawingAirbus.cs index 2b08264..8729aaa 100644 --- a/Project_airbus/Project_airbus/Drawings/DrawingAirbus.cs +++ b/Project_airbus/Project_airbus/Drawings/DrawingAirbus.cs @@ -21,6 +21,15 @@ public class DrawingAirbus : DrawingAirplan EntityAirplan = new EntityAirbus(speed, weight, bodyAirbus, additionalColor, bodySection, motor); } + /// + /// Конструктор для Extention + /// + /// + public DrawingAirbus(EntityAirbus airplan) : base(130, 60) + { + EntityAirplan = new EntityAirbus(airplan.Speed, airplan.Weight, airplan.BodyAirbus, airplan.AdditionalColor, airplan.BodySection, airplan.Motor); + } + public override void DrawTransport(Graphics g) { if (EntityAirplan == null || EntityAirplan is not EntityAirbus airbus || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/Project_airbus/Project_airbus/Drawings/DrawingAirplan.cs b/Project_airbus/Project_airbus/Drawings/DrawingAirplan.cs index 8769601..38c9a86 100644 --- a/Project_airbus/Project_airbus/Drawings/DrawingAirplan.cs +++ b/Project_airbus/Project_airbus/Drawings/DrawingAirplan.cs @@ -93,6 +93,15 @@ public class DrawingAirplan _drawingAirplanHeight = drawingAirbusHeight; } + /// + /// Конструктор для Extention + /// + /// + public DrawingAirplan(EntityAirplan airplan) : this() + { + EntityAirplan = new EntityAirplan(airplan.Speed, airplan.Weight, airplan.BodyAirbus); + } + /// /// Установка границ поля /// diff --git a/Project_airbus/Project_airbus/Drawings/ExtentionDrawingAirplan.cs b/Project_airbus/Project_airbus/Drawings/ExtentionDrawingAirplan.cs new file mode 100644 index 0000000..0d21014 --- /dev/null +++ b/Project_airbus/Project_airbus/Drawings/ExtentionDrawingAirplan.cs @@ -0,0 +1,52 @@ +using Project_airbus.Entities; + +namespace Project_airbus.Drawings; + +public static class ExtentionDrawingAirplan +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawingAirplan? CreateDrawingAirplan(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityAirplan? airplan = EntityAirbus.CreateEntityAirbus(strs); + if (airplan != null) + { + return new DrawingAirbus((EntityAirbus)airplan); + } + + airplan = EntityAirplan.CreateEntityAirplan(strs); + if (airplan != null) + { + return new DrawingAirplan(airplan); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawingAirplan drawingAirplan) + { + string[]? array = drawingAirplan?.EntityAirplan?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } + +} diff --git a/Project_airbus/Project_airbus/Entities/EntityAirbus.cs b/Project_airbus/Project_airbus/Entities/EntityAirbus.cs index 27bbaa2..000f21a 100644 --- a/Project_airbus/Project_airbus/Entities/EntityAirbus.cs +++ b/Project_airbus/Project_airbus/Entities/EntityAirbus.cs @@ -44,4 +44,29 @@ public class EntityAirbus : EntityAirplan BodySection = bodySection; Motor = motor; } + + /// + /// Получение строк со значениями свойств продвинутого объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityAirbus), Speed.ToString(), Weight.ToString(), BodyAirbus.Name, AdditionalColor.Name, + BodySection.ToString(), Motor.ToString()}; + } + + /// + /// Создание продвинутого объекта из массива строк + /// + /// + /// + public static EntityAirbus? CreateEntityAirbus(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityAirbus)) + { + return null; + } + return new EntityAirbus(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/Project_airbus/Project_airbus/Entities/EntityAirplan.cs b/Project_airbus/Project_airbus/Entities/EntityAirplan.cs index 1bce00d..60e6e37 100644 --- a/Project_airbus/Project_airbus/Entities/EntityAirplan.cs +++ b/Project_airbus/Project_airbus/Entities/EntityAirplan.cs @@ -46,4 +46,28 @@ public class EntityAirplan Weight = weight; BodyAirbus = bodyAirbus; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityAirplan), Speed.ToString(), Weight.ToString(), BodyAirbus.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityAirplan? CreateEntityAirplan(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityAirplan)) + { + return null; + } + + return new EntityAirplan(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/Project_airbus/Project_airbus/FormAirplanCollection.Designer.cs b/Project_airbus/Project_airbus/FormAirplanCollection.Designer.cs index 3905d00..974a73b 100644 --- a/Project_airbus/Project_airbus/FormAirplanCollection.Designer.cs +++ b/Project_airbus/Project_airbus/FormAirplanCollection.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(925, 0); + groupBoxTools.Location = new Point(925, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(210, 707); + groupBoxTools.Size = new Size(210, 679); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -235,12 +242,53 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(925, 707); + pictureBox.Size = new Size(925, 679); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1135, 28); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(59, 24); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(227, 26); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(227, 26); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormAirplanCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -248,6 +296,8 @@ ClientSize = new Size(1135, 707); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormAirplanCollection"; Text = "Коллекция самолётов"; groupBoxTools.ResumeLayout(false); @@ -256,7 +306,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -279,5 +332,11 @@ private RadioButton radioButtonList; private Button buttonCreateToCompany; 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/Project_airbus/Project_airbus/FormAirplanCollection.cs b/Project_airbus/Project_airbus/FormAirplanCollection.cs index c937a74..db4bf67 100644 --- a/Project_airbus/Project_airbus/FormAirplanCollection.cs +++ b/Project_airbus/Project_airbus/FormAirplanCollection.cs @@ -240,4 +240,48 @@ public partial class FormAirplanCollection : 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); + } + } + } } \ No newline at end of file diff --git a/Project_airbus/Project_airbus/FormAirplanCollection.resx b/Project_airbus/Project_airbus/FormAirplanCollection.resx index af32865..b2e8bcd 100644 --- a/Project_airbus/Project_airbus/FormAirplanCollection.resx +++ b/Project_airbus/Project_airbus/FormAirplanCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 153, 20 + + + 310, 17 + \ No newline at end of file