From f00e0c5a8ccf0578ba025804a88403ff9aab3bee Mon Sep 17 00:00:00 2001 From: BoiledMilk123 Date: Tue, 7 May 2024 02:10:53 +0400 Subject: [PATCH] labwork06 --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 15 +- .../ListGenericObjects.cs | 26 +++- .../LocomotiveDepot.cs | 10 +- .../MassiveGenericObjects.cs | 31 +++- .../StorageCollection.cs | 138 +++++++++++++++++- .../Drawnings/DrawningElectricLocomotive.cs | 5 + .../Drawnings/DrawningLocomotive.cs | 5 + .../Drawnings/ExtentionDrawningLocomotive.cs | 53 +++++++ .../Entities/EntityElectricLocomotive.cs | 23 +++ .../Entities/EntityLocomotive.cs | 22 +++ .../FormLocomotiveCollection.Designer.cs | 68 ++++++++- .../FormLocomotiveCollection.cs | 56 ++++++- .../FormLocomotiveCollection.resx | 9 ++ 14 files changed, 435 insertions(+), 28 deletions(-) create mode 100644 ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/ExtentionDrawningLocomotive.cs diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs index 0173f6e..20c3f40 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs @@ -50,7 +50,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs index c5a8798..9eb3578 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -17,10 +17,12 @@ public interface ICollectionGenericObjects /// Количество объектов в коллекции /// int Count { get; } + /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } + /// /// Добавление объекта в коллекцию /// @@ -46,4 +48,15 @@ public interface ICollectionGenericObjects /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// + IEnumerable GetItems(); + } \ No newline at end of file diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs index 27a8078..325c0bb 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs @@ -20,7 +20,23 @@ 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 _collection.Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -76,4 +92,12 @@ public class ListGenericObjects : ICollectionGenericObjects return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/LocomotiveDepot.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/LocomotiveDepot.cs index 386ef83..f6e9926 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/LocomotiveDepot.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/LocomotiveDepot.cs @@ -25,9 +25,9 @@ public class LocomotiveDepot : AbstractCompany int count_width = _pictureWidth / _placeSizeWidth; // кол-во мест в ширину int count_height = _pictureHeight / _placeSizeHeight; // кол-во мест в длинну Pen pen = new(Color.Black, 3); - for (int i = 0; i < count_width; i++) + for (int i = 0; i < count_width ; i++) { - for (int j = 0; j < count_height + 1; ++j) + for (int j = 0; j < count_height + 1 ; ++j) { g.DrawLine(pen, i * _placeSizeWidth + 10, j * _placeSizeHeight + 5 , i * _placeSizeWidth + _placeSizeWidth - 50, j * _placeSizeHeight + 5); g.DrawLine(pen, i * _placeSizeWidth + 10, j * _placeSizeHeight , i * _placeSizeWidth + 10, j * _placeSizeHeight + _placeSizeHeight ); @@ -45,12 +45,12 @@ public class LocomotiveDepot : AbstractCompany if (_collection?.Count != null) { - for (int i = 0; i < (_collection.Count); i++) + for (int i = 0; i < (_collection?.Count); i++) { if (_collection.Get(i) != null) { - _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i).SetPosition(_placeSizeWidth * positionWidth + 25, positionHeight * _placeSizeHeight + 10); + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(_placeSizeWidth * positionWidth + 25, positionHeight * _placeSizeHeight + 10); } if (positionWidth < width - 1) diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs index 8e31670..0f1f62d 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs @@ -20,7 +20,28 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount { set { if (Count > 0) { Array.Resize(ref _collection, value); } else { _collection = new T?[value]; } } } + public int MaxCount + { + get + { + return _collection.Length; + } + set + { + if (value > 0) + { + if (_collection.Length > 0) + { + Array.Resize(ref _collection, value); + } + else _collection = new T?[value]; + } + } + } + + public CollectionType GetCollectionType => CollectionType.Massive; + + /// /// Конструктор @@ -104,4 +125,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return removedObject; } + + public IEnumerable GetItems() + { + for( int i = 0; i < _collection.Length; ++i ) + { + yield return _collection[i]; + } + } } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs index f869a1b..90c3e24 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using ProjectElectricLocomotive.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -11,7 +12,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningLocomotive { /// /// Словарь с коллекциями @@ -23,6 +24,21 @@ public class StorageCollection /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -64,14 +80,13 @@ public class StorageCollection } } - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[int index] { get { - // логика получения объекта (если есть запись с ключом мы должны вернуть объект иначе значение словаря по ключу) - if (_storages.ContainsKey(name)) + if (index >= 0 && index < _storages.Count) { - return _storages[name]; + return _storages.ElementAt(index).Value; } else { @@ -79,4 +94,115 @@ public class StorageCollection } } } + + + /// + /// Сохранение информации по автомобилям в хранилице в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + + if (_storages.Count == 0) return false; + + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.WriteLine(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}"); + writer.Write(_separatorItems); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (!string.IsNullOrEmpty(data)) + { + writer.Write(data + _separatorItems); + } + } + writer.WriteLine(); + } + } + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) return false; + + using (StreamReader reader = new StreamReader(filename)) + { + string line = reader.ReadLine(); + + if (line == null || !line.Equals(_collectionKey)) + { + return false; + } + + _storages.Clear(); + + while (line != null) + { + string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + + if (record.Length != 4) + { + line = reader.ReadLine(); + 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?.CreateDrawningLocomotive() is T locomotive) + { + if (collection.Insert(locomotive) == -1) + { + return false; + } + } + } + _storages.Add(record[0], collection); + + line = reader.ReadLine(); + } + } + + return true; + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs index c9283c8..7d5c237 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs @@ -22,6 +22,11 @@ public class DrawningElectricLocomotive : DrawningLocomotive EntityLocomotive = new EntityElectricLocomotive(speed, weight, bodyColor, additionalColor, electricHorns, batteryPlacement); } + public DrawningElectricLocomotive(EntityLocomotive locomotive) : base(locomotive) + { + + } + public override void DrawTransport(Graphics g) { if (EntityLocomotive == null || EntityLocomotive is not EntityElectricLocomotive electricLocomotive || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs index b5c64de..0a123a3 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs @@ -87,6 +87,11 @@ public class DrawningLocomotive EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor); } + public DrawningLocomotive(EntityLocomotive locomotive) + { + EntityLocomotive = locomotive; + } + /// /// Конструктор для наследников /// diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/ExtentionDrawningLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/ExtentionDrawningLocomotive.cs new file mode 100644 index 0000000..77f1352 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/ExtentionDrawningLocomotive.cs @@ -0,0 +1,53 @@ +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +public static class ExtentionDrawningLocomotive +{ + + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningLocomotive? CreateDrawningLocomotive(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityLocomotive? locomotive = EntityElectricLocomotive.CreateEntityElectricLocomotive(strs); + if (locomotive != null) + { + return new DrawningElectricLocomotive(locomotive); + } + locomotive = EntityLocomotive.CreateEntityLocomotive(strs); + if (locomotive != null) + { + return new DrawningLocomotive(locomotive); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawningLocomotive drawningLocomotive) + { + string[]? array = drawningLocomotive?.EntityLocomotive?.GetStringRepresentation(); + + if (array == null) return string.Empty; + + return string.Join(_separatorForObject, array); + + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs index da17af0..bbc829e 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs @@ -42,4 +42,27 @@ public class EntityElectricLocomotive : EntityLocomotive { AdditionalColor = color; } + + /// + /// Получение строк с значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityElectricLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, ElectricHorns.ToString(), BatteryPlacement.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityElectricLocomotive? CreateEntityElectricLocomotive(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityElectricLocomotive)) + { + return null; + } + return new EntityElectricLocomotive(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/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityLocomotive.cs index a4fff9e..dd000d6 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityLocomotive.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityLocomotive.cs @@ -47,4 +47,26 @@ public class EntityLocomotive { BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + public static EntityLocomotive? CreateEntityLocomotive(string[] strs) + { + if(strs.Length != 4 || strs[0] != nameof(EntityLocomotive)) + { + return null; + } + return new EntityLocomotive(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs index d2b0584..85e6d7b 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs @@ -47,10 +47,17 @@ labelCollectionName = new Label(); pictureBox = new PictureBox(); colorDialog1 = new ColorDialog(); + 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(panelCompanyTools); groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(640, 0); + groupBoxTools.Location = new Point(640, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(200, 593); + groupBoxTools.Size = new Size(200, 569); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -98,7 +105,7 @@ panelCompanyTools.Controls.Add(buttonRemoveLocomotive); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 364); + panelCompanyTools.Location = new Point(3, 340); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(194, 226); panelCompanyTools.TabIndex = 8; @@ -237,12 +244,52 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(640, 593); + pictureBox.Size = new Size(640, 569); 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(840, 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(173, 22); + saveToolStripMenuItem.Text = "Сохранить"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(173, 22); + loadToolStripMenuItem.Text = "Загрузить"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file|*.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file|*.txt"; + // // FormLocomotiveCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -250,6 +297,8 @@ ClientSize = new Size(840, 593); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormLocomotiveCollection"; Text = "FormLocomotiveCollection"; groupBoxTools.ResumeLayout(false); @@ -258,7 +307,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -282,5 +334,11 @@ private RadioButton radioButtonList; 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/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs index 83ec660..19b6768 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs @@ -62,7 +62,7 @@ public partial class FormLocomotiveCollection : Form /// private void SetLocomotive(DrawningLocomotive locomotive) { - if(_company == null || locomotive == null) + if (_company == null || locomotive == null) { return; } @@ -160,18 +160,18 @@ public partial class FormLocomotiveCollection : Form /// private void ButtonCollectionAdd_Click(object sender, EventArgs e) { - if(string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } CollectionType collectionType = CollectionType.None; - if(radioButtonMassive.Checked) + if (radioButtonMassive.Checked) { collectionType = CollectionType.Massive; } - else if (radioButtonList.Checked) + else if (radioButtonList.Checked) { collectionType = CollectionType.List; } @@ -207,10 +207,9 @@ public partial class FormLocomotiveCollection : Form private void RefreshListBoxItems() { listBoxCollection.Items.Clear(); - for(int i = 0; i < _storageCollection.Keys?.Count; ++i) + foreach(string colName in _storageCollection.Keys) { - string? colName = _storageCollection.Keys?[i]; - if(!string.IsNullOrEmpty(colName) ) + if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); } @@ -230,7 +229,7 @@ public partial class FormLocomotiveCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedIndex]; if (collection == null) { MessageBox.Show("Коллекция не проиннициализирована"); @@ -245,4 +244,45 @@ public partial class FormLocomotiveCollection : 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)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RefreshListBoxItems(); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.resx b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.resx index 818dfae..98c6f9e 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.resx +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.resx @@ -120,4 +120,13 @@ 17, 17 + + 138, 17 + + + 247, 17 + + + 382, 17 + \ No newline at end of file