diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs index 85dc5d6..e61a6fa 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs @@ -46,7 +46,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs index 515fb9d..e132cea 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -15,7 +15,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального кол-ва объектов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллецию @@ -44,4 +44,16 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементный вывод элементов коллекции + IEnumerable GetItems(); + } diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs index e9fec46..8c54936 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs @@ -19,7 +19,9 @@ public class ListGenericObjects : ICollectionGenericObjects 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; /// /// конструктор @@ -68,4 +70,12 @@ public class ListGenericObjects : ICollectionGenericObjects } return null; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; i++) + { + yield return _collection[i]; + } + } } diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs index 3307fc2..944ded4 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -14,8 +14,13 @@ 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,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + + public CollectionType GetCollectionType => CollectionType.Massive; + + /// /// Конструктор /// @@ -119,4 +128,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; i++) + { + yield return _collection[i]; + } + } + } diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs index f8d9499..c96f572 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,14 @@ -namespace ProjectTrolleybus.CollectionGenericObjects; +using ProjectTrolleybus.Drawnings; +using System.Text; + +namespace ProjectTrolleybus.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningTrolleyB { /// /// Словарь (хранилище) с коллекциями @@ -16,7 +19,22 @@ public class StorageCollection /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); - + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -69,4 +87,136 @@ 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); + } + + + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + writer.Write(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) + { + continue; + } + + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.GetCollectionType); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + writer.Write(data); + writer.Write(_separatorItems); + } + } + } + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (StreamReader reader = File.OpenText(filename)) + { + string str = reader.ReadLine(); + + if (str == null || str.Length == 0) + { + return false; + } + + if (!str.StartsWith(_collectionKey)) + { + //если нет такой записи, то это не те данные + return false; + } + + _storages.Clear(); + string strs = ""; + while ((strs = reader.ReadLine()) != null) + { + string[] record = strs.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?.CreateDrawningTrolleyB() is T trolleyB) + { + if (collection.Insert(trolleyB) == -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/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyB.cs b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyB.cs index ab71e3d..da530b6 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyB.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyB.cs @@ -1,4 +1,5 @@ using ProjectTrolleybus.Entities; +using System.Security.Policy; namespace ProjectTrolleybus.Drawnings; @@ -62,7 +63,7 @@ public class DrawningTrolleyB /// /// Пустой конструктор /// - private DrawningTrolleyB() + public DrawningTrolleyB() { _pictureHeight = null; _pictureWidth = null; @@ -93,6 +94,15 @@ public class DrawningTrolleyB _drawningVehicleHeight = drawningVehicleHeight; } + /// + /// Конструктор, принимающий объект EntityTrolleyB в качестве параметра + /// + /// + public DrawningTrolleyB(EntityTrolleyB bull) : this() + { + EntityTrolleyB = new EntityTrolleyB(bull.Speed, bull.Weight, bull.BodyColor); + } + /// /// Установка границ поля /// diff --git a/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleybus.cs b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleybus.cs index d9db6e6..dddb33b 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleybus.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleybus.cs @@ -22,6 +22,15 @@ public class DrawningTrolleybus : DrawningTrolleyB EntityTrolleyB = new EntityTrolleybus(speed, weight, bodyColor, additionalColor, batteryCompartment, horns); } + /// + /// Конструктор, принимающий объект EntityTrolleyB в качестве параметра + /// + /// + public DrawningTrolleybus(EntityTrolleybus exc) : base(120, 80) + { + EntityTrolleyB = new EntityTrolleybus(exc.Speed, exc.Weight, exc.BodyColor, exc.AdditionalColor, exc.BatteryCompartment, exc.Horns); + } + public override void DrawTransport(Graphics g) { diff --git a/ProjectTrolleybus/ProjectTrolleybus/Drawnings/ExtentionDrawningTrolleyB.cs b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/ExtentionDrawningTrolleyB.cs new file mode 100644 index 0000000..94c3e6b --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/ExtentionDrawningTrolleyB.cs @@ -0,0 +1,54 @@ +using ProjectTrolleybus.Entities; + +namespace ProjectTrolleybus.Drawnings; + +/// +/// Расширение для класса EntityTrolleyB +/// +public static class ExtentionDrawningTrolleyB +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningTrolleyB? CreateDrawningTrolleyB(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityTrolleyB? trolleyB = EntityTrolleybus.CreateEntityTrolleybus(strs); + if (trolleyB != null) + { + return new DrawningTrolleybus((EntityTrolleybus)trolleyB); + } + + trolleyB = EntityTrolleyB.CreateEntityTrolleyB(strs); + if (trolleyB != null) + { + return new DrawningTrolleyB(trolleyB); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningTrolleyB drawningTrolleyB) + { + string[]? array = drawningTrolleyB?.EntityTrolleyB?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectTrolleybus/ProjectTrolleybus/Entities/EntityTrolleyB.cs b/ProjectTrolleybus/ProjectTrolleybus/Entities/EntityTrolleyB.cs index dde604a..cab67e1 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/Entities/EntityTrolleyB.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/Entities/EntityTrolleyB.cs @@ -43,4 +43,28 @@ public class EntityTrolleyB Weight = weight; BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityTrolleyB), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityTrolleyB? CreateEntityTrolleyB(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityTrolleyB)) + { + return null; + } + + return new EntityTrolleyB(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectTrolleybus/ProjectTrolleybus/Entities/EntityTrolleybus.cs b/ProjectTrolleybus/ProjectTrolleybus/Entities/EntityTrolleybus.cs index 142893f..d1b3bc6 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/Entities/EntityTrolleybus.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/Entities/EntityTrolleybus.cs @@ -39,4 +39,28 @@ public class EntityTrolleybus : EntityTrolleyB BatteryCompartment = batteryCompartment; Horns = horns; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityTrolleybus), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, BatteryCompartment.ToString(), Horns.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityTrolleybus? CreateEntityTrolleybus(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityTrolleybus)) + { + return null; + } + + return new EntityTrolleybus(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/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.Designer.cs b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.Designer.cs index 27b8b56..495a441 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.Designer.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.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(861, 0); + groupBoxTools.Location = new Point(875, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(201, 645); + groupBoxTools.Size = new Size(201, 636); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -75,7 +82,7 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 364); + panelCompanyTools.Location = new Point(3, 355); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(195, 278); panelCompanyTools.TabIndex = 8; @@ -136,7 +143,7 @@ // // buttonCreateCompany // - buttonCreateCompany.Location = new Point(12, 335); + buttonCreateCompany.Location = new Point(12, 324); buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Size = new Size(177, 23); buttonCreateCompany.TabIndex = 7; @@ -241,19 +248,62 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(861, 645); + pictureBox.Size = new Size(875, 636); 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(1076, 24); + menuStrip.TabIndex = 2; + 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.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.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file | *.txt"; + // // FormTrolleyBCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1062, 645); + ClientSize = new Size(1076, 660); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormTrolleyBCollection"; Text = "Коллекция троллейбусов"; groupBoxTools.ResumeLayout(false); @@ -262,7 +312,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -285,5 +338,11 @@ private ListBox listBoxCollection; 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/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs index ff8799d..38b8704 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs @@ -1,5 +1,6 @@ using ProjectTrolleybus.CollectionGenericObjects; using ProjectTrolleybus.Drawnings; +using System.Windows.Forms; namespace ProjectTrolleybus; @@ -245,4 +246,46 @@ public partial class FormTrolleyBCollection : Form } } } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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); + + RerfreshListBoxItems(); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.resx b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.resx index af32865..d5caa48 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.resx +++ b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 261, 17 + + + 52 + \ No newline at end of file