Готовая 6 лабораторная

This commit is contained in:
russell 2023-12-01 19:22:27 +04:00
parent 0d223f8de8
commit 6d86c591d1
6 changed files with 283 additions and 16 deletions

View File

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.Entities;
namespace DumpTruck.DrawingObjects
{
public static class ExtentionDrawingTruck
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingTruck? CreateDrawingTruck(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingTruck(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawingDumpTruck(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Convert.ToBoolean(strs[3]),
Convert.ToBoolean(strs[4]),
Color.FromName(strs[5]),
Color.FromName(strs[6]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingTruck">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingTruck drawingTruck, char separatorForObject)
{
var truck = drawingTruck.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.Tent}{separatorForObject}{dumpTruck.DumpBox}{separatorForObject}{dumpTruck.TentColor.Name}{separatorForObject}{dumpTruck.DumpBoxColor.Name}";
}
}
}

View File

@ -32,6 +32,10 @@
this.panelStorages = new System.Windows.Forms.Panel(); this.panelStorages = new System.Windows.Forms.Panel();
this.labelStorages = new System.Windows.Forms.Label(); this.labelStorages = new System.Windows.Forms.Label();
this.textBoxStorageName = new System.Windows.Forms.TextBox(); this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.menuStripFile = new System.Windows.Forms.MenuStrip();
this.toolStripMenuItemFile = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemSave = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemLoad = new System.Windows.Forms.ToolStripMenuItem();
this.buttonDelObject = new System.Windows.Forms.Button(); this.buttonDelObject = new System.Windows.Forms.Button();
this.buttonAddObject = new System.Windows.Forms.Button(); this.buttonAddObject = new System.Windows.Forms.Button();
this.listBoxStorages = new System.Windows.Forms.ListBox(); this.listBoxStorages = new System.Windows.Forms.ListBox();
@ -41,8 +45,11 @@
this.buttonRemoveTruck = new System.Windows.Forms.Button(); this.buttonRemoveTruck = new System.Windows.Forms.Button();
this.buttonAddTruck = new System.Windows.Forms.Button(); this.buttonAddTruck = new System.Windows.Forms.Button();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.panelTools.SuspendLayout(); this.panelTools.SuspendLayout();
this.panelStorages.SuspendLayout(); this.panelStorages.SuspendLayout();
this.menuStripFile.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.SuspendLayout(); this.SuspendLayout();
// //
@ -65,12 +72,13 @@
// //
this.panelStorages.Controls.Add(this.labelStorages); this.panelStorages.Controls.Add(this.labelStorages);
this.panelStorages.Controls.Add(this.textBoxStorageName); this.panelStorages.Controls.Add(this.textBoxStorageName);
this.panelStorages.Controls.Add(this.menuStripFile);
this.panelStorages.Controls.Add(this.buttonDelObject); this.panelStorages.Controls.Add(this.buttonDelObject);
this.panelStorages.Controls.Add(this.buttonAddObject); this.panelStorages.Controls.Add(this.buttonAddObject);
this.panelStorages.Controls.Add(this.listBoxStorages); this.panelStorages.Controls.Add(this.listBoxStorages);
this.panelStorages.Location = new System.Drawing.Point(3, 18); this.panelStorages.Location = new System.Drawing.Point(3, 18);
this.panelStorages.Name = "panelStorages"; this.panelStorages.Name = "panelStorages";
this.panelStorages.Size = new System.Drawing.Size(200, 221); this.panelStorages.Size = new System.Drawing.Size(200, 246);
this.panelStorages.TabIndex = 5; this.panelStorages.TabIndex = 5;
// //
// labelStorages // labelStorages
@ -89,6 +97,40 @@
this.textBoxStorageName.Size = new System.Drawing.Size(150, 23); this.textBoxStorageName.Size = new System.Drawing.Size(150, 23);
this.textBoxStorageName.TabIndex = 3; this.textBoxStorageName.TabIndex = 3;
// //
// menuStripFile
//
this.menuStripFile.Dock = System.Windows.Forms.DockStyle.None;
this.menuStripFile.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemFile});
this.menuStripFile.Location = new System.Drawing.Point(25, 222);
this.menuStripFile.Name = "menuStripFile";
this.menuStripFile.Size = new System.Drawing.Size(176, 24);
this.menuStripFile.TabIndex = 2;
this.menuStripFile.Text = "menuStripFile";
//
// toolStripMenuItemFile
//
this.toolStripMenuItemFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemSave,
this.toolStripMenuItemLoad});
this.toolStripMenuItemFile.Name = "toolStripMenuItemFile";
this.toolStripMenuItemFile.Size = new System.Drawing.Size(48, 20);
this.toolStripMenuItemFile.Text = "Файл";
//
// toolStripMenuItemSave
//
this.toolStripMenuItemSave.Name = "toolStripMenuItemSave";
this.toolStripMenuItemSave.Size = new System.Drawing.Size(180, 22);
this.toolStripMenuItemSave.Text = "Сохранить";
this.toolStripMenuItemSave.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// toolStripMenuItemLoad
//
this.toolStripMenuItemLoad.Name = "toolStripMenuItemLoad";
this.toolStripMenuItemLoad.Size = new System.Drawing.Size(180, 22);
this.toolStripMenuItemLoad.Text = "Загрузить";
this.toolStripMenuItemLoad.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// buttonDelObject // buttonDelObject
// //
this.buttonDelObject.Location = new System.Drawing.Point(25, 185); this.buttonDelObject.Location = new System.Drawing.Point(25, 185);
@ -121,7 +163,7 @@
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 302); this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 306);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber"; this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(150, 23); this.maskedTextBoxNumber.Size = new System.Drawing.Size(150, 23);
this.maskedTextBoxNumber.TabIndex = 4; this.maskedTextBoxNumber.TabIndex = 4;
@ -148,7 +190,7 @@
// //
// buttonRemoveTruck // buttonRemoveTruck
// //
this.buttonRemoveTruck.Location = new System.Drawing.Point(28, 336); this.buttonRemoveTruck.Location = new System.Drawing.Point(28, 335);
this.buttonRemoveTruck.Name = "buttonRemoveTruck"; this.buttonRemoveTruck.Name = "buttonRemoveTruck";
this.buttonRemoveTruck.Size = new System.Drawing.Size(150, 30); this.buttonRemoveTruck.Size = new System.Drawing.Size(150, 30);
this.buttonRemoveTruck.TabIndex = 2; this.buttonRemoveTruck.TabIndex = 2;
@ -158,7 +200,7 @@
// //
// buttonAddTruck // buttonAddTruck
// //
this.buttonAddTruck.Location = new System.Drawing.Point(28, 257); this.buttonAddTruck.Location = new System.Drawing.Point(28, 270);
this.buttonAddTruck.Name = "buttonAddTruck"; this.buttonAddTruck.Name = "buttonAddTruck";
this.buttonAddTruck.Size = new System.Drawing.Size(150, 30); this.buttonAddTruck.Size = new System.Drawing.Size(150, 30);
this.buttonAddTruck.TabIndex = 1; this.buttonAddTruck.TabIndex = 1;
@ -174,6 +216,15 @@
this.pictureBoxCollection.TabIndex = 1; this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false; this.pictureBoxCollection.TabStop = false;
// //
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormTruckCollection // FormTruckCollection
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@ -181,12 +232,15 @@
this.ClientSize = new System.Drawing.Size(800, 450); this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.pictureBoxCollection); this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.panelTools); this.Controls.Add(this.panelTools);
this.MainMenuStrip = this.menuStripFile;
this.Name = "FormTruckCollection"; this.Name = "FormTruckCollection";
this.Text = "FormTruckCollection"; this.Text = "FormTruckCollection";
this.panelTools.ResumeLayout(false); this.panelTools.ResumeLayout(false);
this.panelTools.PerformLayout(); this.panelTools.PerformLayout();
this.panelStorages.ResumeLayout(false); this.panelStorages.ResumeLayout(false);
this.panelStorages.PerformLayout(); this.panelStorages.PerformLayout();
this.menuStripFile.ResumeLayout(false);
this.menuStripFile.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.ResumeLayout(false); this.ResumeLayout(false);
@ -207,5 +261,11 @@
private ListBox listBoxStorages; private ListBox listBoxStorages;
private Label labelStorages; private Label labelStorages;
private TextBox textBoxStorageName; private TextBox textBoxStorageName;
private MenuStrip menuStripFile;
private ToolStripMenuItem toolStripMenuItemFile;
private ToolStripMenuItem toolStripMenuItemSave;
private ToolStripMenuItem toolStripMenuItemLoad;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
} }
} }

