3 Commits
Lab5 ... Lab7

Author SHA1 Message Date
5f39e71615 Lab7 fix 2022-12-13 17:24:29 +04:00
cebb91a24c Lab7 ready 2022-12-13 15:32:05 +04:00
5acbbdb986 Lab6 ready 2022-12-08 00:31:48 +04:00
15 changed files with 480 additions and 94 deletions

View File

@@ -30,5 +30,9 @@
{ {
_roadTrain.DrawTransport(g); _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.buttonShowStorage = new System.Windows.Forms.Button();
this.buttonRemoveRoadTrain = new System.Windows.Forms.Button(); this.buttonRemoveRoadTrain = new System.Windows.Forms.Button();
this.buttonAddRoadTrain = 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(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.groupBox.SuspendLayout(); this.groupBox.SuspendLayout();
this.groupBoxMaps.SuspendLayout(); this.groupBoxMaps.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
// //
// pictureBox // 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.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.TabIndex = 0;
this.pictureBox.TabStop = false; this.pictureBox.TabStop = false;
// //
@@ -240,6 +246,40 @@
this.buttonAddRoadTrain.UseVisualStyleBackColor = true; this.buttonAddRoadTrain.UseVisualStyleBackColor = true;
this.buttonAddRoadTrain.Click += new System.EventHandler(this.ButtonAddRoadTrain_Click); 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 // FormMapWithSetRoadTrains
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@@ -247,6 +287,8 @@
this.ClientSize = new System.Drawing.Size(831, 450); this.ClientSize = new System.Drawing.Size(831, 450);
this.Controls.Add(this.groupBox); this.Controls.Add(this.groupBox);
this.Controls.Add(this.pictureBox); this.Controls.Add(this.pictureBox);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMapWithSetRoadTrains"; this.Name = "FormMapWithSetRoadTrains";
this.Text = "Карта с набором объектов"; this.Text = "Карта с набором объектов";
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
@@ -254,7 +296,11 @@
this.groupBox.PerformLayout(); this.groupBox.PerformLayout();
this.groupBoxMaps.ResumeLayout(false); this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout(); this.groupBoxMaps.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout();
} }
#endregion #endregion
@@ -276,5 +322,10 @@
private Button buttonRemoveMap; private Button buttonRemoveMap;
private ListBox listBoxMaps; private ListBox listBoxMaps;
private TextBox textBoxNewMapName; private TextBox textBoxNewMapName;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private MenuStrip menuStrip1;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
} }
} }

View File

@@ -1,7 +1,15 @@
namespace RoadTrain using static System.Net.Mime.MediaTypeNames;
using Microsoft.Extensions.Logging;
namespace RoadTrain
{ {
public partial class FormMapWithSetRoadTrains : Form public partial class FormMapWithSetRoadTrains : Form
{ {
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Словарь для выпадающего списка /// Словарь для выпадающего списка
/// </summary> /// </summary>
@@ -19,9 +27,10 @@
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormMapWithSetRoadTrains() public FormMapWithSetRoadTrains(ILogger<FormMapWithSetRoadTrains> logger)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear(); comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict) foreach (var elem in _mapsDict)
@@ -61,6 +70,7 @@
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Был осуществлен переход на карту под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
} }
/// <summary> /// <summary>
@@ -73,15 +83,18 @@
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? " Не все данные заполнены " : "Не была названа карта");
return; return;
} }
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{ {
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Нет такой карты {textBoxNewMapName.Text}");
return; return;
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
} }
/// <summary> /// <summary>
@@ -100,6 +113,7 @@
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps(); ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
@@ -124,21 +138,32 @@
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void AddRoadTrainOnForm(DrawningRoadTrain drawningRoadTrain) private void AddRoadTrainOnForm(DrawningRoadTrain drawningRoadTrain)
{
try
{ {
if (listBoxMaps.SelectedIndex == -1) if (listBoxMaps.SelectedIndex == -1)
{ {
_logger.LogInformation("Попытка добавить объект, без создания карты");
return; return;
} }
DrawningObjectRoadTrain roadTrain = new(drawningRoadTrain); DrawningObjectRoadTrain roadTrain = new(drawningRoadTrain);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + roadTrain >= 0) if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + roadTrain >= 0)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {drawningRoadTrain}");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
} }
} }
@@ -162,13 +187,30 @@
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект {_mapsCollection[listBoxMaps.SelectedItem?.ToString()]}");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else { MessageBox.Show("Не удалось удалить объект"); } else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Не удалось удалить объект");
}
}
catch (RoadTrainNotFoundException ex)
{
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
} }
/// <summary> /// <summary>
@@ -231,5 +273,53 @@
} }
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir); 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)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение прошло успешно. Файл находится: {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл '{openFileDialog.FileName}' успешно загружен");
ReloadMaps();
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не получилось загрузить файл. Текст ошибки: {ex.Message}");
}
}
ReloadMaps();
}
} }
} }

View File

