Боровков М В ПИбд-22 6 лабораторная работа #7

Closed
bekodeg wants to merge 3 commits from labWork6 into labWork5
8 changed files with 290 additions and 6 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -35,6 +35,19 @@ namespace ProjectElectricLocomotive.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>
@ -92,5 +105,94 @@ namespace ProjectElectricLocomotive.Generics
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
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<string, LocomotivesGenericCollection<
DrawningLocomotive, DrawningObjectLocomotive>>
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;
}
}
/// <summary>
/// Загрузка информации по Локомативам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка призагрузке данных</returns>
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<DrawningLocomotive, DrawningObjectLocomotive>
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;
}
}
}
}

View File

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

View File

@ -16,6 +16,8 @@ namespace ProjectElectricLocomotive
/// </summary>
DrawningLocomotive? _locomotive = null;
public delegate Object Func<out Object>();
/// <summary>
/// Событие
/// </summary>