diff --git a/ProjectCar/ProjectCar/CollectionGenericObjects/AbstractCompany.cs b/ProjectCar/ProjectCar/CollectionGenericObjects/AbstractCompany.cs index fe1d6b0..f7a1147 100644 --- a/ProjectCar/ProjectCar/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectCar/ProjectCar/CollectionGenericObjects/AbstractCompany.cs @@ -53,7 +53,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectCar/ProjectCar/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectCar/ProjectCar/CollectionGenericObjects/ICollectionGenericObjects.cs index 89631a1..5aeb486 100644 --- a/ProjectCar/ProjectCar/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectCar/ProjectCar/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectGasMachine.CollectionGenericObjects; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -21,7 +22,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -51,4 +52,15 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectCar/ProjectCar/CollectionGenericObjects/ListGenericObjects.cs b/ProjectCar/ProjectCar/CollectionGenericObjects/ListGenericObjects.cs index be63af4..0ac85cf 100644 --- a/ProjectCar/ProjectCar/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectCar/ProjectCar/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectGasMachine.CollectionGenericObjects; + +namespace ProjectGasMachine.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -19,7 +20,10 @@ 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; + /// /// Конструктор @@ -73,4 +77,12 @@ public class ListGenericObjects : ICollectionGenericObjects return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectCar/ProjectCar/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectCar/ProjectCar/CollectionGenericObjects/MassiveGenericObjects.cs index 680932e..0898dfa 100644 --- a/ProjectCar/ProjectCar/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectCar/ProjectCar/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectGasMachine.CollectionGenericObjects; + +namespace ProjectGasMachine.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -15,8 +16,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } + set { if (value > 0) @@ -33,6 +39,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// конструктор /// @@ -110,4 +118,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]; + } + } } diff --git a/ProjectCar/ProjectCar/CollectionGenericObjects/StorageCollection.cs b/ProjectCar/ProjectCar/CollectionGenericObjects/StorageCollection.cs index be1729b..4c3ccdc 100644 --- a/ProjectCar/ProjectCar/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectCar/ProjectCar/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,13 @@ -namespace ProjectGasMachine.CollectionGenericObjects; +using ProjectGasMachine.Drawnings; + +namespace ProjectGasMachine.CollectionGenericObjects; /// /// класс-хранилище /// /// public class StorageCollection - where T : class + where T : DrawningMachine { /// /// словарь (хранилище) с коллекциями @@ -17,6 +19,19 @@ public class StorageCollection /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// конструктор /// @@ -80,4 +95,135 @@ public class StorageCollection } } + + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filename)) + { + File.Delete(filename); + } + + using (StreamWriter sw = new StreamWriter(filename)) + { + 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 (StreamReader sr = new(filename)) + { + string line = sr.ReadLine(); + + if (line == null || line.Length == 0) + { + return false; + } + if (!line.Equals(_collectionKey)) + { + //если нет такой записи, то это не те данные + return false; + } + _storages.Clear(); + + while ((line = sr.ReadLine()) != null) + { + string[] record = line.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?.CreateDrawningMachine() is T machine) + { + if (collection.Insert(machine) == -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/ProjectCar/ProjectCar/Drawnings/DrawningGasMachine.cs b/ProjectCar/ProjectCar/Drawnings/DrawningGasMachine.cs index fb23512..6da55c6 100644 --- a/ProjectCar/ProjectCar/Drawnings/DrawningGasMachine.cs +++ b/ProjectCar/ProjectCar/Drawnings/DrawningGasMachine.cs @@ -23,6 +23,15 @@ public class DrawningGasMachine : DrawningMachine EntityGas = new EntityMachine(speed, weight, bodyColor, additionalColor, gas, beacon); } + /// + /// Конструктор для класса Extention + /// + /// + public DrawningGasMachine(EntityGas? gasmachine) : base(gasmachine) + { + EntityGas = gasmachine; + } + public override void DrawTransport(Graphics g) { diff --git a/ProjectCar/ProjectCar/Drawnings/DrawningMachine.cs b/ProjectCar/ProjectCar/Drawnings/DrawningMachine.cs index 58d9812..0144114 100644 --- a/ProjectCar/ProjectCar/Drawnings/DrawningMachine.cs +++ b/ProjectCar/ProjectCar/Drawnings/DrawningMachine.cs @@ -97,6 +97,18 @@ public class DrawningMachine _drawningMachineWidth = drawningMachineWidth; _pictureHeight = drawningMachineHeight; } + + + /// + /// Конструктор для класса Extention + /// + /// + public DrawningMachine(EntityGas? machine) : this() + { + EntityGas = machine; + } + + /// /// Установка границ поля /// diff --git a/ProjectCar/ProjectCar/Drawnings/ExtentionDrawningGas.cs b/ProjectCar/ProjectCar/Drawnings/ExtentionDrawningGas.cs new file mode 100644 index 0000000..5493a5d --- /dev/null +++ b/ProjectCar/ProjectCar/Drawnings/ExtentionDrawningGas.cs @@ -0,0 +1,56 @@ +using ProjectGasMachine.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGasMachine.Drawnings; + +public static class ExtentionDrawningGas +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningMachine? CreateDrawningMachine(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityGas? machine = EntityMachine.CreateEntityMachine(strs); + if (machine != null) + { + return new DrawningGasMachine(machine); + } + + machine = EntityGas.CreateEntityGas(strs); + if (machine != null) + { + return new DrawningMachine(machine); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningMachine drawningMachine) + { + string[]? array = drawningMachine?.EntityGas?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectCar/ProjectCar/Entities/EntityGas.cs b/ProjectCar/ProjectCar/Entities/EntityGas.cs index a111cb9..1c18583 100644 --- a/ProjectCar/ProjectCar/Entities/EntityGas.cs +++ b/ProjectCar/ProjectCar/Entities/EntityGas.cs @@ -51,4 +51,29 @@ public class EntityGas { BodyColor = newColor; } + + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityGas), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityGas? CreateEntityGas(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityGas)) + { + return null; + } + + return new EntityGas(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectCar/ProjectCar/Entities/EntityMachine.cs b/ProjectCar/ProjectCar/Entities/EntityMachine.cs index b325a1e..fe23731 100644 --- a/ProjectCar/ProjectCar/Entities/EntityMachine.cs +++ b/ProjectCar/ProjectCar/Entities/EntityMachine.cs @@ -36,4 +36,34 @@ public class EntityMachine : EntityGas { AdditionalColor = newColor; } + + public override string[] GetStringRepresentation() + { + return new[] + { + nameof(EntityMachine), + Speed.ToString(), + Weight.ToString(), + BodyColor.Name, + AdditionalColor.Name, + Gas.ToString(), + Beacon.ToString(), + }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityMachine? CreateEntityMachine(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityMachine)) + { + return null; + } + + return new EntityMachine(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/ProjectCar/ProjectCar/FormGasMachineCollection.Designer.cs b/ProjectCar/ProjectCar/FormGasMachineCollection.Designer.cs index 7b2348c..c01bcbd 100644 --- a/ProjectCar/ProjectCar/FormGasMachineCollection.Designer.cs +++ b/ProjectCar/ProjectCar/FormGasMachineCollection.Designer.cs @@ -46,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + FileToolStripMenuItem = 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(727, 0); + groupBoxTools.Location = new Point(727, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(196, 543); + groupBoxTools.Size = new Size(196, 519); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -77,13 +84,13 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 323); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(190, 217); + panelCompanyTools.Size = new Size(190, 193); panelCompanyTools.TabIndex = 9; // // buttonAddMachine // buttonAddMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddMachine.Location = new Point(10, 14); + buttonAddMachine.Location = new Point(10, 3); buttonAddMachine.Name = "buttonAddMachine"; buttonAddMachine.Size = new Size(174, 33); buttonAddMachine.TabIndex = 2; @@ -93,7 +100,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(3, 83); + maskedTextBoxPosition.Location = new Point(3, 42); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(184, 23); @@ -103,7 +110,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(10, 185); + buttonRefresh.Location = new Point(10, 152); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(174, 32); buttonRefresh.TabIndex = 7; @@ -114,7 +121,7 @@ // buttonRemoveMachine // buttonRemoveMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveMachine.Location = new Point(10, 112); + buttonRemoveMachine.Location = new Point(10, 71); buttonRemoveMachine.Name = "buttonRemoveMachine"; buttonRemoveMachine.Size = new Size(174, 32); buttonRemoveMachine.TabIndex = 5; @@ -125,7 +132,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(10, 150); + buttonGoToCheck.Location = new Point(10, 109); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(174, 29); buttonGoToCheck.TabIndex = 6; @@ -240,12 +247,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(727, 543); + pictureBox.Size = new Size(727, 519); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(923, 24); + menuStrip.TabIndex = 4; + menuStrip.Text = "menuStrip"; + // + // FileToolStripMenuItem + // + FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + FileToolStripMenuItem.Name = "FileToolStripMenuItem"; + FileToolStripMenuItem.Size = new Size(48, 20); + FileToolStripMenuItem.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"; + // // FormGasMachineCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -253,6 +300,8 @@ ClientSize = new Size(923, 543); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormGasMachineCollection"; Text = "Коллекция газовозов"; groupBoxTools.ResumeLayout(false); @@ -261,7 +310,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -284,5 +336,11 @@ private Button buttonCollectionDel; private ListBox listBoxCollection; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem FileToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; } } \ No newline at end of file diff --git a/ProjectCar/ProjectCar/FormGasMachineCollection.cs b/ProjectCar/ProjectCar/FormGasMachineCollection.cs index 92e0a45..f833233 100644 --- a/ProjectCar/ProjectCar/FormGasMachineCollection.cs +++ b/ProjectCar/ProjectCar/FormGasMachineCollection.cs @@ -67,7 +67,7 @@ namespace ProjectGasMachine /// /// /// - private void ButtonAddMachine_Click(object sender, EventArgs e) + private void ButtonAddMachine_Click(object sender, EventArgs e) { FormGasConfig form = new(); // TODO передать метод + @@ -250,5 +250,46 @@ namespace ProjectGasMachine panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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/ProjectCar/ProjectCar/FormGasMachineCollection.resx b/ProjectCar/ProjectCar/FormGasMachineCollection.resx index af32865..8b1dfa1 100644 --- a/ProjectCar/ProjectCar/FormGasMachineCollection.resx +++ b/ProjectCar/ProjectCar/FormGasMachineCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 261, 17 + \ No newline at end of file