5 Commits
LABA5 ... LABA7

Author SHA1 Message Date
Daniel
931ccb2599 искл 2022-12-23 01:31:29 +04:00
Daniel
beb635889b . 2022-12-23 01:28:21 +04:00
Daniel
01d98db116 дописал исключение 2022-12-23 01:13:22 +04:00
Daniel
122a5dbfe1 готово 2022-12-23 00:48:39 +04:00
Daniel
cc983c3272 6 лабораторная по сохранению 2022-12-13 01:49:12 +04:00
15 changed files with 458 additions and 46 deletions

View File

@@ -4,6 +4,7 @@ using System.Drawing;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Tractors;
namespace WinFormsApp1 namespace WinFormsApp1
{ {
@@ -23,6 +24,10 @@ namespace WinFormsApp1
return _tractor?.GetCurrentPosition() ?? default; return _tractor?.GetCurrentPosition() ?? default;
} }
public string GetInfo() => _tractor?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectTractor(data.CreateDrawingTraktor());
public void MoveObject(Direction direction) public void MoveObject(Direction direction)
{ {
_tractor?.MoveTransport(direction); _tractor?.MoveTransport(direction);

View File

@@ -34,5 +34,12 @@ namespace WinFormsApp1
Weight = weight <= 0 ? rnd.Next(40, 70) : weight; Weight = weight <= 0 ? rnd.Next(40, 70) : weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
public static EntityTractor Creator(string data)
{
string[] strs = data.Split(':');
return new EntityTractor(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
} }
} }

View File

