diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs index 6543640..2a01fdc 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs @@ -47,14 +47,14 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// /// Перегрузка оператора сложения для класса /// - /// Компания - /// Добавляемый объект + /// + /// /// public static int operator +(AbstractCompany company, DrawningPlane plane) { diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ICollectionGenericObjects.cs index 0df392d..67c7e92 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -11,7 +11,7 @@ public interface ICollectionGenericObjects /// /// Установка макс кол-ва элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -41,4 +41,16 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// Объект T? Get(int position); + + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs index e96241e..eb1d335 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectAirbus.CollectionGenericObjects; + +namespace ProjectAirbus.CollectionGenericObjects; /// /// Параметризованный набор объектов /// @@ -18,7 +19,22 @@ public class ListGenericObjects : ICollectionGenericObjects public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get + { + return _maxCount; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -76,4 +92,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]; + } + } } diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs index af5b58d..ef18b96 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectAirbus.CollectionGenericObjects; + +namespace ProjectAirbus.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -14,8 +15,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 +37,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -105,4 +112,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/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs index d989a05..94b9b8e 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,14 @@ -namespace ProjectAirbus.CollectionGenericObjects; +using ProjectAirbus.Drawnings; +using System.Text; + +namespace ProjectAirbus.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningPlane { /// /// Словарь (хранилище) с коллекциями @@ -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 = ";"; + /// /// Конструктор /// @@ -73,4 +91,120 @@ public class StorageCollection return _storages[name]; } } + + + /// + /// Сохранение информации хранилища в файл + /// + /// Путь и имя файла + /// 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?.CreateDrawningPlane() is T plane) + { + if (collection.Insert(plane) == -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, + }; + } } \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/Drawnings/DrawningAirbus.cs b/ProjectAirbus/ProjectAirbus/Drawnings/DrawningAirbus.cs index 8da0c8f..9814033 100644 --- a/ProjectAirbus/ProjectAirbus/Drawnings/DrawningAirbus.cs +++ b/ProjectAirbus/ProjectAirbus/Drawnings/DrawningAirbus.cs @@ -24,6 +24,11 @@ public class DrawningAirbus : DrawningPlane EntityPlane = new EntityAirbus(speed, weight, bodyColor, additionalColor, motor, otsek); } + public DrawningAirbus(EntityPlane entityPlane) : base() + { + EntityPlane = entityPlane; + } + public override void DrawTransport(Graphics g) { if (EntityPlane == null || EntityPlane is not EntityAirbus airbus || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectAirbus/ProjectAirbus/Drawnings/DrawningPlane.cs b/ProjectAirbus/ProjectAirbus/Drawnings/DrawningPlane.cs index cb8fbb7..9e6bcac 100644 --- a/ProjectAirbus/ProjectAirbus/Drawnings/DrawningPlane.cs +++ b/ProjectAirbus/ProjectAirbus/Drawnings/DrawningPlane.cs @@ -63,11 +63,11 @@ public class DrawningPlane /// высота объекта /// public int GetHeight => _drawningPlaneHeight; - + /// /// Пустой конструктор /// - private DrawningPlane() + protected DrawningPlane() { _pictureWidth = null; _pictureHeight = null; @@ -86,6 +86,11 @@ public class DrawningPlane EntityPlane = new EntityPlane(speed, weight, bodyColor); } + public DrawningPlane(EntityPlane entityPlane) : base() + { + EntityPlane = entityPlane; + } + /// /// Конструктор для наследников /// diff --git a/ProjectAirbus/ProjectAirbus/Drawnings/ExtentionDrawningPlane.cs b/ProjectAirbus/ProjectAirbus/Drawnings/ExtentionDrawningPlane.cs new file mode 100644 index 0000000..60ed6d3 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Drawnings/ExtentionDrawningPlane.cs @@ -0,0 +1,47 @@ +using ProjectAirbus.Entities; + +namespace ProjectAirbus.Drawnings; + +public static class ExtentionDrawningPlane +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningPlane? CreateDrawningPlane(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityPlane? plane = EntityAirbus.CreateEntityAirbus(strs); + if (plane != null) + { + return new DrawningAirbus(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); + } +} diff --git a/ProjectAirbus/ProjectAirbus/Entities/EntityAirbus.cs b/ProjectAirbus/ProjectAirbus/Entities/EntityAirbus.cs index 2dd3a42..11aee65 100644 --- a/ProjectAirbus/ProjectAirbus/Entities/EntityAirbus.cs +++ b/ProjectAirbus/ProjectAirbus/Entities/EntityAirbus.cs @@ -49,5 +49,32 @@ Motor = motor; Otsek = otsek; } + + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityAirbus), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Motor.ToString(), Otsek.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/ProjectAirbus/ProjectAirbus/Entities/EntityPlane.cs b/ProjectAirbus/ProjectAirbus/Entities/EntityPlane.cs index 37d8c64..fc8024b 100644 --- a/ProjectAirbus/ProjectAirbus/Entities/EntityPlane.cs +++ b/ProjectAirbus/ProjectAirbus/Entities/EntityPlane.cs @@ -46,5 +46,29 @@ public class EntityPlane Weight = weight; BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + 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])); + } } diff --git a/ProjectAirbus/ProjectAirbus/FormPlaneCollection.Designer.cs b/ProjectAirbus/ProjectAirbus/FormPlaneCollection.Designer.cs index 69d6654..a7fedba 100644 --- a/ProjectAirbus/ProjectAirbus/FormPlaneCollection.Designer.cs +++ b/ProjectAirbus/ProjectAirbus/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(); + openFileDialog = new OpenFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -59,11 +66,11 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(1075, 0); + groupBoxTools.Location = new Point(1075, 28); groupBoxTools.Margin = new Padding(3, 4, 3, 4); groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Padding = new Padding(3, 4, 3, 4); - groupBoxTools.Size = new Size(226, 891); + groupBoxTools.Size = new Size(226, 863); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -252,13 +259,55 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 28); pictureBox.Margin = new Padding(3, 4, 3, 4); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1075, 891); + pictureBox.Size = new Size(1075, 863); 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(1301, 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.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file | *.txt"; + // // FormPlaneCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -266,6 +315,8 @@ ClientSize = new Size(1301, 891); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Margin = new Padding(3, 4, 3, 4); Name = "FormPlaneCollection"; Text = "Коллекция самолётов"; @@ -275,7 +326,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -298,5 +352,11 @@ private RadioButton radioButtonMassive; private Button buttonCreateCompany; 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/ProjectAirbus/ProjectAirbus/FormPlaneCollection.cs b/ProjectAirbus/ProjectAirbus/FormPlaneCollection.cs index f1aa10b..d639f95 100644 --- a/ProjectAirbus/ProjectAirbus/FormPlaneCollection.cs +++ b/ProjectAirbus/ProjectAirbus/FormPlaneCollection.cs @@ -236,4 +236,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 (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + RefreshListBoxItems(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/FormPlaneCollection.resx b/ProjectAirbus/ProjectAirbus/FormPlaneCollection.resx index af32865..ee1748a 100644 --- a/ProjectAirbus/ProjectAirbus/FormPlaneCollection.resx +++ b/ProjectAirbus/ProjectAirbus/FormPlaneCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 145, 17 + + + 310, 17 + \ No newline at end of file