PIbd-21. Danilov V.V. Lab work 06 #6

Closed
VoOneChek wants to merge 1 commits from LabWork06 into LabWork05
6 changed files with 275 additions and 5 deletions

View File

@ -0,0 +1,68 @@
using Project_DumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_DumpTruck.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtentionDrawningTruck
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningTruck? CreateDrawningTruck(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningTruck(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningDumpTruck(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="drawningTruck">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTruck drawningTruck,
char separatorForObject)
{
var truck = drawningTruck.EntityTruck;
if (truck == null)
{
return string.Empty;
}
var str =
$"{truck.Speed}{separatorForObject}{truck.Weight}{separatorForObject}{truck.BodyColor.Name}";
if (truck is not EntityDumpTruck dumpTruck)
{
return str;
}
return
$"{str}{separatorForObject}{dumpTruck.AdditionalColor.Name}{separatorForObject}{dumpTruck.BodyKit}{separatorForObject}{dumpTruck.Tent}";
}
}
}

View File

@ -39,9 +39,16 @@
buttonRemoveTruck = new Button();
buttonAddTruck = new Button();
pictureBoxCollection = new PictureBox();
menuStrip1 = new MenuStrip();
ToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBox1.SuspendLayout();
groupBoxStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// groupBox1
@ -51,7 +58,7 @@
groupBox1.Controls.Add(buttonRefreshCollection);
groupBox1.Controls.Add(buttonRemoveTruck);
groupBox1.Controls.Add(buttonAddTruck);
groupBox1.Location = new Point(588, 12);
groupBox1.Location = new Point(588, 27);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(200, 426);
groupBox1.TabIndex = 0;
@ -147,19 +154,60 @@
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(12, 12);
pictureBoxCollection.Location = new Point(12, 27);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(570, 426);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { ToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(800, 24);
menuStrip1.TabIndex = 2;
menuStrip1.Text = "menuStrip1";
//
// ToolStripMenuItem
//
ToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
ToolStripMenuItem.Name = "ToolStripMenuItem";
ToolStripMenuItem.Size = new Size(48, 20);
ToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(180, 22);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(180, 22);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormTruckCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(800, 468);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBox1);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormTruckCollection";
Text = "Набор грузовиков";
groupBox1.ResumeLayout(false);
@ -167,7 +215,10 @@
groupBoxStorage.ResumeLayout(false);
groupBoxStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -183,5 +234,11 @@
private ListBox listBoxStorages;
private Button buttonAddObject;
private TextBox textBoxStorageName;
private MenuStrip menuStrip1;
private ToolStripMenuItem ToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -174,5 +174,48 @@ namespace Project_DumpTruck
ReloadObjects();
}
}
/// <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 LoadToolStripMenuItem_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);
}
}
}
}
}

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="menuStrip1.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>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>271, 17</value>
</metadata>
</root>

View File

@ -33,6 +33,10 @@ namespace Project_DumpTruck.Generics
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetCars => _collection.GetTrucks();
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>

View File

@ -27,6 +27,18 @@ namespace Project_DumpTruck.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>
/// <param name="pictureWidth"></param>
@ -43,7 +55,6 @@ namespace Project_DumpTruck.Generics
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// TODO Прописать логику для добавления
_truckStorages.Add(name, new TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>(_pictureWidth, _pictureHeight));
}
/// <summary>
@ -52,7 +63,6 @@ namespace Project_DumpTruck.Generics
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
// TODO Прописать логику для удаления
if (_truckStorages.ContainsKey(name))
_truckStorages.Remove(name);
}
@ -72,5 +82,84 @@ namespace Project_DumpTruck.Generics
}
}
/// <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,
TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>> record in _truckStorages)
{
StringBuilder records = new();
foreach (DrawningTruck? elem in record.Value.GetCars)
{
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($"TruckStorage{Environment.NewLine}{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 = new(filename))
{
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith("TruckStorage"))
{
//если нет такой записи, то это не те данные
return false;
}
_truckStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
TrucksGenericCollection<DrawningTruck, DrawningObjectTruck> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set.Reverse())
{
DrawningTruck? truck = elem?.CreateDrawningTruck(_separatorForObject, _pictureWidth, _pictureHeight);
if (truck != null)
{
if (collection + truck == -1)
{
return false;
}
}
}
_truckStorages.Add(record[0], collection);
}
}
return true;
}
}
}