@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFormsApp1;
namespace WinFormsApp1
{
internal static class ExtentionTraktor
{
private static readonly char _separatorForObject = ':';
public static TractorDraw CreateDrawingTraktor(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new TractorDraw(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new MultiTraktorDraw(
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;
}
public static string GetDataForSave(this TractorDraw drawingTraktor)
{
var traktor = drawingTraktor.Tractor;
var str = $"{traktor.Speed}{_separatorForObject}{traktor.Weight}{_separatorForObject}{traktor.BodyColor.Name}";
if (traktor is not MultiTraktor multiTraktor)
{
return str;
}
return $"{str}{_separatorForObject}{multiTraktor.DopColor.Name}{_separatorForObject}{multiTraktor.dopAhead}{_separatorForObject}{multiTraktor.dopBehind}";
}
}
}

View File

@@ -47,9 +47,16 @@ namespace WinFormsApp1
this.buttonRemoveTraktor = new System.Windows.Forms.Button(); this.buttonRemoveTraktor = new System.Windows.Forms.Button();
this.buttonAddTraktor = new System.Windows.Forms.Button(); this.buttonAddTraktor = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox(); this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBox1.SuspendLayout(); this.groupBox1.SuspendLayout();
this.groupBoxMaps.SuspendLayout(); this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
// //
// groupBox1 // groupBox1
@@ -65,11 +72,11 @@ namespace WinFormsApp1
this.groupBox1.Controls.Add(this.buttonRemoveTraktor); this.groupBox1.Controls.Add(this.buttonRemoveTraktor);
this.groupBox1.Controls.Add(this.buttonAddTraktor); this.groupBox1.Controls.Add(this.buttonAddTraktor);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Right; this.groupBox1.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox1.Location = new System.Drawing.Point(596, 0); this.groupBox1.Location = new System.Drawing.Point(596, 24);
this.groupBox1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.groupBox1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBox1.Name = "groupBox1"; this.groupBox1.Name = "groupBox1";
this.groupBox1.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2); this.groupBox1.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBox1.Size = new System.Drawing.Size(219, 476); this.groupBox1.Size = new System.Drawing.Size(219, 515);
this.groupBox1.TabIndex = 0; this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false; this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты"; this.groupBox1.Text = "Инструменты";
@@ -143,7 +150,7 @@ namespace WinFormsApp1
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Tractors.Properties.Resources.RkYIe2_6DuQ; this.buttonRight.BackgroundImage = global::Tractors.Properties.Resources.RkYIe2_6DuQ;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(126, 435); this.buttonRight.Location = new System.Drawing.Point(126, 442);
this.buttonRight.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.buttonRight.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonRight.Name = "buttonRight"; this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(35, 30); this.buttonRight.Size = new System.Drawing.Size(35, 30);
@@ -156,7 +163,7 @@ namespace WinFormsApp1
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Tractors.Properties.Resources.MbV2DYU_nPM; this.buttonDown.BackgroundImage = global::Tractors.Properties.Resources.MbV2DYU_nPM;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(91, 435); this.buttonDown.Location = new System.Drawing.Point(91, 442);
this.buttonDown.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.buttonDown.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDown.Name = "buttonDown"; this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(35, 30); this.buttonDown.Size = new System.Drawing.Size(35, 30);
@@ -169,7 +176,7 @@ namespace WinFormsApp1
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::Tractors.Properties.Resources.Hhxt4dLqV5g; this.buttonLeft.BackgroundImage = global::Tractors.Properties.Resources.Hhxt4dLqV5g;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(56, 435); this.buttonLeft.Location = new System.Drawing.Point(56, 442);
this.buttonLeft.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.buttonLeft.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(35, 30); this.buttonLeft.Size = new System.Drawing.Size(35, 30);
@@ -182,7 +189,7 @@ namespace WinFormsApp1
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::Tractors.Properties.Resources._2EdzyM4iEKw; this.buttonUp.BackgroundImage = global::Tractors.Properties.Resources._2EdzyM4iEKw;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(91, 405); this.buttonUp.Location = new System.Drawing.Point(91, 412);
this.buttonUp.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.buttonUp.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonUp.Name = "buttonUp"; this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(35, 30); this.buttonUp.Size = new System.Drawing.Size(35, 30);
@@ -245,20 +252,66 @@ namespace WinFormsApp1
// pictureBox // pictureBox
// //
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0); this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.pictureBox.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.pictureBox.Name = "pictureBox"; this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(596, 476); this.pictureBox.Size = new System.Drawing.Size(596, 515);
this.pictureBox.TabIndex = 1; this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false; this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(815, 24);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// //
// FormMapWithSetTraktor // FormMapWithSetTraktor
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(815, 476); this.ClientSize = new System.Drawing.Size(815, 538);
this.Controls.Add(this.pictureBox); this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormMapWithSetTraktor"; this.Name = "FormMapWithSetTraktor";
this.Text = "Автобус"; this.Text = "Автобус";
@@ -267,7 +320,10 @@ namespace WinFormsApp1
this.groupBoxMaps.ResumeLayout(false); this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout(); this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout();
} }
@@ -290,5 +346,11 @@ namespace WinFormsApp1
private Button buttonAddMap; private Button buttonAddMap;
private TextBox textBoxNewMapName; private TextBox textBoxNewMapName;
private ListBox listBoxMaps; private ListBox listBoxMaps;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
} }
} }

View File

