diff --git a/ElectricLocomotive/ElectricLocomotive/ExtentionLocomotive.cs b/ElectricLocomotive/ElectricLocomotive/ExtentionLocomotive.cs
new file mode 100644
index 0000000..b426397
--- /dev/null
+++ b/ElectricLocomotive/ElectricLocomotive/ExtentionLocomotive.cs
@@ -0,0 +1,66 @@
+using ElectricLocomotive;
+using ElectricLocomotive.DrawningObject;
+using ElectricLocomotive.Entities;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectElectricLocomotive.DrawingObjects
+{
+ public static class ExtentionLocomotive
+ {
+ ///
+ /// Создание объекта из строки
+ ///
+ /// Строка с данными для создания объекта
+ /// Разделитель даннных
+ /// Ширина
+ /// Высота
+ /// Объект
+ 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 drawningCar, char separatorForObject)
+ {
+ var loco = drawningCar.EntityLocomotive;
+ if (loco == null)
+ {
+ return string.Empty;
+ }
+ var str =
+ $"{loco.Speed}{separatorForObject}{loco.Weight}{separatorForObject}{loco.BodyColor.Name}";
+ if (loco is not EntityElectroLocomotive electricLocomotive)
+ {
+ return str;
+ }
+ return
+ $"{str}{separatorForObject}{electricLocomotive.AdditionalColor.Name}{separatorForObject}{electricLocomotive.Horns_1}{separatorForObject}{electricLocomotive.Horns_2}";
+ }
+ }
+}
diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.Designer.cs b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.Designer.cs
index 64686c6..37297ef 100644
--- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.Designer.cs
+++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.Designer.cs
@@ -28,6 +28,7 @@
///
private void InitializeComponent()
{
+ System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormLocomotiveCollection));
CollectionPictureBox = new PictureBox();
ToolsBox = new GroupBox();
NaborGroupBox = new GroupBox();
@@ -39,16 +40,23 @@
RefreshCollection = new Button();
DelLocomotive = new Button();
AddLocomotive = new Button();
+ menuStrip = new MenuStrip();
+ файлToolStripMenuItem = new ToolStripMenuItem();
+ LoadToolStripMenuItem = new ToolStripMenuItem();
+ SaveToolStripMenuItem = new ToolStripMenuItem();
+ saveFileDialog = new SaveFileDialog();
+ openFileDialog = new OpenFileDialog();
((System.ComponentModel.ISupportInitialize)CollectionPictureBox).BeginInit();
ToolsBox.SuspendLayout();
NaborGroupBox.SuspendLayout();
+ menuStrip.SuspendLayout();
SuspendLayout();
//
// CollectionPictureBox
//
- CollectionPictureBox.Location = new Point(3, 0);
+ CollectionPictureBox.Location = new Point(3, 34);
CollectionPictureBox.Name = "CollectionPictureBox";
- CollectionPictureBox.Size = new Size(696, 554);
+ CollectionPictureBox.Size = new Size(696, 496);
CollectionPictureBox.TabIndex = 0;
CollectionPictureBox.TabStop = false;
//
@@ -59,9 +67,9 @@
ToolsBox.Controls.Add(RefreshCollection);
ToolsBox.Controls.Add(DelLocomotive);
ToolsBox.Controls.Add(AddLocomotive);
- ToolsBox.Location = new Point(705, 12);
+ ToolsBox.Location = new Point(705, 34);
ToolsBox.Name = "ToolsBox";
- ToolsBox.Size = new Size(200, 542);
+ ToolsBox.Size = new Size(200, 496);
ToolsBox.TabIndex = 1;
ToolsBox.TabStop = false;
ToolsBox.Text = "Инструменты";
@@ -74,14 +82,14 @@
NaborGroupBox.Controls.Add(textBoxStorageName);
NaborGroupBox.Location = new Point(7, 22);
NaborGroupBox.Name = "NaborGroupBox";
- NaborGroupBox.Size = new Size(185, 329);
+ NaborGroupBox.Size = new Size(185, 280);
NaborGroupBox.TabIndex = 4;
NaborGroupBox.TabStop = false;
NaborGroupBox.Text = "Наборы";
//
// ButtomRemoveNabor
//
- ButtomRemoveNabor.Location = new Point(6, 275);
+ ButtomRemoveNabor.Location = new Point(6, 221);
ButtomRemoveNabor.Name = "ButtomRemoveNabor";
ButtomRemoveNabor.Size = new Size(173, 48);
ButtomRemoveNabor.TabIndex = 3;
@@ -95,7 +103,7 @@
listBoxStorage.ItemHeight = 15;
listBoxStorage.Location = new Point(6, 112);
listBoxStorage.Name = "listBoxStorage";
- listBoxStorage.Size = new Size(173, 139);
+ listBoxStorage.Size = new Size(173, 94);
listBoxStorage.TabIndex = 2;
listBoxStorage.SelectedIndexChanged += listBoxStorage_SelectedIndexChanged;
//
@@ -118,14 +126,14 @@
//
// Input
//
- Input.Location = new Point(6, 409);
+ Input.Location = new Point(7, 360);
Input.Name = "Input";
Input.Size = new Size(186, 23);
Input.TabIndex = 3;
//
// RefreshCollection
//
- RefreshCollection.Location = new Point(7, 490);
+ RefreshCollection.Location = new Point(7, 441);
RefreshCollection.Name = "RefreshCollection";
RefreshCollection.Size = new Size(187, 46);
RefreshCollection.TabIndex = 2;
@@ -135,7 +143,7 @@
//
// DelLocomotive
//
- DelLocomotive.Location = new Point(6, 438);
+ DelLocomotive.Location = new Point(7, 389);
DelLocomotive.Name = "DelLocomotive";
DelLocomotive.Size = new Size(187, 46);
DelLocomotive.TabIndex = 1;
@@ -145,7 +153,7 @@
//
// AddLocomotive
//
- AddLocomotive.Location = new Point(5, 357);
+ AddLocomotive.Location = new Point(7, 308);
AddLocomotive.Name = "AddLocomotive";
AddLocomotive.Size = new Size(187, 46);
AddLocomotive.TabIndex = 0;
@@ -153,21 +161,69 @@
AddLocomotive.UseVisualStyleBackColor = true;
AddLocomotive.Click += ButtonAddLocomotive_Click;
//
+ // menuStrip
+ //
+ menuStrip.BackColor = SystemColors.ButtonFace;
+ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
+ menuStrip.Location = new Point(0, 0);
+ menuStrip.Name = "menuStrip";
+ menuStrip.Size = new Size(914, 24);
+ menuStrip.TabIndex = 3;
+ menuStrip.Text = "menuStrip1";
+ //
+ // файлToolStripMenuItem
+ //
+ файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { LoadToolStripMenuItem, SaveToolStripMenuItem });
+ файлToolStripMenuItem.Name = "файлToolStripMenuItem";
+ файлToolStripMenuItem.Size = new Size(48, 20);
+ файлToolStripMenuItem.Text = "&Файл";
+ //
+ // LoadToolStripMenuItem
+ //
+ LoadToolStripMenuItem.Image = (Image)resources.GetObject("LoadToolStripMenuItem.Image");
+ LoadToolStripMenuItem.ImageTransparentColor = Color.Magenta;
+ LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
+ LoadToolStripMenuItem.Size = new Size(141, 22);
+ LoadToolStripMenuItem.Text = "Загрузка";
+ LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
+ //
+ // SaveToolStripMenuItem
+ //
+ SaveToolStripMenuItem.Image = (Image)resources.GetObject("SaveToolStripMenuItem.Image");
+ SaveToolStripMenuItem.ImageTransparentColor = Color.Magenta;
+ SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
+ SaveToolStripMenuItem.Size = new Size(141, 22);
+ SaveToolStripMenuItem.Text = "Сохранение";
+ SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
+ //
+ // saveFileDialog
+ //
+ saveFileDialog.Filter = "txt file | *.txt";
+ //
+ // openFileDialog
+ //
+ openFileDialog.FileName = "openFileDialog1";
+ //
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
- ClientSize = new Size(917, 566);
+ ClientSize = new Size(914, 537);
+ Controls.Add(menuStrip);
Controls.Add(ToolsBox);
Controls.Add(CollectionPictureBox);
Name = "FormLocomotiveCollection";
Text = "Коллекция";
+ MainMenuStrip = menuStrip;
((System.ComponentModel.ISupportInitialize)CollectionPictureBox).EndInit();
ToolsBox.ResumeLayout(false);
ToolsBox.PerformLayout();
NaborGroupBox.ResumeLayout(false);
NaborGroupBox.PerformLayout();
+ menuStrip.ResumeLayout(false);
+ menuStrip.PerformLayout();
ResumeLayout(false);
+ PerformLayout();
}
#endregion
@@ -183,5 +239,12 @@
private TextBox textBoxStorageName;
private Button ButtomRemoveNabor;
private ListBox listBoxStorage;
+ private MenuStrip menuStrip;
+ private SaveFileDialog saveFileDialog;
+ private OpenFileDialog openFileDialog;
+ private ToolStripMenuItem файлToolStripMenuItem;
+ private ToolStripMenuItem LoadToolStripMenuItem;
+ private ToolStripMenuItem SaveToolStripMenuItem;
+ private GroupBox groupBoxMenu;
}
}
\ No newline at end of file
diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs
index f2ccf7b..f0ac0b1 100644
--- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs
+++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs
@@ -140,5 +140,48 @@ namespace ElectricLocomotive
}
CollectionPictureBox.Image = obj.ShowLocomotives();
}
+
+ ///
+ /// Обработка нажатия "Сохранение"
+ ///
+ ///
+ ///
+ private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (saveFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ if (_storage.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 (_storage.LoadData(openFileDialog.FileName))
+ {
+ MessageBox.Show("Загрузка завершена!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ ReloadObjects();
+ }
+ else
+ {
+ MessageBox.Show("Ошибка загрузки!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
+
+ }
+ }
+ }
}
}
\ No newline at end of file
diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.resx b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.resx
index af32865..974a777 100644
--- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.resx
+++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.resx
@@ -117,4 +117,28 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+ 19, 13
+
+
+
+
+ iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
+ YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAFUSURBVDhPlZK9SgNBFIXnCcQnkLyA4CPkHayFdBY22mqj
+ paVlxCKCoBaClUQLESNRC4OE4EKQrAbcYBKy62Z/ynHOzUwcMzuyDhzYGc795tw7y2ZXFEVLSZI8p2la
+ kkf5lywO1vZr/MH54LkhwlgQKsZxvC4AfHHjjM+tHOaDiKIKiqDqk0s6rbUJoCDCsy3t5kJh+bJFZrZ8
+ YGhh9ZjgSIeUUgVZPgHot2HfGwbTNu4aTf75UuW+50wVhSMAKwRwugO6aevokYohfQbDzj1/vdj8pffb
+ PfJREpUAEPSOvXoFBdSFBIDgmxIgTr3lEkRPYZMOwDwYDtzrXToATPVp06B9QwB8o4YAipjVr02dqx0T
+ gOHMGm3qNc8nL6EAX33XMP2l8cj7mQEOvMaJYbKpWy/zMAzf6BVE9ADF6CnLnCXMCn8mAUSMEiCYwX/k
+ +/48Y4x9AwxhsnXBwZZBAAAAAElFTkSuQmCC
+
+
+
+
+ iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
+ YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABzSURBVDhPY/j69WvDt2/f/pODQXoZQIyYCfv+MwTPIQmD
+ 9ID0gg3ApoAYjGHAh/cficLD2QBS8SA1AJufkTGyWtoagM5HFwdhmAEfkPMCukJkzcjiIAw24MuXLwbI
+ hqArRNaMLA7CYANAAGYISIA0/O0/AID67ECmnhNDAAAAAElFTkSuQmCC
+
+
\ No newline at end of file
diff --git a/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs b/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs
index 18614ed..8838fb6 100644
--- a/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs
+++ b/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs
@@ -1,4 +1,5 @@
using ElectricLocomotive.DrawningObject;
+using ProjectElectricLocomotive.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -18,10 +19,22 @@ namespace ElectricLocomotive.Generics
/// Возвращение списка названий наборов
///
public List Keys => _locomotivesStorage.Keys.ToList();
+ ///
+ /// Разделитель для записи ключа и значения элемента словаря
+ ///
+ private static readonly char _separatorForKeyValue = '|';
+ ///
+ /// Разделитель для записей коллекции данных в файл
+ ///
+ private readonly char _separatorRecords = ';';
+ ///
+ /// Разделитель для записи информации по объекту в файл
+ ///
+ private static readonly char _separatorForObject = ':';
+
-
private readonly int _pictureWidth;
-
+
private readonly int _pictureHeight;
///
@@ -78,5 +91,101 @@ namespace ElectricLocomotive.Generics
return null;
}
}
+
+ ///
+ /// Сохранение информации по автомобилям в хранилище в файл
+ ///
+ /// Путь и имя файла
+ /// true - сохранение прошло успешно, false - ошибка при сохранении данных
+ public bool SaveData(string filename)
+ {
+ if (File.Exists(filename))
+ {
+ File.Delete(filename);
+ }
+ StringBuilder data = new();
+ foreach (KeyValuePair> record in _locomotivesStorage)
+ {
+ StringBuilder records = new();
+ foreach (DrawningLocomotive? elem in record.Value.GetLocomotives)
+ {
+ records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
+ }
+ data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
+ }
+ if (data.Length == 0)
+ {
+ return false;
+ }
+ using StreamWriter fs = new StreamWriter(filename);
+ {
+ fs.WriteLine($"LocomotiveStorage{Environment.NewLine}");
+ fs.WriteLine(data);
+ }
+ return true;
+ }
+ ///
+ /// Загрузка информации по автомобилям в хранилище из файла
+ ///
+ /// Путь и имя файла
+ /// true - загрузка прошла успешно, false - ошибка при загрузке данных
+ public bool LoadData(string filename)
+ {
+ if (!File.Exists(filename))
+ {
+ return false;
+ }
+
+ using (StreamReader fs = File.OpenText(filename))
+ {
+
+ string str = fs.ReadLine();
+
+ if (str == null || str.Length == 0)
+ {
+ return false;
+ }
+
+ if (!str.StartsWith("LocomotiveStorage"))
+ {
+ //если нет такой записи, то это не те данные
+ return false;
+ }
+
+ _locomotivesStorage.Clear();
+ string strs = "";
+
+
+ while ((strs = fs.ReadLine()) != null)
+ {
+
+ if (strs == null)
+ {
+ return false;
+ }
+
+ string[] record = strs.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? loco = elem?.CreateDrawningLocomotive(_separatorForObject, _pictureWidth, _pictureHeight);
+ if (loco != null)
+ {
+ if ((collection + loco) == -1)
+ {
+ return false;
+ }
+ }
+ }
+ _locomotivesStorage.Add(record[0], collection);
+ }
+ return true;
+ }
+ }
}
}
diff --git a/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs b/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs
index dd3ad2d..5b95146 100644
--- a/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs
+++ b/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs
@@ -88,5 +88,9 @@ namespace ElectricLocomotive.Generics
}
}
}
+ ///
+ /// Получение объектов коллекции
+ ///
+ public IEnumerable GetLocomotives => _collection.GetLocomotives();
}
}