diff --git a/ProjectMonorail/ProjectMonorail/ExtentionDrawingMonorail.cs b/ProjectMonorail/ProjectMonorail/ExtentionDrawingMonorail.cs
new file mode 100644
index 0000000..fca6d16
--- /dev/null
+++ b/ProjectMonorail/ProjectMonorail/ExtentionDrawingMonorail.cs
@@ -0,0 +1,61 @@
+using ProjectMonorail.DrawingObjects;
+using ProjectMonorail.Entities;
+
+namespace ProjectMonorail
+{
+ ///
+ /// Расширение для класса EntityMonorail
+ ///
+ public static class ExtentionDrawingMonorail
+ {
+ ///
+ /// Создание объекта из строки
+ ///
+ /// Строка с данными для создания объекта
+ /// Разделитель даннных
+ /// Ширина
+ /// Высота
+ /// Объект
+ public static DrawingMonorail? CreateDrawingMonorail(this string info, char separatorForObject, int width, int height)
+ {
+ string[] strs = info.Split(separatorForObject);
+ if (strs.Length == 3)
+ {
+ return new DrawingMonorail(Convert.ToInt32(strs[0]),
+ Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
+ }
+ if (strs.Length == 6)
+ {
+ return new DrawingExtendedMonorail(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 DrawingMonorail drawingMonorail, char separatorForObject)
+ {
+ var monorail = drawingMonorail.EntityMonorail;
+ if (monorail == null)
+ {
+ return string.Empty;
+ }
+ var str = $"{monorail.Speed}{separatorForObject}{monorail.Weight}{separatorForObject}{monorail.MainColor.Name}";
+ if (monorail is not EntityExtendedMonorail extendedMonorail)
+ {
+ return str;
+ }
+ return $"{str}{separatorForObject}{extendedMonorail.AdditionalColor.Name}{separatorForObject}{extendedMonorail.MagneticRail}{separatorForObject}{extendedMonorail.ExtraCabin}";
+ }
+ }
+}
\ No newline at end of file
diff --git a/ProjectMonorail/ProjectMonorail/FormMonorailCollection.Designer.cs b/ProjectMonorail/ProjectMonorail/FormMonorailCollection.Designer.cs
index 99b55ed..2016826 100644
--- a/ProjectMonorail/ProjectMonorail/FormMonorailCollection.Designer.cs
+++ b/ProjectMonorail/ProjectMonorail/FormMonorailCollection.Designer.cs
@@ -41,9 +41,16 @@
buttonRemoveMonorail = new Button();
buttonAddMonorail = new Button();
pictureBoxCollection = new PictureBox();
+ menuStripFile = new MenuStrip();
+ fileToolStripMenuItem = new ToolStripMenuItem();
+ saveToolStripMenuItem = new ToolStripMenuItem();
+ loadToolStripMenuItem = new ToolStripMenuItem();
+ openFileDialog = new OpenFileDialog();
+ saveFileDialog = new SaveFileDialog();
panelTools.SuspendLayout();
panelSets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
+ menuStripFile.SuspendLayout();
SuspendLayout();
//
// panelTools
@@ -56,7 +63,7 @@
panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Controls.Add(buttonRemoveMonorail);
panelTools.Controls.Add(buttonAddMonorail);
- panelTools.Location = new Point(788, 10);
+ panelTools.Location = new Point(784, 38);
panelTools.Name = "panelTools";
panelTools.Size = new Size(187, 580);
panelTools.TabIndex = 0;
@@ -196,27 +203,74 @@
//
// pictureBoxCollection
//
- pictureBoxCollection.Location = new Point(12, 10);
+ pictureBoxCollection.Location = new Point(8, 38);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(774, 580);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
+ // menuStripFile
+ //
+ menuStripFile.Dock = DockStyle.None;
+ menuStripFile.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
+ menuStripFile.Location = new Point(0, 4);
+ menuStripFile.Name = "menuStripFile";
+ menuStripFile.Padding = new Padding(3, 2, 0, 2);
+ menuStripFile.Size = new Size(42, 24);
+ menuStripFile.TabIndex = 2;
+ menuStripFile.Text = "menuStrip";
+ //
+ // fileToolStripMenuItem
+ //
+ fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
+ fileToolStripMenuItem.Name = "fileToolStripMenuItem";
+ fileToolStripMenuItem.Size = new Size(37, 20);
+ fileToolStripMenuItem.Text = "File";
+ //
+ // saveToolStripMenuItem
+ //
+ saveToolStripMenuItem.Name = "saveToolStripMenuItem";
+ saveToolStripMenuItem.Size = new Size(100, 22);
+ saveToolStripMenuItem.Text = "Save";
+ saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
+ //
+ // loadToolStripMenuItem
+ //
+ loadToolStripMenuItem.Name = "loadToolStripMenuItem";
+ loadToolStripMenuItem.Size = new Size(100, 22);
+ loadToolStripMenuItem.Text = "Load";
+ loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
+ //
+ // openFileDialog
+ //
+ openFileDialog.FileName = "openFileDialog1";
+ openFileDialog.Filter = "txt file | *.txt";
+ //
+ // saveFileDialog
+ //
+ saveFileDialog.Filter = "txt file | *.txt";
+ //
// FormMonorailCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
- ClientSize = new Size(974, 589);
+ ClientSize = new Size(974, 626);
Controls.Add(pictureBoxCollection);
Controls.Add(panelTools);
+ Controls.Add(menuStripFile);
+ MainMenuStrip = menuStripFile;
Name = "FormMonorailCollection";
+ StartPosition = FormStartPosition.CenterScreen;
Text = "Monorail collection";
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
+ menuStripFile.ResumeLayout(false);
+ menuStripFile.PerformLayout();
ResumeLayout(false);
+ PerformLayout();
}
#endregion
@@ -234,5 +288,11 @@
private Button ButtonDelSet;
private Button buttonAddSet;
private TextBox textBoxNameSet;
+ private MenuStrip menuStripFile;
+ private ToolStripMenuItem fileToolStripMenuItem;
+ private ToolStripMenuItem saveToolStripMenuItem;
+ private ToolStripMenuItem loadToolStripMenuItem;
+ private OpenFileDialog openFileDialog;
+ private SaveFileDialog saveFileDialog;
}
}
\ No newline at end of file
diff --git a/ProjectMonorail/ProjectMonorail/FormMonorailCollection.cs b/ProjectMonorail/ProjectMonorail/FormMonorailCollection.cs
index 67af839..ff9b2b0 100644
--- a/ProjectMonorail/ProjectMonorail/FormMonorailCollection.cs
+++ b/ProjectMonorail/ProjectMonorail/FormMonorailCollection.cs
@@ -1,5 +1,6 @@
using ProjectMonorail.DrawingObjects;
using ProjectMonorail.Generics;
+using System.Windows.Forms;
namespace ProjectMonorail
{
@@ -111,7 +112,7 @@ namespace ProjectMonorail
else
{
MessageBox.Show("Не удалось добавить объект");
- }
+ }
}
///
@@ -186,5 +187,50 @@ namespace ProjectMonorail
pictureBoxCollection.Image = obj.ShowMonorails();
}
+
+ ///
+ /// Обработка нажатия "Сохранение"
+ ///
+ ///
+ ///
+ private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (saveFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ if (_storage.SaveData(saveFileDialog.FileName))
+ {
+ MessageBox.Show("Save was successful",
+ "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ }
+ else
+ {
+ MessageBox.Show("Save failed", "Result",
+ MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+ }
+
+ ///
+ /// Обработка нажатия "Загрузка"
+ ///
+ ///
+ ///
+ private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (openFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ if (_storage.LoadData(openFileDialog.FileName))
+ {
+ MessageBox.Show("Load was successful",
+ "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ ReloadObjects();
+ }
+ else
+ {
+ MessageBox.Show("Load failed", "Result",
+ MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+ }
}
}
diff --git a/ProjectMonorail/ProjectMonorail/FormMonorailCollection.resx b/ProjectMonorail/ProjectMonorail/FormMonorailCollection.resx
index af32865..bbe01e9 100644
--- a/ProjectMonorail/ProjectMonorail/FormMonorailCollection.resx
+++ b/ProjectMonorail/ProjectMonorail/FormMonorailCollection.resx
@@ -117,4 +117,16 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+ 17, 10
+
+
+ 136, 10
+
+
+ 269, 10
+
+
+ 25
+
\ No newline at end of file
diff --git a/ProjectMonorail/ProjectMonorail/FormMonorailConfig.Designer.cs b/ProjectMonorail/ProjectMonorail/FormMonorailConfig.Designer.cs
index cd33f69..cb0754a 100644
--- a/ProjectMonorail/ProjectMonorail/FormMonorailConfig.Designer.cs
+++ b/ProjectMonorail/ProjectMonorail/FormMonorailConfig.Designer.cs
@@ -136,7 +136,7 @@
//
// panelBlue
//
- panelBlue.BackColor = Color.FromArgb(0, 0, 192);
+ panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(114, 16);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(32, 34);
diff --git a/ProjectMonorail/ProjectMonorail/MonorailsGenericCollection.cs b/ProjectMonorail/ProjectMonorail/MonorailsGenericCollection.cs
index 2a43cf7..40b0329 100644
--- a/ProjectMonorail/ProjectMonorail/MonorailsGenericCollection.cs
+++ b/ProjectMonorail/ProjectMonorail/MonorailsGenericCollection.cs
@@ -37,6 +37,11 @@ namespace ProjectMonorail.Generics
///
private readonly SetGeneric _collection;
+ ///
+ /// Получение объектов коллекции
+ ///
+ public IEnumerable GetMonorails => _collection.GetMonorails();
+
///
/// Конструктор
///
diff --git a/ProjectMonorail/ProjectMonorail/MonorailsGenericStorage.cs b/ProjectMonorail/ProjectMonorail/MonorailsGenericStorage.cs
index 39a2de4..f23c149 100644
--- a/ProjectMonorail/ProjectMonorail/MonorailsGenericStorage.cs
+++ b/ProjectMonorail/ProjectMonorail/MonorailsGenericStorage.cs
@@ -1,5 +1,6 @@
using ProjectMonorail.DrawingObjects;
using ProjectMonorail.MovementStrategy;
+using System.Text;
namespace ProjectMonorail.Generics
{
@@ -8,6 +9,21 @@ namespace ProjectMonorail.Generics
///
internal class MonorailsGenericStorage
{
+ ///
+ /// Разделитель для записи ключа и значения элемента словаря
+ ///
+ private static readonly char _separatorForKeyValue = '|';
+
+ ///
+ /// Разделитель для записей коллекции данных в файл
+ ///
+ private readonly char _separatorRecords = ';';
+
+ ///
+ /// Разделитель для записи информации по объекту в файл
+ ///
+ private static readonly char _separatorForObject = ':';
+
///
/// Словарь (хранилище)
///
@@ -74,5 +90,85 @@ namespace ProjectMonorail.Generics
return null;
}
}
+
+ ///
+ /// Сохранение информации по монорельсам в хранилище в файл
+ ///
+ /// Путь и имя файла
+ /// true - сохранение прошло успешно, false - ошибка при сохранении данных
+ public bool SaveData(string filename)
+ {
+ if (File.Exists(filename))
+ {
+ File.Delete(filename);
+ }
+ StringBuilder data = new();
+ foreach (KeyValuePair> record in _monorailsStorages)
+ {
+ StringBuilder records = new();
+ foreach (DrawingMonorail? elem in record.Value.GetMonorails)
+ {
+ records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
+ }
+ data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
+ }
+ if (data.Length == 0)
+ {
+ return false;
+ }
+ using StreamWriter sw = new(filename);
+ sw.Write($"MonorailStorage{Environment.NewLine}{data}");
+ return true;
+ }
+
+ ///
+ /// Загрузка информации по монорельсам в хранилище из файла
+ ///
+ /// Путь и имя файла
+ /// true - загрузка прошла успешно, false - ошибка при загрузке данных
+ public bool LoadData(string filename)
+ {
+ if (!File.Exists(filename))
+ {
+ return false;
+ }
+ using (StreamReader sr = new(filename))
+ {
+ string str = sr.ReadLine();
+ if (str == null || str.Length == 0)
+ {
+ return false;
+ }
+ if (!str.StartsWith("MonorailStorage"))
+ {
+ //если нет такой записи, то это не те данные
+ return false;
+ }
+ _monorailsStorages.Clear();
+ while ((str = sr.ReadLine()) != null)
+ {
+ string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
+ if (record.Length != 2)
+ {
+ continue;
+ }
+ MonorailsGenericCollection collection = new(_pictureWidth, _pictureHeight);
+ string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
+ foreach (string elem in set.Reverse())
+ {
+ DrawingMonorail? monorail = elem?.CreateDrawingMonorail(_separatorForObject, _pictureWidth, _pictureHeight);
+ if (monorail != null)
+ {
+ if (collection + monorail == -1)
+ {
+ return false;
+ }
+ }
+ }
+ _monorailsStorages.Add(record[0], collection);
+ }
+ }
+ return true;
+ }
}
}
diff --git a/ProjectMonorail/ProjectMonorail/SetGeneric.cs b/ProjectMonorail/ProjectMonorail/SetGeneric.cs
index 418e6be..bab1cd7 100644
--- a/ProjectMonorail/ProjectMonorail/SetGeneric.cs
+++ b/ProjectMonorail/ProjectMonorail/SetGeneric.cs
@@ -95,12 +95,12 @@
/// Проход по списку
///
///
- public IEnumerable GetMonorails(int? maxCars = null)
+ public IEnumerable GetMonorails(int? maxMonorails = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
- if (maxCars.HasValue && i == maxCars.Value)
+ if (maxMonorails.HasValue && i == maxMonorails.Value)
{
yield break;
}