@@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@@ -23,16 +24,22 @@ namespace WinFormsApp1
private readonly MapsCollection _mapsCollection; private readonly MapsCollection _mapsCollection;
public FormMapWithSetTraktor() private readonly ILogger _logger;
public FormMapWithSetTraktor(ILogger<FormMapWithSetTraktor> 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 item in _mapsDict) foreach (var item in _mapsDict)
{ {
comboBoxSelectorMap.Items.Add(item.Key); comboBoxSelectorMap.Items.Add(item.Key);
} }
}
public FormMapWithSetTraktor()
{
} }
private void ReloadMaps() private void ReloadMaps()
@@ -79,8 +86,6 @@ namespace WinFormsApp1
} }
} }
private void ButtonAddTraktor_Click(object sender, EventArgs e) private void ButtonAddTraktor_Click(object sender, EventArgs e)
{ {
var formBusConfig = new FormTraktorConfig(); var formBusConfig = new FormTraktorConfig();
@@ -89,6 +94,8 @@ namespace WinFormsApp1
} }
private void AddTraktor(TractorDraw traktor) private void AddTraktor(TractorDraw traktor)
{
try
{ {
if (listBoxMaps.SelectedIndex == -1) if (listBoxMaps.SelectedIndex == -1)
{ {
@@ -98,13 +105,27 @@ namespace WinFormsApp1
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0) if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation("Объект добавлен");
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)
{
_logger.LogWarning($"Ошибка, переполнение хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка, хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentException ex)
{
_logger.LogWarning("Ошибка добавления");
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemoveTraktor_Click(object sender, EventArgs e) private void ButtonRemoveTraktor_Click(object sender, EventArgs e)
{ {
if (listBoxMaps.SelectedIndex == -1) if (listBoxMaps.SelectedIndex == -1)
@@ -124,17 +145,32 @@ namespace WinFormsApp1
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) try
{
var deletedTraktor = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedTraktor != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удален объект {@traktor}", deletedTraktor);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
_logger.LogWarning("Не удалось добавить объект по позиции {0} равен null", pos);
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (TraktorNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e) private void ButtonShowStorage_Click(object sender, EventArgs e)
{ {
@@ -186,20 +222,24 @@ namespace WinFormsApp1
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.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return; return;
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
} }
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);
} }
private void buttonDeleteMap_Click(object sender, EventArgs e) private void buttonDeleteMap_Click(object sender, EventArgs e)
@@ -213,6 +253,44 @@ namespace WinFormsApp1
{ {
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps(); ReloadMaps();
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка данных прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} }
} }
} }

View File

@@ -25,5 +25,7 @@ namespace WinFormsApp1
void DrawningObject(Graphics g); void DrawningObject(Graphics g);
/// Получение текущей позиции объекта /// Получение текущей позиции объекта
(float Left, float Right, float Top, float Bottom) GetCurrentPosition(); (float Left, float Right, float Top, float Bottom) GetCurrentPosition();
string GetInfo();
} }
} }

View File

@@ -28,9 +28,9 @@ namespace WinFormsApp1
_map = map; _map = map;
} }
public static int operator +(MapWithSetTraktorGeneric<T, U> map, T bus) public static int operator +(MapWithSetTraktorGeneric<T, U> map, T traktor)
{ {
return map._setTraktors.Insert(bus); return map._setTraktors.Insert(traktor);
} }
public static T operator -(MapWithSetTraktorGeneric<T, U> map, int position) public static T operator -(MapWithSetTraktorGeneric<T, U> map, int position)
@@ -75,10 +75,10 @@ namespace WinFormsApp1
{ {
for (; j > i; j--) for (; j > i; j--)
{ {
var bus = _setTraktors[j]; var traktor = _setTraktors[j];
if (bus != null) if (traktor != null)
{ {
_setTraktors.Insert(bus, i); _setTraktors.Insert(traktor, i);
_setTraktors.Remove(j); _setTraktors.Remove(j);
break; break;
} }
@@ -135,5 +135,23 @@ namespace WinFormsApp1
} }
} }
} }
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var traktor in _setTraktors.GetTraktor())
{
data += $"{traktor.GetInfo()}{separatorData}";
}
return data;
}
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setTraktors.Insert(DrawningObjectTractor.Create(rec) as T);
}
}
} }
} }

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -8,7 +9,7 @@ namespace WinFormsApp1
{ {
internal class MapsCollection internal class MapsCollection
{ {
readonly Dictionary<string, MapWithSetTraktorGeneric<DrawningObjectTractor, AbstractMap>> _mapStorages; readonly Dictionary<string, MapWithSetTraktorGeneric<IDrawningObject, AbstractMap>> _mapStorages;
public List<string> Keys => _mapStorages.Keys.ToList(); public List<string> Keys => _mapStorages.Keys.ToList();
@@ -16,9 +17,13 @@ namespace WinFormsApp1
private readonly int _pictureHeight; private readonly int _pictureHeight;
private readonly char separatorDict = '|';
private readonly char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight) public MapsCollection(int pictureWidth, int pictureHeight)
{ {
_mapStorages = new Dictionary<string, MapWithSetTraktorGeneric<DrawningObjectTractor, AbstractMap>>(); _mapStorages = new Dictionary<string, MapWithSetTraktorGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@@ -28,7 +33,7 @@ namespace WinFormsApp1
if (_mapStorages.ContainsKey(name)) return; //уникальное имя if (_mapStorages.ContainsKey(name)) return; //уникальное имя
else else
{ {
_mapStorages.Add(name, new MapWithSetTraktorGeneric<DrawningObjectTractor, AbstractMap>(_pictureWidth, _pictureHeight, map)); _mapStorages.Add(name, new MapWithSetTraktorGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
} }
} }
@@ -40,14 +45,70 @@ namespace WinFormsApp1
} }
} }
public MapWithSetTraktorGeneric<DrawningObjectTractor, AbstractMap> this[string ind] public MapWithSetTraktorGeneric<IDrawningObject, AbstractMap> this[string ind]
{ {
get get
{ {
_mapStorages.TryGetValue(ind, out var MapWithSetDoubleDeckerBusGeneric); _mapStorages.TryGetValue(ind, out var result);
return MapWithSetDoubleDeckerBusGeneric; return result;
} }
} }
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new(filename))
{
fs.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
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 "Простая карта":
map = new SimpleMap();
break;
case "Поле":
map = new FieldMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetTraktorGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
} }
} }

