diff --git a/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs b/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs new file mode 100644 index 0000000..112673f --- /dev/null +++ b/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs @@ -0,0 +1,72 @@ +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.DrawningObjects +{ + /// + /// Расширение для класса EntityCar + /// + public static class ExtentionDrawningLocomotive + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель даннных + /// Ширина + /// Высота + /// Объект + public static DrawningLocomotive? CreateDrawningLocomotive(this string info, char separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3 ) { + return new DrawningLocomotive( + Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), + Color.FromName(strs[2]), + width, height); + } + if (strs.Length == 6) { + return new DrawningElectricLocomotive( + Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), + Color.FromName(strs[2]), + Color.FromName(strs[3]), + Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5]), + width, height); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Разделитель даннных + /// + public static string GetDataForSave(this DrawningLocomotive drawningLocomotive, char separatorForObject) + { + var locomotive = drawningLocomotive.EntityLocomotive; + if (locomotive == null) + { + return string.Empty; + } + var str = + $"{locomotive.Speed}{separatorForObject}" + + $"{locomotive.Weight}{separatorForObject}" + + $"{locomotive.BodyColor.Name}"; + if (locomotive is not EntityElectricLocomotive electricLocomotive) + { + return str; + } + return $"{str}{separatorForObject}" + + $"{electricLocomotive.AdditionalColor}{separatorForObject}" + + $"{electricLocomotive.Horns}{separatorForObject}" + + $"{electricLocomotive.Battery}"; + } + } +} diff --git a/ElectricLocomotive/FormLocomotiveCollection.Designer.cs b/ElectricLocomotive/FormLocomotiveCollection.Designer.cs index a8bdfd8..bd9649b 100644 --- a/ElectricLocomotive/FormLocomotiveCollection.Designer.cs +++ b/ElectricLocomotive/FormLocomotiveCollection.Designer.cs @@ -40,10 +40,15 @@ buttonRefreshCollection = new Button(); buttonRemoveLocomotive = new Button(); buttonAddLocomotive = new Button(); + menuStrip1 = new MenuStrip(); + fileToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); groupBox1.SuspendLayout(); groupBox2.SuspendLayout(); + menuStrip1.SuspendLayout(); SuspendLayout(); // // tableLayoutPanel1 @@ -55,11 +60,11 @@ tableLayoutPanel1.Controls.Add(pictureBoxCollection, 0, 0); tableLayoutPanel1.Controls.Add(groupBox1, 1, 0); tableLayoutPanel1.Dock = DockStyle.Fill; - tableLayoutPanel1.Location = new Point(0, 0); + tableLayoutPanel1.Location = new Point(0, 28); tableLayoutPanel1.Name = "tableLayoutPanel1"; tableLayoutPanel1.RowCount = 1; tableLayoutPanel1.RowStyles.Add(new RowStyle()); - tableLayoutPanel1.Size = new Size(885, 449); + tableLayoutPanel1.Size = new Size(885, 453); tableLayoutPanel1.TabIndex = 0; // // pictureBoxCollection @@ -68,7 +73,7 @@ pictureBoxCollection.Location = new Point(3, 3); pictureBoxCollection.MinimumSize = new Size(100, 100); pictureBoxCollection.Name = "pictureBoxCollection"; - pictureBoxCollection.Size = new Size(673, 444); + pictureBoxCollection.Size = new Size(673, 447); pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabStop = false; // @@ -178,12 +183,45 @@ buttonAddLocomotive.UseVisualStyleBackColor = true; buttonAddLocomotive.Click += buttonAddLocomotive_Click; // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(885, 28); + menuStrip1.TabIndex = 1; + menuStrip1.Text = "menuStrip1"; + // + // fileToolStripMenuItem + // + fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + fileToolStripMenuItem.Size = new Size(59, 24); + fileToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.Size = new Size(224, 26); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.Size = new Size(224, 26); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // // FormLocomotiveCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(885, 449); + ClientSize = new Size(885, 481); Controls.Add(tableLayoutPanel1); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; MinimumSize = new Size(700, 400); Name = "FormLocomotiveCollection"; Text = "FormLocomotiveCollection"; @@ -193,6 +231,8 @@ groupBox1.PerformLayout(); groupBox2.ResumeLayout(false); groupBox2.PerformLayout(); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); ResumeLayout(false); PerformLayout(); } @@ -211,5 +251,9 @@ private Button buttonAddObject; private ListBox listBoxStorages; private Button buttonDelObject; + private MenuStrip menuStrip1; + private ToolStripMenuItem fileToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; } } \ No newline at end of file diff --git a/ElectricLocomotive/FormLocomotiveCollection.cs b/ElectricLocomotive/FormLocomotiveCollection.cs index 5b3fab0..1b8a281 100644 --- a/ElectricLocomotive/FormLocomotiveCollection.cs +++ b/ElectricLocomotive/FormLocomotiveCollection.cs @@ -40,5 +40,15 @@ namespace ProjectElectricLocomotive { ListBoxObjects_SelectedIndexChanged(sender, e); } + + private void saveToolStripMenuItem_Click(object sender, EventArgs e) + { + SaveToolStripMenuItem_Click(sender, e); + } + + private void loadToolStripMenuItem_Click(object sender, EventArgs e) + { + LoadToolStripMenuItem_Click(sender, e); + } } } diff --git a/ElectricLocomotive/FormLocomotiveCollection.resx b/ElectricLocomotive/FormLocomotiveCollection.resx index af32865..a0623c8 100644 --- a/ElectricLocomotive/FormLocomotiveCollection.resx +++ b/ElectricLocomotive/FormLocomotiveCollection.resx @@ -117,4 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + \ No newline at end of file diff --git a/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs b/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs index a77769e..43335fa 100644 --- a/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs +++ b/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs @@ -146,5 +146,9 @@ namespace ProjectElectricLocomotive.Generics } } } + /// + /// Получение объектов коллекции + /// + public IEnumerable GetCars => _collection.GetLocomotives(); } } \ No newline at end of file diff --git a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs index e7b044b..b10a6c2 100644 --- a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs +++ b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs @@ -35,6 +35,19 @@ namespace ProjectElectricLocomotive.Generics /// private readonly int _pictureHeight; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// /// Конструктор /// @@ -92,5 +105,94 @@ namespace ProjectElectricLocomotive.Generics return null; } } + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + + StringBuilder data = new(); + using (StreamWriter sw = new StreamWriter(filename)) + { + sw.WriteLine("LocomotiveStorage"); + if (_locomotiveStorage.Count == 0) + { + return false; + } + foreach ( + KeyValuePair> + record in _locomotiveStorage) + { + sw.Write(record.Key); + sw.Write(_separatorForKeyValue); + foreach (DrawningLocomotive? elem in record.Value.GetCars) + { + sw.Write( + $"{elem?.GetDataForSave(_separatorForObject)}" + + $"{_separatorRecords}"); + } + sw.WriteLine(); + } + return true; + } + } + /// + /// Загрузка информации по Локомативам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка призагрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + string bufferTextFromFile = ""; + using (StreamReader sr = new(filename)) + { + string line; + if (!((line = sr.ReadLine() != null) && line.StartsWith("LocomotiveStorage"))) + { + //если нет такой записи, то это не те данные + return false; + } + _locomotiveStorage.Clear(); + while ((line = sr.ReadLine()) != null) + { + string[] record = line.Split( + _separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + LocomotivesGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningLocomotive? locomotive = + elem?.CreateDrawningLocomotive( + _separatorForObject, + _pictureWidth, _pictureHeight); + if (locomotive != null) + { + if ((collection + locomotive) == 0) + { + return false; + } + } + } + _locomotiveStorage.Add(record[0], collection); + } + return true; + } + } } } diff --git a/ElectricLocomotive/LogicFormLocomotiveCollection.cs b/ElectricLocomotive/LogicFormLocomotiveCollection.cs index 524dabb..1acefcd 100644 --- a/ElectricLocomotive/LogicFormLocomotiveCollection.cs +++ b/ElectricLocomotive/LogicFormLocomotiveCollection.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Windows.Forms; using ProjectElectricLocomotive.DrawningObjects; using ProjectElectricLocomotive.Generics; using ProjectElectricLocomotive.MovementStrategy; @@ -124,7 +125,7 @@ namespace ProjectElectricLocomotive if (obj + SelectedLocomotive > 0) { MessageBox.Show("Объект добавлен"); - + pictureBoxCollection.Image = obj.ShowLocomotives(); } else @@ -159,7 +160,8 @@ namespace ProjectElectricLocomotive try { pos = Convert.ToInt32(maskedTextBoxNumber.Text); - } catch(System.FormatException ex) + } + catch (System.FormatException ex) { pos = 0; } @@ -191,5 +193,50 @@ namespace ProjectElectricLocomotive } pictureBoxCollection.Image = obj.ShowLocomotives(); } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + SaveFileDialog saveFileDialog = new SaveFileDialog(); + saveFileDialog.Filter = "txt file | *.txt"; + saveFileDialog.Title = "Сохранение"; + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show("Сохранение прошло успешно", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadToolStripMenuItem_Click(object sendee, EventArgs e) + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Filter = "txt file | *.txt"; + openFileDialog.Title = "Загрузка"; + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + ReloadObjects(); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/ElectricLocomotive/LogicFormLocomotiveConfig.cs b/ElectricLocomotive/LogicFormLocomotiveConfig.cs index a62e59e..38942c2 100644 --- a/ElectricLocomotive/LogicFormLocomotiveConfig.cs +++ b/ElectricLocomotive/LogicFormLocomotiveConfig.cs @@ -16,6 +16,8 @@ namespace ProjectElectricLocomotive /// DrawningLocomotive? _locomotive = null; + public delegate Object Func(); + /// /// Событие ///