PIbd-22_Chernyshev_G.Y._LabWork06_Base #6

Closed
ujijrujijr wants to merge 1 commits from LabWork06 into LabWork05
6 changed files with 276 additions and 10 deletions

View File

@ -150,5 +150,9 @@ namespace Trolleybus.Generics
}
}
}
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetBuses => _collection.GetBuses();
}
}

View File

@ -31,6 +31,19 @@ namespace Trolleybus.Generics
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
@ -85,5 +98,80 @@ namespace Trolleybus.Generics
return _busStorages[ind];
}
}
/// <summary>
/// Сохранение информации по автобусам из хранилища в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, BusesGenericCollection<DrawingBus, DrawingObjectBus>> 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;
}
/// <summary>
/// Загрузка информации по автобусам из файла в хранилище
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
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<DrawingBus, DrawingObjectBus> 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;
}
}
}

View File

@ -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
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
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;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingBus">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
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}";
}
}
}

View File

@ -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);

View File

@ -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();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>323, 17</value>
</metadata>
</root>