Tomasheva_Lab_№6 #7

Closed
Saanechkaa wants to merge 1 commits from Lab6 into Lab5
8 changed files with 292 additions and 69 deletions
Showing only changes of commit 5acbbdb986 - Show all commits

View File

@ -30,5 +30,9 @@
{
_roadTrain.DrawTransport(g);
}
public string GetInfo() => _roadTrain?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectRoadTrain(data.CreateDrawningRoadTrain());
}
}

View File

@ -0,0 +1,58 @@
namespace RoadTrain
{
/// <summary>
/// Расширение для класса DrawningRoadTrain
/// </summary>
internal static class ExtentionRoadTrain
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningRoadTrain CreateDrawningRoadTrain(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningRoadTrain(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningSweeperRoadTrain(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningRoadTrain"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningRoadTrain drawningRoadTrain)
{
var roadTrain = drawningRoadTrain.RoadTrain;
var str = $"{roadTrain.Speed}{_separatorForObject}{roadTrain.Weight}" +
$"{_separatorForObject}{roadTrain.BodyColor. Name}";
if (roadTrain is not EntitySweeperRoadTrain sweeperRoadTrain)
{
return str;
}
return $"{str}{_separatorForObject}{sweeperRoadTrain.DopColor.Name}{_separatorForObject}" +
$"{sweeperRoadTrain.WaterTank}{_separatorForObject}{sweeperRoadTrain.SweepingBush}";
}
}
}

View File

@ -45,16 +45,22 @@
this.buttonShowStorage = new System.Windows.Forms.Button();
this.buttonRemoveRoadTrain = new System.Windows.Forms.Button();
this.buttonAddRoadTrain = new System.Windows.Forms.Button();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.groupBox.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// pictureBox
//
this.pictureBox.Location = new System.Drawing.Point(3, 3);
this.pictureBox.Location = new System.Drawing.Point(3, 27);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(644, 445);
this.pictureBox.Size = new System.Drawing.Size(644, 421);
this.pictureBox.TabIndex = 0;
this.pictureBox.TabStop = false;
//
@ -240,6 +246,40 @@
this.buttonAddRoadTrain.UseVisualStyleBackColor = true;
this.buttonAddRoadTrain.Click += new System.EventHandler(this.ButtonAddRoadTrain_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(831, 24);
this.menuStrip1.TabIndex = 2;
this.menuStrip1.Text = "menuStrip1";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(86, 20);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(67, 20);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// FormMapWithSetRoadTrains
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@ -247,6 +287,8 @@
this.ClientSize = new System.Drawing.Size(831, 450);
this.Controls.Add(this.groupBox);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMapWithSetRoadTrains";
this.Text = "Карта с набором объектов";
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
@ -254,7 +296,11 @@
this.groupBox.PerformLayout();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
@ -276,5 +322,10 @@
private Button buttonRemoveMap;
private ListBox listBoxMaps;
private TextBox textBoxNewMapName;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private MenuStrip menuStrip1;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
}
}

View File

@ -1,4 +1,6 @@
namespace RoadTrain
using static System.Net.Mime.MediaTypeNames;
namespace RoadTrain
{
public partial class FormMapWithSetRoadTrains : Form
{
@ -231,5 +233,46 @@
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.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 (_mapsCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Ошибка загрузки", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
ReloadMaps();
}
}
}

View File

@ -1,64 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
@ -117,4 +57,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>157, 17</value>
</metadata>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>286, 17</value>
</metadata>
</root>

View File

@ -33,5 +33,11 @@
/// </summary>
/// <returns></returns>
(float Left, float Top, float Right, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@ -188,5 +188,32 @@
j++;
}
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var roadTrain in _setRoadTrains.GetRoadTrains())
{
data += $"{roadTrain.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setRoadTrains.Insert(DrawningObjectRoadTrain.Create(rec) as T);
}
}
}
}

View File

@ -1,4 +1,6 @@
namespace RoadTrain
using System.Text;
namespace RoadTrain
{
/// <summary>
/// Класс для хранения коллекции карт
@ -8,7 +10,7 @@
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetRoadTrainsGeneric<DrawningObjectRoadTrain, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetRoadTrainsGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
@ -25,6 +27,16 @@
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Знак-разделитель для карт
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Знак-разделитель для объектов
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
@ -32,7 +44,7 @@
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetRoadTrainsGeneric<DrawningObjectRoadTrain, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetRoadTrainsGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -51,7 +63,7 @@
}
else
{
_mapStorages.Add(name, new MapWithSetRoadTrainsGeneric<DrawningObjectRoadTrain, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetRoadTrainsGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
}
@ -69,7 +81,7 @@
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetRoadTrainsGeneric<DrawningObjectRoadTrain, AbstractMap> this[string ind]
public MapWithSetRoadTrainsGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
@ -78,5 +90,78 @@
return null;
}
}
/// <summary>
/// Метод записи информации в файл
/// </summary>
/// <param name="text">Строка, которую следует записать</param>
/// <param name="stream">Поток для записи</param>
private static void WriteToFile(string text, FileStream stream)
Review

Неиспользуемый метод

Неиспользуемый метод
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
/// <summary>
/// Сохранение информации по грузовикам хранилища в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
/// <summary>
/// Загрузка нформации по грузовикам на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
string bufferTextFromFile = "";
Review

Зачем заводить bufferTextFromFile, если она не используется?

Зачем заводить bufferTextFromFile, если она не используется?
using (StreamReader sr = new(filename))
{
string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
return false;
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
var elem = str.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "RoadMap":
map = new RoadMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetRoadTrainsGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}