View File

@ -96,8 +96,8 @@ namespace DumpTruck
private void AddTruck(DrawingTruck truck) private void AddTruck(DrawingTruck truck)
{ {
truck._pictureWidth = pictureBoxCollection.Width; truck._pictureWidth = pictureBoxCollection.Image.Width;
truck._pictureHeight = pictureBoxCollection.Height; truck._pictureHeight = pictureBoxCollection.Image.Height;
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
return; return;
@ -170,6 +170,48 @@ namespace DumpTruck
} }
pictureBoxCollection.Image = obj.ShowTrucks(); pictureBoxCollection.Image = obj.ShowTrucks();
} }
} /// <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))
{
MessageBox.Show("Загрузка прошла успешно",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
} }

View File

@ -57,4 +57,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStripFile.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>143, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>276, 17</value>
</metadata>
</root> </root>

View File

@ -38,6 +38,10 @@ namespace DumpTruck.Generics
/// </summary> /// </summary>
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
/// <summary> /// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTrucks => _collection.GetTrucks();
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="picWidth"></param> /// <param name="picWidth"></param>
@ -131,8 +135,8 @@ namespace DumpTruck.Generics
{ {
if (truck != null) if (truck != null)
{ {
truck.SetPosition(index % (_pictureWidth / _placeSizeWidth) * _placeSizeWidth, index / (_pictureWidth / _placeSizeWidth) * _placeSizeHeight); truck.SetPosition(index % (_pictureWidth / _placeSizeWidth) * _placeSizeWidth, index / (_pictureWidth / _placeSizeWidth) * _placeSizeHeight);
truck.DrawTransport(g); truck.DrawTransport(g);
} }
index++; index++;
} }

View File

@ -13,10 +13,22 @@ namespace DumpTruck.Generics
/// </summary> /// </summary>
internal class TrucksGenericStorage internal class TrucksGenericStorage
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) /// Разделитель для записи ключа и значения элемента словаря
/// </summary> /// </summary>
readonly Dictionary<string, TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>> _truckStorages; private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>> _truckStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
@ -70,5 +82,82 @@ namespace DumpTruck.Generics
return null; return null;
} }
} }
} /// <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<DrawingTruck, DrawningObjectTruck>> record in _truckStorages)
{
StringBuilder records = new();
foreach (DrawingTruck? elem in record.Value.GetTrucks)
{
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 < DrawingTruck, DrawningObjectTruck > collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingTruck? truck = elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight);
if (truck != null)
{
if (collection + truck == -1)
{
return false;
}
}
}
_truckStorages.Add(record[0], collection);
}
}
return true;
}
}
} }