From de6700f50c66ad488d793a67a60be7de8659bd51 Mon Sep 17 00:00:00 2001 From: MatveyPetrov Date: Mon, 12 Feb 2024 18:04:38 +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.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 13 +- .../ListgenericObjects.cs | 104 +++++------ .../MassiveGenericObjects.cs | 17 +- .../StorageCollection.cs | 163 +++++++++++++++++- .../Draw/DrawningAircraft.cs | 19 +- .../Draw/DrawningMilitaryAircraft.cs | 23 ++- .../Draw/ExtensionDrawningAircraft.cs | 59 +++++++ .../Entities/EntityAircraft.cs | 23 +++ .../Entities/EntityMilitaryAircraft.cs | 23 +++ .../FormAircraftCollection.Designer.cs | 68 +++++++- .../FormAircraftCollection.cs | 53 +++++- .../FormAircraftCollection.resx | 12 ++ 13 files changed, 496 insertions(+), 83 deletions(-) create mode 100644 ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/ExtensionDrawningAircraft.cs diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/AbstractCompany.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/AbstractCompany.cs index c30ca93..603cf4f 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/AbstractCompany.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/AbstractCompany.cs @@ -48,7 +48,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/ICollectionGenericObjects.cs index 1091f0a..80cf557 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -23,7 +23,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -53,4 +53,15 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/ListgenericObjects.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/ListgenericObjects.cs index 58c3ef8..ef55222 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/ListgenericObjects.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/ListgenericObjects.cs @@ -11,13 +11,13 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects; /// Параметризованный набор объектов /// /// Параметр : ограничение - ссылочный тип -public class ListgenericObjects +public class ListGenericObjects : ICollectionGenericObjects where T : class { /// - /// Список объектов, которые храниим + /// Список объектов, которые храним /// - private readonly List? _collection; + private readonly List _collection; /// /// Максимально допустимое число объектов в списке @@ -26,93 +26,77 @@ public class ListgenericObjects 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; + + public int SetMaxCount { set => throw new NotImplementedException(); } /// /// Конструктор /// - public ListgenericObjects(int count) + public ListGenericObjects() { - _maxCount = count; _collection = new(); } - - /// - /// Получение объекта из набора позиции - /// - /// - /// - public T? this[int position] + public T? Get(int position) { - get - { - if (position < 0 || position >= _maxCount) - { - return null; - } - - return _collection?[position]; - } - - set - { - if (!(position >= 0 && position < Count && _collection?.Count < _maxCount)) - { - return; - } - - _collection?.Insert(position, value); - return; - } + // TODO проверка позиции + if (position < 0 || position >= Count) return null; + return _collection[position]; } public bool Insert(T obj) { - if (_collection?.Count == _maxCount) + // TODO проверка, что не превышено максимальное количество элементов + // TODO вставка в конец набора + if (Convert.ToInt32(obj) <= _maxCount) { - return false; + _collection.Add(obj); } - - Insert(obj, 0); return true; } public bool Insert(T obj, int position) { - if (_collection?.Count == _maxCount) - { - return false; - } + // TODO проверка, что не превышено максимальное количество элементов + // TODO проверка позиции + // TODO вставка по позиции - Insert(obj, 0); + if (Convert.ToInt32(obj) >= _maxCount) { return false; } + + if (position < 0 || position >= Count) { return false; } + + else { _collection.Add(obj); } return true; } public bool Remove(int position) { - if (position < 0 || position >= Count) - { - return false; - } - - _collection?.RemoveAt(position); + // TODO проверка позиции + // TODO удаление объекта из списка + if (position < 0 || position >= Count) { return false; } + _collection.RemoveAt(position); return true; } - /// - /// Проход по списку - /// - /// - public IEnumerable GetTheAirplanes(int? maxTheAirplanes = null) + public IEnumerable GetItems() { - for (int i = 0; i < _collection?.Count; ++i) + for (int i = 0; i < _collection.ToArray().Length; ++i) { - yield return _collection?[i]; - if (maxTheAirplanes.HasValue && i == maxTheAirplanes.Value) - { - yield break; - } + yield return _collection[i]; } } -} +} \ No newline at end of file diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/MassiveGenericObjects.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/MassiveGenericObjects.cs index 578626e..2594e4f 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProectMilitaryAircraft.Draw; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -11,7 +12,7 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects /// /// Параметр : Ограничение - ссылочный тип public class MassiveGenericObjects : ICollectionGenericObjects - where T : class + where T : DrawningAircraft { /// /// Массив объектов, которые храним @@ -19,7 +20,9 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects private T?[] _massive; public int Count => _massive.Length; - public int SetMaxCount { set { if (value > 0) { _massive = new T?[value]; } } } + public int MaxCount { get { return _massive.Length; } set { if (value > 0) { _massive = new T?[value]; } } } + + public CollectionType GetCollectionType => CollectionType.Massive; /// /// Конструктор @@ -81,6 +84,14 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects _massive[position] = null; return true; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _massive.Length; ++i) + { + yield return _massive[i]; + } + } } } diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/StorageCollection.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/StorageCollection.cs index 0e2a472..4e5ba4e 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/StorageCollection.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using ProectMilitaryAircraft.MovementStrategy; +using ProectMilitaryAircraft.Draw; +using ProectMilitaryAircraft.MovementStrategy; using System; using System.Collections.Generic; using System.Linq; @@ -8,7 +9,7 @@ using System.Threading.Tasks; namespace ProectMilitaryAircraft.CollectionGenericObjects; public class StorageCollection - where T : class + where T : DrawningAircraft { readonly Dictionary> _storages; @@ -19,6 +20,21 @@ public class StorageCollection _storages = new Dictionary>(); } + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + public void AddCollection (string name, CollectionType collectionType) { if (name != null && !_storages.ContainsKey(name)) @@ -30,7 +46,7 @@ public class StorageCollection } if (collectionType == CollectionType.List) { - _storages.Add(name, new MassiveGenericObjects()); + _storages.Add(name, new ListGenericObjects()); } } @@ -57,4 +73,145 @@ 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.Count); + 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?.CreateDrawningCar() is T car) + { + if (!collection.Insert(car)) + { + 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/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/DrawningAircraft.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/DrawningAircraft.cs index 51b60c9..370e7ed 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/DrawningAircraft.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/DrawningAircraft.cs @@ -33,6 +33,7 @@ public class DrawningAircraft /// Верхняя координа прорисовки самолета /// protected int? _startPosY; + public DrawningAircraft aircraft; /// /// Ширина прорисовки самолета @@ -68,14 +69,14 @@ public class DrawningAircraft /// /// Пустой конструктор /// - private DrawningAircraft() + public DrawningAircraft() { _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } - + /// /// Конструктор /// @@ -90,7 +91,7 @@ public class DrawningAircraft return; } _pictureWidth = width; - _pictureHeight = height; + _pictureHeight = height; EntityAircraft = new EntityAircraft(speed, weight, bodyColor); } @@ -112,6 +113,18 @@ public class DrawningAircraft _drawingMilitaryAircraftHeight = drawingMilitaryAircraftHeight; EntityAircraft = new EntityAircraft(speed, weight, bodyColor); } + + /// + /// Конструктор для Drawning + /// + /// + /// + /// + public DrawningAircraft(EntityAircraft entityAircraft) + { + EntityAircraft = entityAircraft; + } + /// /// Установка границ поля /// diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/DrawningMilitaryAircraft.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/DrawningMilitaryAircraft.cs index 0713114..86648c5 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/DrawningMilitaryAircraft.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/DrawningMilitaryAircraft.cs @@ -15,6 +15,8 @@ namespace ProectMilitaryAircraft.Draw; /// public class DrawningMilitaryAircraft : DrawningAircraft { + private DrawningAircraft aircraft; + /// /// Констуктор /// @@ -34,6 +36,25 @@ public class DrawningMilitaryAircraft : DrawningAircraft } } + + /// + /// Конструктор для DrawningAircraft2 + /// + /// + /// + /// + /// + /// + /// + /// + public DrawningMilitaryAircraft(EntityAircraft entityAircraft) + { + if (entityAircraft != null) + { + EntityAircraft = entityAircraft; + } + } + public override void DrawTransport(Graphics g) { if (EntityAircraft is not EntityMilitaryAircraft airCraft || !_startPosX.HasValue || !_startPosY.HasValue) @@ -116,7 +137,7 @@ public class DrawningMilitaryAircraft : DrawningAircraft //Носовая часть g.FillEllipse(abr, _startPosX.Value + 78, _startPosY.Value + 37, 10, 5); } - + } } diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/ExtensionDrawningAircraft.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/ExtensionDrawningAircraft.cs new file mode 100644 index 0000000..116b6e4 --- /dev/null +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/Draw/ExtensionDrawningAircraft.cs @@ -0,0 +1,59 @@ +using ProectMilitaryAircraft.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProectMilitaryAircraft.Draw; + +/// +/// Расширение для класса EntityCar +/// +public static class ExtensionDrawningAircraft +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningAircraft? CreateDrawningCar(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityAircraft? aircraft = EntityMilitaryAircraft.CreateEntityMilitaryAircraft(strs); + if (aircraft != null) + { + return new DrawningMilitaryAircraft(aircraft); + } + + aircraft = EntityAircraft.CreateEntityAircraft(strs); + if (aircraft != null) + { + return new DrawningAircraft(aircraft); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningAircraft drawningAircraft) + { + string[]? array = drawningAircraft?.EntityAircraft?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/Entities/EntityAircraft.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/Entities/EntityAircraft.cs index fb3a21c..cd015fc 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/Entities/EntityAircraft.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/Entities/EntityAircraft.cs @@ -45,4 +45,27 @@ public class EntityAircraft BodyColor = bodyColor; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityAircraft? CreateEntityAircraft(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityAircraft)) + { + return null; + } + + return new EntityAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/Entities/EntityMilitaryAircraft.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/Entities/EntityMilitaryAircraft.cs index 8deb593..711980b 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/Entities/EntityMilitaryAircraft.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/Entities/EntityMilitaryAircraft.cs @@ -43,4 +43,27 @@ public class EntityMilitaryAircraft : EntityAircraft Rokets = rokets; Symbolism = symbolism; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityMilitaryAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityMilitaryAircraft? CreateEntityMilitaryAircraft(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityMilitaryAircraft)) + { + return null; + } + return new EntityMilitaryAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } } \ No newline at end of file diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.Designer.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.Designer.cs index 5fb26d0..cecaac4 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.Designer.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.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(607, 0); + groupBoxTools.Location = new Point(607, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(194, 563); + groupBoxTools.Size = new Size(194, 560); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = " Инструменты"; @@ -239,19 +246,61 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(607, 563); + pictureBox.Size = new Size(607, 560); 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(801, 24); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(48, 20); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(181, 22); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(181, 22); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormAircraftCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(801, 563); + ClientSize = new Size(801, 584); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormAircraftCollection"; Text = "Коллекция самолетов"; groupBoxTools.ResumeLayout(false); @@ -260,7 +309,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -283,5 +335,11 @@ private Button buttonCreateCompany; private Button buttonCollectionDel; 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/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.cs b/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.cs index 7d23d8b..eb96ae1 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.cs +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.cs @@ -35,7 +35,7 @@ public partial class FormAircraftCollection : Form public FormAircraftCollection() { InitializeComponent(); - _storageCollection = new(); + _storageCollection = new(); } /// /// Выбор компании @@ -44,7 +44,7 @@ public partial class FormAircraftCollection : Form /// private void ComboBoxSelectorCompany_SelectedValueChanged(object sender, EventArgs e) { - panelCompanyTools.Enabled = false; + panelCompanyTools.Enabled = false; } /// @@ -76,7 +76,7 @@ public partial class FormAircraftCollection : Form if (_company + aircraft) { - + MessageBox.Show("не удалось добавить объект"); pictureBox.Image = _company.Show(); } @@ -181,7 +181,7 @@ public partial class FormAircraftCollection : Form { collectionType = CollectionType.Massive; } - else if (radioButtonList.Checked) + else if (radioButtonList.Checked) { collectionType = CollectionType.List; } @@ -213,7 +213,7 @@ public partial class FormAircraftCollection : Form private void RefreshListBoxItems() { listBoxCollection.Items.Clear(); - for (int i =0; i < _storageCollection.Keys?.Count; i++) + for (int i = 0; i < _storageCollection.Keys?.Count; i++) { string? colName = _storageCollection.Keys?[i]; if (!string.IsNullOrEmpty(colName)) @@ -236,7 +236,7 @@ public partial class FormAircraftCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString()?? string.Empty]; + ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллкция не проиницилизирована"); @@ -253,4 +253,45 @@ public partial class FormAircraftCollection : Form panelCompanyTools.Enabled = true; } + + /// + /// Обработка нажатия на "Сохранение" + /// + /// + /// + 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); + RefreshListBoxItems(); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.resx b/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.resx index af32865..47b8d2b 100644 --- a/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.resx +++ b/ProectMilitaryAircraft/ProectMilitaryAircraft/FormAircraftCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 16, 5 + + + 125, 5 + + + 260, 5 + + + 48 + \ No newline at end of file