View File

@@ -1,5 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
@@ -14,10 +19,30 @@ namespace WinFormsApp1
[STAThread] [STAThread]
static void Main() static void Main()
{ {
Application.SetHighDpiMode(HighDpiMode.SystemAware); // To customize application configuration such as set high DPI settings or default font,
Application.EnableVisualStyles(); // see https://aka.ms/applicationconfiguration.
Application.SetCompatibleTextRenderingDefault(false); ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetTraktor()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetTraktor>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetTraktor>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: "appsettings.json").Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@@ -27,16 +27,21 @@ namespace WinFormsApp1
public int Insert(T tractor, int position) public int Insert(T tractor, int position)
{ {
if (position < 0 && position > _maxCount) if (position > _maxCount && position < 0)
{ {
return -1; return -1;
} }
else if (_places.Contains(tractor))
{ {
throw new ArgumentException($"Объект {tractor} уже есть в наборе");
}
if (Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, tractor); _places.Insert(position, tractor);
return position; return position;
} }
}
public T Remove(int position) public T Remove(int position)
{ {

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsApp1
{
[Serializable]
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

@@ -3,9 +3,36 @@
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework> <TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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.LoggerConfiguration.ConditionExtensions" Version="1.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsApp1
{
internal class TraktorNotFoundException : ApplicationException
{
public TraktorNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public TraktorNotFoundException() : base() { }
public TraktorNotFoundException(string message) : base(message) { }
public TraktorNotFoundException(string message, Exception exception) : base(message, exception) { }
protected TraktorNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -0,0 +1,19 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"outputTemplate": "{Timestamp:HH:mm:ss. zzz} [{Level}] {Message} {Exception} {NewLine}",
"path": "D:/log.txt",
"fileSizeLimitBytes": 2147483648
}
}
],
"Properties": {
"Application": "Serilog-Demo"
}
}
}

13
WinFormsApp1/nlog.config Normal file
View File

@@ -0,0 +1,13 @@
<?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 ="tankerlog-${shortdate}.log"/>
</targets>
<rules>
<logger name ="*" minlevel ="Debug" writeTo ="toFile" />
</rules>
</nlog>
</configuration>