From 7a60c03c4a3b9321c43955093645a627e73c29b6 Mon Sep 17 00:00:00 2001 From: Anna Date: Fri, 15 Dec 2023 23:53:20 +0400 Subject: [PATCH] laba 6 --- .../ExtentionDrawningAirplane.cs | 61 ++++++++++ .../FormAirplaneCollection.Designer.cs | 71 +++++++++++- Airbus_Base/FormAirplaneCollection.cs | 44 ++++++++ .../Generics/TheAirplaneGenericStorage.cs | 104 ++++++++++++++++++ .../Generics/TheAirplanesGenericCollection.cs | 4 + 5 files changed, 281 insertions(+), 3 deletions(-) create mode 100644 Airbus_Base/DrawningObjects/ExtentionDrawningAirplane.cs diff --git a/Airbus_Base/DrawningObjects/ExtentionDrawningAirplane.cs b/Airbus_Base/DrawningObjects/ExtentionDrawningAirplane.cs new file mode 100644 index 0000000..006e9ee --- /dev/null +++ b/Airbus_Base/DrawningObjects/ExtentionDrawningAirplane.cs @@ -0,0 +1,61 @@ +using Airbus_Base.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Airbus_Base.DrawningObjects +{ + /// + /// Расширение для класса EntityAirplane + /// + public static class ExtentionDrawningAirplane + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель даннных + /// Ширина + /// Высота + /// Объект + public static DrawningAirplane? CreateDrawningAirplane(this string info, char separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3) + { + return new DrawningAirplane(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height); + } + if (strs.Length == 6) + { + return new DrawningAirbus(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), + Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), width, height); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Разделитель даннных + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningAirplane drawningairplane, char separatorForObject) + { + var airplane = drawningairplane.EntityAirplane; + if (airplane == null) + { + return string.Empty; + } + var str = $"{airplane.Speed}{separatorForObject}{airplane.Weight}{separatorForObject}{airplane.BodyColor.Name}"; + if (airplane is not EntityAirbus airBus) + { + return str; + } + return + $"{str}{separatorForObject}{airBus.AdditionalColor.Name}{separatorForObject}{airBus.AdditionalEngine}" + + $"{separatorForObject}{airBus.AdditionalPassengerCompartment}"; + } + } +} diff --git a/Airbus_Base/FormAirplaneCollection.Designer.cs b/Airbus_Base/FormAirplaneCollection.Designer.cs index 95064be..16f7632 100644 --- a/Airbus_Base/FormAirplaneCollection.Designer.cs +++ b/Airbus_Base/FormAirplaneCollection.Designer.cs @@ -1,4 +1,6 @@ -namespace Airbus_Base +using System.Windows.Forms; + +namespace Airbus_Base { partial class FormAirplaneCollection { @@ -41,9 +43,16 @@ this.maskedTextBoxNumber = new System.Windows.Forms.TextBox(); this.LabelTools = new System.Windows.Forms.Label(); this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); + this.menuStrip = new MenuStrip(); + this.FileToolStripMenuItem = new ToolStripMenuItem(); + this.SaveToolStripMenuItem = new ToolStripMenuItem(); + this.LoadToolStripMenuItem = new ToolStripMenuItem(); + this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); + this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.toolsPanel.SuspendLayout(); this.panelSets.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); + this.menuStrip.SuspendLayout(); this.SuspendLayout(); // // toolsPanel @@ -165,12 +174,52 @@ // // pictureBoxCollection // - this.pictureBoxCollection.Location = new System.Drawing.Point(1, -2); + this.pictureBoxCollection.Location = new System.Drawing.Point(1, 31); this.pictureBoxCollection.Name = "pictureBoxCollection"; - this.pictureBoxCollection.Size = new System.Drawing.Size(676, 451); + this.pictureBoxCollection.Size = new System.Drawing.Size(676, 471); this.pictureBoxCollection.TabIndex = 0; this.pictureBoxCollection.TabStop = false; // + // menuStrip1 + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(882, 28); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // FileToolStripMenuItem + // + FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem }); + FileToolStripMenuItem.Name = "FileToolStripMenuItem"; + FileToolStripMenuItem.Size = new Size(59, 24); + FileToolStripMenuItem.Text = "Файл"; + // + // SaveToolStripMenuItem + // + SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + SaveToolStripMenuItem.Size = new Size(224, 26); + SaveToolStripMenuItem.Text = "Сохранение"; + SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // LoadToolStripMenuItem + // + LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + LoadToolStripMenuItem.Size = new Size(224, 26); + LoadToolStripMenuItem.Text = "Загрузка"; + LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog"; + openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // // FormAirplaneCollection // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); @@ -178,6 +227,8 @@ this.ClientSize = new System.Drawing.Size(900, 450); this.Controls.Add(this.pictureBoxCollection); this.Controls.Add(this.toolsPanel); + this.Controls.Add(menuStrip); + this.MainMenuStrip = menuStrip; this.Name = "FormAirplaneCollection"; this.Text = "FormAirplaneCollection"; this.toolsPanel.ResumeLayout(false); @@ -185,10 +236,18 @@ this.panelSets.ResumeLayout(false); this.panelSets.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit(); + this.menuStrip.ResumeLayout(false); + this.menuStrip.PerformLayout(); this.ResumeLayout(false); + PerformLayout(); } + private void LoadToolStripMenuItem_Click1(object sender, EventArgs e) + { + throw new NotImplementedException(); + } + #endregion private Panel toolsPanel; @@ -204,5 +263,11 @@ private Button ButtonRefreshCollection; private ListBox listBoxObjects; private TextBox textBoxStorageName; + private MenuStrip menuStrip; + private ToolStripMenuItem FileToolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem LoadToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/Airbus_Base/FormAirplaneCollection.cs b/Airbus_Base/FormAirplaneCollection.cs index 5622cbf..24db4a0 100644 --- a/Airbus_Base/FormAirplaneCollection.cs +++ b/Airbus_Base/FormAirplaneCollection.cs @@ -193,5 +193,49 @@ namespace Airbus_Base } pictureBoxCollection.Image = obj.ShowTheAirplanes(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.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 (_storage.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + foreach (var collection in _storage.Keys) + { + listBoxObjects.Items.Add(collection); + } + } + else + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/Airbus_Base/Generics/TheAirplaneGenericStorage.cs b/Airbus_Base/Generics/TheAirplaneGenericStorage.cs index edabd4a..4e69fb7 100644 --- a/Airbus_Base/Generics/TheAirplaneGenericStorage.cs +++ b/Airbus_Base/Generics/TheAirplaneGenericStorage.cs @@ -33,6 +33,19 @@ namespace Airbus_Base.Generics /// private readonly int _pictureHeight; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// /// Конструктор /// @@ -44,6 +57,97 @@ namespace Airbus_Base.Generics _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } + /// + /// Сохранение информации по самолётам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in _airplaneStorages) + { + StringBuilder records = new(); + foreach (DrawningAirplane? elem in record.Value.GetTheAirplanes) + { + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } + + if (data.Length == 0) + { + return false; + } + string toWrite = $"AirplaneStorage{Environment.NewLine}{data}"; + var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + + using (StreamWriter sw = new(filename)) + { + foreach (var str in strs) + { + sw.WriteLine(str); + } + } + return true; + } + + /// + /// Загрузка информации по автобусам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + using (StreamReader sr = new(filename)) + { + string str = sr.ReadLine(); + var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + return false; + } + if (!strs[0].StartsWith("AirplaneStorage")) + { + return false; + } + _airplaneStorages.Clear(); + do + { + string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + str = sr.ReadLine(); + continue; + } + TheAirplanesGenericCollection collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningAirplane? airplane = elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight); + if (airplane != null) + { + if (!(collection + airplane)) + { + return false; + } + } + } + _airplaneStorages.Add(record[0], collection); + + str = sr.ReadLine(); + } while (str != null); + } + return true; + } /// /// Добавление набора diff --git a/Airbus_Base/Generics/TheAirplanesGenericCollection.cs b/Airbus_Base/Generics/TheAirplanesGenericCollection.cs index b5a01b0..2638cfd 100644 --- a/Airbus_Base/Generics/TheAirplanesGenericCollection.cs +++ b/Airbus_Base/Generics/TheAirplanesGenericCollection.cs @@ -17,6 +17,10 @@ namespace Airbus_Base.Generics where T : DrawningAirplane where U : IMoveableObject { + /// + /// Получение объектов коллекции + /// + public IEnumerable GetTheAirplanes => _collection.GetTheAirplanes(); /// /// Ширина окна прорисовки ///