diff --git a/Trolleybus/Trolleybus/BusesGenericCollection.cs b/Trolleybus/Trolleybus/BusesGenericCollection.cs
index c04d7dc..ff8b62d 100644
--- a/Trolleybus/Trolleybus/BusesGenericCollection.cs
+++ b/Trolleybus/Trolleybus/BusesGenericCollection.cs
@@ -150,5 +150,9 @@ namespace Trolleybus.Generics
}
}
}
+ ///
+ /// Получение объектов коллекции
+ ///
+ public IEnumerable GetBuses => _collection.GetBuses();
}
}
diff --git a/Trolleybus/Trolleybus/BusesGenericStorage.cs b/Trolleybus/Trolleybus/BusesGenericStorage.cs
index 6e4f877..f837e84 100644
--- a/Trolleybus/Trolleybus/BusesGenericStorage.cs
+++ b/Trolleybus/Trolleybus/BusesGenericStorage.cs
@@ -31,6 +31,19 @@ namespace Trolleybus.Generics
///
private readonly int _pictureHeight;
+ ///
+ /// Разделитель для записи ключа и значения элемента словаря
+ ///
+ private static readonly char _separatorForKeyValue = '|';
+ ///
+ /// Разделитель для записей коллекции данных в файл
+ ///
+ private readonly char _separatorRecords = ';';
+ ///
+ /// Разделитель для записи информации по объекту в файл
+ ///
+ private static readonly char _separatorForObject = ':';
+
///
/// Конструктор
///
@@ -85,5 +98,80 @@ namespace Trolleybus.Generics
return _busStorages[ind];
}
}
+ ///
+ /// Сохранение информации по автобусам из хранилища в файл
+ ///
+ /// Путь и имя файла
+ /// true - сохранение прошло успешно, false - ошибка при сохранении данных
+ public bool SaveData(string filename)
+ {
+ if (File.Exists(filename))
+ {
+ File.Delete(filename);
+ }
+
+ StringBuilder data = new();
+ foreach (KeyValuePair> record in _busStorages)
+ {
+ StringBuilder records = new();
+ foreach (DrawingBus? elem in record.Value.GetBuses)
+ {
+ records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
+ }
+ data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
+ }
+ if (data.Length == 0)
+ {
+ return false;
+ }
+ using StreamWriter sw = new StreamWriter(filename, false);
+ sw.WriteLine($"BusesStorage");
+ sw.WriteLine(data);
+ return true;
+ }
+ ///
+ /// Загрузка информации по автобусам из файла в хранилище
+ ///
+ /// Путь и имя файла
+ /// true - загрузка прошла успешно, false - ошибка при загрузке данных
+ public bool LoadData(string filename)
+ {
+ if (!File.Exists(filename))
+ {
+ return false;
+ }
+ using(StreamReader sr = File.OpenText(filename))
+ {
+ String currentLine = sr.ReadLine();
+ // Если первая строка пустая или в файле не те данные
+ if (currentLine == null || !currentLine.Contains("BusesStorage"))
+ {
+ return false;
+ }
+ // Очистка хранилища
+ _busStorages.Clear();
+ currentLine = sr.ReadLine();
+ while (currentLine != "" && currentLine != null)
+ {
+ string[] record = currentLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
+ BusesGenericCollection collection = new(_pictureWidth, _pictureHeight);
+ string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
+ foreach (string elem in set)
+ {
+ DrawingBus? bus = elem?.CreateDrawingBus(_separatorForObject, _pictureWidth, _pictureHeight);
+ if (bus != null)
+ {
+ if ((collection + bus) == -1)
+ {
+ return false;
+ }
+ }
+ }
+ _busStorages.Add(record[0], collection);
+ currentLine = sr.ReadLine();
+ }
+ }
+ return true;
+ }
}
}
diff --git a/Trolleybus/Trolleybus/ExtensionDrawingBus.cs b/Trolleybus/Trolleybus/ExtensionDrawingBus.cs
new file mode 100644
index 0000000..74e763c
--- /dev/null
+++ b/Trolleybus/Trolleybus/ExtensionDrawingBus.cs
@@ -0,0 +1,68 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+using Trolleybus.Entities;
+using Trolleybus.DrawingObjects;
+using System.Configuration;
+
+namespace Trolleybus
+{
+ public static class ExtensionDrawingBus
+ {
+ ///
+ /// Создание объекта из строки
+ ///
+ /// Строка с данными для создания объекта
+ /// Разделитель даннных
+ /// Ширина
+ /// Высота
+ /// Объект
+ public static DrawingBus? CreateDrawingBus(this string info, char separatorForObject, int width, int height)
+ {
+ string[] strs = info.Split(separatorForObject);
+ if (strs.Length == 3)
+ {
+ return new DrawingBus(Convert.ToInt32(strs[0]),
+ Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
+ }
+ if (strs.Length == 6)
+ {
+ return new DrawingTrolleybus(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 DrawingBus drawingBus, char separatorForObject)
+ {
+ var bus = drawingBus.EntityBus;
+ if (bus == null)
+ {
+ return string.Empty;
+ }
+ var str = $"{bus.Speed}{separatorForObject}{bus.Weight}{separatorForObject}{bus.BodyColor.Name}";
+ //Если это автобус (т.е. не троллейбус), то строки из 3 свойств достаточно
+ if (bus is not EntityTrolleybus trolleyBus)
+ {
+ return str;
+ }
+ //Если это троллейбус, то дополнение строки из 3 свойств доп. свойствами
+ return $"{str}{separatorForObject}{trolleyBus.AdditionalColor.Name}{separatorForObject}{trolleyBus.Horns}{separatorForObject}{trolleyBus.Batteries}";
+ }
+ }
+}
+
diff --git a/Trolleybus/Trolleybus/FormBusConfig.Designer.cs b/Trolleybus/Trolleybus/FormBusConfig.Designer.cs
index 058751d..eac14ab 100644
--- a/Trolleybus/Trolleybus/FormBusConfig.Designer.cs
+++ b/Trolleybus/Trolleybus/FormBusConfig.Designer.cs
@@ -119,7 +119,7 @@
//
// panelLightBlue
//
- panelLightBlue.BackColor = Color.FromArgb(128, 255, 255);
+ panelLightBlue.BackColor = Color.Aqua;
panelLightBlue.Location = new Point(5, 85);
panelLightBlue.Name = "panelLightBlue";
panelLightBlue.Size = new Size(50, 40);
@@ -127,7 +127,7 @@
//
// panelBlue
//
- panelBlue.BackColor = Color.FromArgb(0, 0, 192);
+ panelBlue.BackColor = Color.DarkBlue;
panelBlue.Location = new Point(75, 85);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(50, 40);
@@ -151,7 +151,7 @@
//
// panelGreen
//
- panelGreen.BackColor = Color.FromArgb(0, 192, 0);
+ panelGreen.BackColor = Color.DarkGreen;
panelGreen.Location = new Point(215, 25);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(50, 40);
@@ -167,7 +167,7 @@
//
// panelOrange
//
- panelOrange.BackColor = Color.FromArgb(255, 128, 0);
+ panelOrange.BackColor = Color.DarkOrange;
panelOrange.Location = new Point(75, 25);
panelOrange.Name = "panelOrange";
panelOrange.Size = new Size(50, 40);
diff --git a/Trolleybus/Trolleybus/FormBusesCollection.cs b/Trolleybus/Trolleybus/FormBusesCollection.cs
index c4fde4f..b71fe5f 100644
--- a/Trolleybus/Trolleybus/FormBusesCollection.cs
+++ b/Trolleybus/Trolleybus/FormBusesCollection.cs
@@ -99,7 +99,7 @@ namespace Trolleybus
private void ButtonAddBus_Click(object sender, EventArgs e)
{
var formBusConfig = new FormBusConfig();
- formBusConfig.AddEvent(AddBus);
+ formBusConfig.AddEvent(AddBus);
formBusConfig.Show();
}
private void AddBus(DrawingBus selectedBus)
@@ -180,6 +180,45 @@ namespace Trolleybus
}
pictureBoxCollection.Image = obj.ShowBuses();
}
+ ///
+ /// Обработка нажатия "Сохранение"
+ ///
+ ///
+ ///
+ 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 DownloadToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (openFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ if (_storage.LoadData(openFileDialog.FileName))
+ {
+ ReloadObjects();
+ MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ }
+ else
+ {
+ MessageBox.Show("Не удалось загрузить данные", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+ }
private void InitializeComponent()
{
@@ -194,17 +233,24 @@ namespace Trolleybus
maskedTextBoxNumber = new MaskedTextBox();
buttonRemoveBus = new Button();
buttonAddBus = new Button();
+ menuStrip = new MenuStrip();
+ fileToolStripMenuItem = new ToolStripMenuItem();
+ saveToolStripMenuItem = new ToolStripMenuItem();
+ downloadToolStripMenuItem = new ToolStripMenuItem();
+ openFileDialog = new OpenFileDialog();
+ saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
panelSets.SuspendLayout();
+ menuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
- pictureBoxCollection.Location = new Point(0, 0);
+ pictureBoxCollection.Location = new Point(0, 36);
pictureBoxCollection.Name = "pictureBoxCollection";
- pictureBoxCollection.Size = new Size(670, 553);
+ pictureBoxCollection.Size = new Size(670, 517);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
@@ -217,9 +263,9 @@ namespace Trolleybus
panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Controls.Add(buttonRemoveBus);
panelTools.Controls.Add(buttonAddBus);
- panelTools.Location = new Point(682, 0);
+ panelTools.Location = new Point(676, 36);
panelTools.Name = "panelTools";
- panelTools.Size = new Size(200, 553);
+ panelTools.Size = new Size(200, 517);
panelTools.TabIndex = 1;
//
// panelSets
@@ -274,7 +320,7 @@ namespace Trolleybus
//
// buttonRefreshCollection
//
- buttonRefreshCollection.Location = new Point(17, 484);
+ buttonRefreshCollection.Location = new Point(17, 465);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(170, 40);
buttonRefreshCollection.TabIndex = 3;
@@ -311,11 +357,53 @@ namespace Trolleybus
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += ButtonAddBus_Click;
//
+ // menuStrip
+ //
+ menuStrip.ImageScalingSize = new Size(20, 20);
+ menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
+ menuStrip.Location = new Point(0, 0);
+ menuStrip.Name = "menuStrip";
+ menuStrip.Size = new Size(882, 28);
+ menuStrip.TabIndex = 2;
+ menuStrip.Text = "menuStrip1";
+ //
+ // fileToolStripMenuItem
+ //
+ fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, downloadToolStripMenuItem });
+ 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;
+ //
+ // downloadToolStripMenuItem
+ //
+ downloadToolStripMenuItem.Name = "downloadToolStripMenuItem";
+ downloadToolStripMenuItem.Size = new Size(224, 26);
+ downloadToolStripMenuItem.Text = "Загрузка";
+ downloadToolStripMenuItem.Click += DownloadToolStripMenuItem_Click;
+ //
+ // openFileDialog
+ //
+ openFileDialog.FileName = "openFileDialog";
+ openFileDialog.Filter = "txt file | *.txt";
+ //
+ // saveFileDialog
+ //
+ saveFileDialog.Filter = "txt file | *.txt";
+ //
// FormBusesCollection
//
ClientSize = new Size(882, 553);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
+ Controls.Add(menuStrip);
+ MainMenuStrip = menuStrip;
Name = "FormBusesCollection";
Text = "Набор автобусов";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
@@ -323,7 +411,10 @@ namespace Trolleybus
panelTools.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
+ menuStrip.ResumeLayout(false);
+ menuStrip.PerformLayout();
ResumeLayout(false);
+ PerformLayout();
}
private PictureBox pictureBoxCollection;
@@ -336,6 +427,12 @@ namespace Trolleybus
private ListBox listBoxSets;
private TextBox textBoxNameOfSet;
private Button buttonDeleteSetOfObjects;
+ private MenuStrip menuStrip;
+ private ToolStripMenuItem fileToolStripMenuItem;
+ private ToolStripMenuItem saveToolStripMenuItem;
+ private ToolStripMenuItem downloadToolStripMenuItem;
+ private OpenFileDialog openFileDialog;
+ private SaveFileDialog saveFileDialog;
private Button buttonAddBus;
}
diff --git a/Trolleybus/Trolleybus/FormBusesCollection.resx b/Trolleybus/Trolleybus/FormBusesCollection.resx
index af32865..5966cd3 100644
--- a/Trolleybus/Trolleybus/FormBusesCollection.resx
+++ b/Trolleybus/Trolleybus/FormBusesCollection.resx
@@ -117,4 +117,13 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+ 17, 17
+
+
+ 153, 17
+
+
+ 323, 17
+
\ No newline at end of file