@@ -1,64 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <root>
<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.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <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:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">
@@ -117,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="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> </root>

View File

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

View File

@@ -49,7 +49,7 @@
{ {
int width = picWidth / _placeSizeWidth; int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight; int height = picHeight / _placeSizeHeight;
_setRoadTrains = new SetRoadTrainsGeneric<T>(width * height - 2); _setRoadTrains = new SetRoadTrainsGeneric<T>(width * height - 1);
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_map = map; _map = map;
@@ -188,5 +188,32 @@
j++; 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> /// <summary>
/// Класс для хранения коллекции карт /// Класс для хранения коллекции карт
@@ -8,7 +10,7 @@
/// <summary> /// <summary>
/// Словарь (хранилище) с картами /// Словарь (хранилище) с картами
/// </summary> /// </summary>
readonly Dictionary<string, MapWithSetRoadTrainsGeneric<DrawningObjectRoadTrain, AbstractMap>> _mapStorages; readonly Dictionary<string, MapWithSetRoadTrainsGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary> /// <summary>
/// Возвращение списка названий карт /// Возвращение списка названий карт
@@ -25,6 +27,16 @@
/// </summary> /// </summary>
private readonly int _pictureHeight; private readonly int _pictureHeight;
/// <summary>
/// Знак-разделитель для карт
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Знак-разделитель для объектов
/// </summary>
private readonly char separatorData = ';';
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -32,7 +44,7 @@
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight) public MapsCollection(int pictureWidth, int pictureHeight)
{ {
_mapStorages = new Dictionary<string, MapWithSetRoadTrainsGeneric<DrawningObjectRoadTrain, AbstractMap>>(); _mapStorages = new Dictionary<string, MapWithSetRoadTrainsGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@@ -51,7 +63,7 @@
} }
else 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> /// </summary>
/// <param name="ind"></param> /// <param name="ind"></param>
/// <returns></returns> /// <returns></returns>
public MapWithSetRoadTrainsGeneric<DrawningObjectRoadTrain, AbstractMap> this[string ind] public MapWithSetRoadTrainsGeneric<IDrawningObject, AbstractMap> this[string ind]
{ {
get get
{ {
@@ -78,5 +90,76 @@
return null; return null;
} }
} }
/// <summary>
/// Метод записи информации в файл
/// </summary>
/// <param name="text">Строка, которую следует записать</param>
/// <param name="stream">Поток для записи</param>
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
/// <summary>
/// Сохранение информации по грузовикам хранилища в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public void 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}");
}
}
}
/// <summary>
/// Загрузка нформации по грузовикам на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
string bufferTextFromFile = "";
using (StreamReader sr = new(filename))
{
string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не правильный");
}
_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));
}
}
}
} }
} }

View File

@@ -1,4 +1,10 @@
namespace RoadTrain using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace RoadTrain
{ {
internal static class Program internal static class Program
{ {
@@ -12,7 +18,31 @@
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetRoadTrains()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetRoadTrains>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetRoadTrains>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@@ -16,6 +16,20 @@
<EmbeddedResource Remove="Form1.resx" /> <EmbeddedResource Remove="Form1.resx" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@@ -0,0 +1,18 @@
using System.Runtime.Serialization;
namespace RoadTrain
{
[Serializable]
internal class RoadTrainNotFoundException : ApplicationException
{
public RoadTrainNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public RoadTrainNotFoundException() : base() { }
public RoadTrainNotFoundException(string message) : base(message) { }
public RoadTrainNotFoundException(string message, Exception exception) : base(message, exception) { }
protected RoadTrainNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -38,7 +38,7 @@
{ {
// проверка на _maxCount // проверка на _maxCount
if (_places.Count + 1 >= _maxCount) if (_places.Count + 1 >= _maxCount)
return -1; throw new StorageOverflowException(_maxCount);
_places.Insert(0, roadTrain); _places.Insert(0, roadTrain);
return 0; return 0;
} }
@@ -57,7 +57,7 @@
// проверка на _maxCount // проверка на _maxCount
if (_places.Count + 1 >= _maxCount) if (_places.Count + 1 >= _maxCount)
return -1; throw new StorageOverflowException(_maxCount);
// вставка по позиции // вставка по позиции
_places[position] = roadTrain; _places[position] = roadTrain;
@@ -72,10 +72,17 @@
public T Remove(int position) public T Remove(int position)
{ {
// проверка позиции // проверка позиции
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount - 1)
return null; return null;
T delObj = _places[position]; if (position >= _places.Count)
// удаление объекта из массива {
throw new RoadTrainNotFoundException(position);
}
var delObj = _places[position];
if (delObj == null)
{
throw new RoadTrainNotFoundException(position);
}
_places.RemoveAt(position); _places.RemoveAt(position);
return delObj; return delObj;
} }

View File

@@ -0,0 +1,18 @@
using System.Runtime.Serialization;
namespace RoadTrain
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
]
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="roadtrainlog${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>