diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/AbstractCompany.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/AbstractCompany.cs index e0b8cb2..e072f57 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/AbstractCompany.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/AbstractCompany.cs @@ -48,7 +48,7 @@ private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _ _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// /// Перегрузка оператора сложения для класса diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs index 4570ed8..95297cd 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectAccordionBus.CollectionGenericObjects; +using AccordionBus.CollectionGenericObjects; + +namespace ProjectAccordionBus.CollectionGenericObjects; /// /// Интерфейс описания действий для набора хранимых объектов /// @@ -10,15 +12,16 @@ where T : class /// Количество объектов в коллекции /// int Count { get; } - /// - /// Установка максимального количества элементов - /// - int SetMaxCount { set; } + /// + /// Установка макс. кол-ва элементов + int MaxCount { get; set; } + /// /// /// Добавление объекта в коллекцию /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -39,4 +42,13 @@ where T : class /// Позиция /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs index d322bea..1f8eae4 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs @@ -12,8 +12,18 @@ public class ListGenericObjects:ICollectionGenericObjects where T : class private readonly List _collection; private int _maxCount; public int Count => _collection.Count; + public CollectionType GetCollectionType => CollectionType.List; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount { + get + { + return _maxCount; + } + set + { + if (value > 0) _maxCount = value; + } + } /// /// Конструктор @@ -61,4 +71,12 @@ public class ListGenericObjects:ICollectionGenericObjects where T : class _collection?.RemoveAt(position); return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; i++) + { + yield return _collection[i]; + } + } } diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs index 3358e36..076a5f1 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -14,8 +14,12 @@ where T : class /// private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -31,6 +35,10 @@ where T : class } } } + + + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -95,4 +103,11 @@ where T : class return temp; } + public IEnumerable GetItems() + { + for(int i=0;i<_collection.Length;i++) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs index 5d355d7..d260435 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs @@ -1,16 +1,13 @@ -using ProjectAccordionBus.CollectionGenericObjects; -using System; -using System.Collections.Generic; -using System.Linq; +using AccordionBus.Drawnings; +using ProjectAccordionBus.CollectionGenericObjects; using System.Text; -using System.Threading.Tasks; namespace AccordionBus.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// -public class StorageCollection where T : class +public class StorageCollection where T : DrawningBus { /// /// Словарь (хранилище) с коллекциями @@ -83,4 +80,137 @@ public class StorageCollection where T : class return null; } } + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// + /// Сохранение информации по самолетам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + return false; + + if (File.Exists(filename)) + File.Delete(filename); + + using FileStream fs = new(filename, FileMode.Create); + using StreamWriter sw = new StreamWriter(fs); + sw.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + sw.Write(Environment.NewLine); + if (value.Value.Count == 0) + { + continue; + } + + sw.Write(value.Key); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.GetCollectionType); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.MaxCount); + sw.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sw.Write(data); + sw.Write(_separatorItems); + } + } + return true; + } + + /// + /// Загрузка информации по самолетам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (FileStream fs = new(filename, FileMode.Open)) + { + using StreamReader sr = new StreamReader(fs); + + string str = sr.ReadLine(); + if (str == null || str.Length == 0) + { + return false; + } + + if (!str.Equals(_collectionKey)) + { + return false; + } + _storages.Clear(); + + while (!sr.EndOfStream) + { + string[] record = sr.ReadLine().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?.CreateDrawningBus() is T bus) + { + if (collection.Insert(bus) == -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/AccordionBus/AccordionBus/Drawnings/DrawningAccordionBus.cs b/AccordionBus/AccordionBus/Drawnings/DrawningAccordionBus.cs index d624452..9cdcede 100644 --- a/AccordionBus/AccordionBus/Drawnings/DrawningAccordionBus.cs +++ b/AccordionBus/AccordionBus/Drawnings/DrawningAccordionBus.cs @@ -19,7 +19,11 @@ public class DrawningAccordionBus:DrawningBus /// Дополнительный цвет /// Признак наличия стёкол /// /// Признак наличия гармошки - + + public DrawningAccordionBus(EntityAccordionBus bus) : base(200, 40) + { + EntityBus = bus; + } public DrawningAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyGlass,bool garmoshka): base(200, 40) { diff --git a/AccordionBus/AccordionBus/Drawnings/DrawningBus.cs b/AccordionBus/AccordionBus/Drawnings/DrawningBus.cs index 6f8b271..c928444 100644 --- a/AccordionBus/AccordionBus/Drawnings/DrawningBus.cs +++ b/AccordionBus/AccordionBus/Drawnings/DrawningBus.cs @@ -55,6 +55,11 @@ public class DrawningBus /// public int GetHeight => _drawningBusHeight; + public DrawningBus(EntityBus bus) + { + EntityBus = bus; + } + /// /// Пустой конструктор /// diff --git a/AccordionBus/AccordionBus/Drawnings/ExtentionDrawningCar.cs b/AccordionBus/AccordionBus/Drawnings/ExtentionDrawningCar.cs new file mode 100644 index 0000000..2d107b5 --- /dev/null +++ b/AccordionBus/AccordionBus/Drawnings/ExtentionDrawningCar.cs @@ -0,0 +1,50 @@ +using AccordionBus.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Drawnings; + +public static class ExtentionDrawningBus +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningBus? CreateDrawningBus(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityBus? bus = EntityAccordionBus.CreateEntityAccordionBus(strs); + if (bus != null && bus is EntityAccordionBus bus1) + { + return new DrawningAccordionBus(bus1); + } + bus = EntityBus.CreateEntityBus(strs); + if (bus != null) + { + return new DrawningBus(bus); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningBus drawningBus) + { + string[]? array = drawningBus?.EntityBus?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } +} diff --git a/AccordionBus/AccordionBus/Entities/EntityAccordionBus.cs b/AccordionBus/AccordionBus/Entities/EntityAccordionBus.cs index 1bc6153..fb38d9f 100644 --- a/AccordionBus/AccordionBus/Entities/EntityAccordionBus.cs +++ b/AccordionBus/AccordionBus/Entities/EntityAccordionBus.cs @@ -45,4 +45,16 @@ public class EntityAccordionBus: EntityBus { AdditionalColor = color; } + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityAccordionBus), Speed.ToString(), Weight.ToString(), BodyColor.Name, + AdditionalColor.Name, BodyGlass.ToString(), BodyGarmoshka.ToString() }; + } + public static EntityAccordionBus? CreateEntityAccordionBus(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityAccordionBus)) { return null; } + + return new EntityAccordionBus(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/AccordionBus/AccordionBus/Entities/EntityBus.cs b/AccordionBus/AccordionBus/Entities/EntityBus.cs index 414e426..877cb52 100644 --- a/AccordionBus/AccordionBus/Entities/EntityBus.cs +++ b/AccordionBus/AccordionBus/Entities/EntityBus.cs @@ -46,4 +46,22 @@ public class EntityBus { BodyColor = color; } + + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityBus), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityBus? CreateEntityBus(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityBus)) + { + return null; + } + return new EntityBus(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/FormBusCollection.Designer.cs b/AccordionBus/AccordionBus/FormBusCollection.Designer.cs index 3f3cdee..a77b5ed 100644 --- a/AccordionBus/AccordionBus/FormBusCollection.Designer.cs +++ b/AccordionBus/AccordionBus/FormBusCollection.Designer.cs @@ -47,10 +47,17 @@ comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); colorDialog1 = new ColorDialog(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new SaveFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -60,9 +67,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(1011, 0); + groupBoxTools.Location = new Point(1011, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(231, 599); + groupBoxTools.Size = new Size(231, 575); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -76,7 +83,7 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 441); + panelCompanyTools.Location = new Point(3, 417); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(225, 155); panelCompanyTools.TabIndex = 10; @@ -240,12 +247,49 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1011, 599); + pictureBox.Size = new Size(1011, 575); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1242, 24); + menuStrip.TabIndex = 4; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(48, 20); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.Size = new Size(141, 22); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.Size = new Size(141, 22); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file|*.txt"; + // openFileDialog + // + openFileDialog.Filter = "txt file|*.txt"; + // // FormBusCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -253,6 +297,8 @@ ClientSize = new Size(1242, 599); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBusCollection"; Text = "Коллекция автобусов"; groupBoxTools.ResumeLayout(false); @@ -261,7 +307,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -285,5 +334,11 @@ private Button buttonCollectionAdd; private Button buttonCreateCompany; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private SaveFileDialog openFileDialog; } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/FormBusCollection.cs b/AccordionBus/AccordionBus/FormBusCollection.cs index b95fd39..bc5fa1d 100644 --- a/AccordionBus/AccordionBus/FormBusCollection.cs +++ b/AccordionBus/AccordionBus/FormBusCollection.cs @@ -57,7 +57,8 @@ public partial class FormBusCollection : Form /// /// /// - private void ButtonAddBus_Click(object sender, EventArgs e) { + private void ButtonAddBus_Click(object sender, EventArgs e) + { FormBusConfig form = new(); form.Show(); form.AddEvent(SetBus); @@ -78,7 +79,7 @@ public partial class FormBusCollection : Form return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos!=null) + if (_company - pos != null) { MessageBox.Show("Объект удален"); pictureBox.Image = _company.Show(); @@ -206,4 +207,36 @@ public partial class FormBusCollection : Form RefreshListBoxItems(); } + 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); + } + } + } + + 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); + } + } + } } diff --git a/AccordionBus/AccordionBus/FormBusCollection.resx b/AccordionBus/AccordionBus/FormBusCollection.resx index 818dfae..0bbe40d 100644 --- a/AccordionBus/AccordionBus/FormBusCollection.resx +++ b/AccordionBus/AccordionBus/FormBusCollection.resx @@ -120,4 +120,13 @@ 17, 17 + + 138, 17 + + + 247, 17 + + + 376, 17 + \ No newline at end of file