6 Commits

Author SHA1 Message Date
crum61kg
6a6abe240f Сравнение объектов 2023-02-14 23:21:28 +04:00
crum61kg
3473802309 меняю nlog на serilog + 2023-02-14 23:06:15 +04:00
crum61kg
2a2bac1b20 Изменения 2023-02-08 23:32:38 +04:00
crum61kg
86398dc418 Логирование 2023-02-08 21:48:34 +04:00
crum61kg
7884e5e29c Генерация ошибок 2023-02-08 21:21:52 +04:00
crum61kg
2ede363766 Изменение лаб_6 2023-02-08 20:43:26 +04:00
15 changed files with 580 additions and 64 deletions

View File

@@ -36,5 +36,40 @@ namespace WarmlyShip
{
_ship.DrawTransport(g);
}
public string GetInfo() => _ship?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectShip(data.CreateDrawningShip());
public bool Equals(IDrawningObject? other)
{
if (other == null)
{
return false;
}
var otherShip = other as DrawningObjectShip;
if (otherShip == null)
{
return false;
}
var ship = _ship.Ship;
var otherShipShip = otherShip._ship.Ship;
if (ship.Speed != otherShipShip.Speed)
{
return false;
}
if (ship.Weight != otherShipShip.Weight)
{
return false;
}
if (ship.BodyColor != otherShipShip.BodyColor)
{
return false;
}
// TODO доделать проверки в случае продвинутого объекта
return true;
}
}
}

View File

@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
internal static class ExtentionShip
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningShip CreateDrawningShip(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningLiner(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="drawningCar"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningShip drawningShip)
{
var ship = drawningShip.Ship;
var str =
$"{ship.Speed}{_separatorForObject}{ship.Weight}{_separatorForObject}{ship.BodyColor.Name}";
if (ship is not EntityLiner liner)
{
return str;
}
return $"{str}{_separatorForObject}{liner.DopColor.Name}{_separatorForObject}{liner.SwimmingPool}{_separatorForObject}{liner.DopDeck}";
}
}
}

View File

@@ -45,9 +45,16 @@
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.ButtonRemoveShip = new System.Windows.Forms.Button();
this.pictureBox1 = 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.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
@@ -63,9 +70,11 @@
this.groupBox1.Controls.Add(this.maskedTextBoxPosition);
this.groupBox1.Controls.Add(this.ButtonRemoveShip);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox1.Location = new System.Drawing.Point(593, 0);
this.groupBox1.Location = new System.Drawing.Point(677, 30);
this.groupBox1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 582);
this.groupBox1.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBox1.Size = new System.Drawing.Size(229, 746);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
@@ -77,9 +86,11 @@
this.groupBoxMaps.Controls.Add(this.buttonAddMap);
this.groupBoxMaps.Controls.Add(this.textBoxNewMapName);
this.groupBoxMaps.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxMaps.Location = new System.Drawing.Point(6, 22);
this.groupBoxMaps.Location = new System.Drawing.Point(7, 29);
this.groupBoxMaps.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBoxMaps.Name = "groupBoxMaps";
this.groupBoxMaps.Size = new System.Drawing.Size(188, 209);
this.groupBoxMaps.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBoxMaps.Size = new System.Drawing.Size(215, 279);
this.groupBoxMaps.TabIndex = 12;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Карты";
@@ -87,17 +98,20 @@
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 15;
this.listBoxMaps.Location = new System.Drawing.Point(6, 109);
this.listBoxMaps.ItemHeight = 20;
this.listBoxMaps.Location = new System.Drawing.Point(7, 145);
this.listBoxMaps.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(176, 64);
this.listBoxMaps.Size = new System.Drawing.Size(201, 84);
this.listBoxMaps.TabIndex = 7;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// buttonDeleteMap
//
this.buttonDeleteMap.Location = new System.Drawing.Point(6, 180);
this.buttonDeleteMap.Location = new System.Drawing.Point(7, 240);
this.buttonDeleteMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(176, 23);
this.buttonDeleteMap.Size = new System.Drawing.Size(201, 31);
this.buttonDeleteMap.TabIndex = 6;
this.buttonDeleteMap.Text = "Удалить карту";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
@@ -105,9 +119,10 @@
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(6, 80);
this.buttonAddMap.Location = new System.Drawing.Point(7, 107);
this.buttonAddMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(176, 23);
this.buttonAddMap.Size = new System.Drawing.Size(201, 31);
this.buttonAddMap.TabIndex = 5;
this.buttonAddMap.Text = "Добавить карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
@@ -115,9 +130,10 @@
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(6, 22);
this.textBoxNewMapName.Location = new System.Drawing.Point(7, 29);
this.textBoxNewMapName.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(176, 23);
this.textBoxNewMapName.Size = new System.Drawing.Size(201, 27);
this.textBoxNewMapName.TabIndex = 0;
//
// comboBoxSelectorMap
@@ -126,9 +142,10 @@
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Море"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(6, 51);
this.comboBoxSelectorMap.Location = new System.Drawing.Point(7, 68);
this.comboBoxSelectorMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(176, 23);
this.comboBoxSelectorMap.Size = new System.Drawing.Size(201, 28);
this.comboBoxSelectorMap.TabIndex = 4;
//
// buttonDown
@@ -136,18 +153,20 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::WarmlyShip.Properties.Resources.Down;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(96, 536);
this.buttonDown.Location = new System.Drawing.Point(110, 685);
this.buttonDown.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.Size = new System.Drawing.Size(34, 40);
this.buttonDown.TabIndex = 11;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// ButtonAddShip
//
this.ButtonAddShip.Location = new System.Drawing.Point(12, 298);
this.ButtonAddShip.Location = new System.Drawing.Point(14, 397);
this.ButtonAddShip.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonAddShip.Name = "ButtonAddShip";
this.ButtonAddShip.Size = new System.Drawing.Size(176, 25);
this.ButtonAddShip.Size = new System.Drawing.Size(201, 33);
this.ButtonAddShip.TabIndex = 2;
this.ButtonAddShip.Text = "Добавить корабль";
this.ButtonAddShip.UseVisualStyleBackColor = true;
@@ -158,9 +177,10 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::WarmlyShip.Properties.Resources.Up;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(96, 500);
this.buttonUp.Location = new System.Drawing.Point(110, 637);
this.buttonUp.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.Size = new System.Drawing.Size(34, 40);
this.buttonUp.TabIndex = 10;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
@@ -170,9 +190,10 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyShip.Properties.Resources.Right;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(132, 536);
this.buttonRight.Location = new System.Drawing.Point(151, 685);
this.buttonRight.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.Size = new System.Drawing.Size(34, 40);
this.buttonRight.TabIndex = 9;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
@@ -182,18 +203,20 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::WarmlyShip.Properties.Resources.Left;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(60, 536);
this.buttonLeft.Location = new System.Drawing.Point(69, 685);
this.buttonLeft.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.Size = new System.Drawing.Size(34, 40);
this.buttonLeft.TabIndex = 8;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// ButtonShowStorage
//
this.ButtonShowStorage.Location = new System.Drawing.Point(12, 402);
this.ButtonShowStorage.Location = new System.Drawing.Point(14, 536);
this.ButtonShowStorage.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonShowStorage.Name = "ButtonShowStorage";
this.ButtonShowStorage.Size = new System.Drawing.Size(176, 23);
this.ButtonShowStorage.Size = new System.Drawing.Size(201, 31);
this.ButtonShowStorage.TabIndex = 7;
this.ButtonShowStorage.Text = "Посмотреть хранилище";
this.ButtonShowStorage.UseVisualStyleBackColor = true;
@@ -201,9 +224,10 @@
//
// ButtonShowOnMap
//
this.ButtonShowOnMap.Location = new System.Drawing.Point(12, 431);
this.ButtonShowOnMap.Location = new System.Drawing.Point(14, 575);
this.ButtonShowOnMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonShowOnMap.Name = "ButtonShowOnMap";
this.ButtonShowOnMap.Size = new System.Drawing.Size(176, 23);
this.ButtonShowOnMap.Size = new System.Drawing.Size(201, 31);
this.ButtonShowOnMap.TabIndex = 6;
this.ButtonShowOnMap.Text = "Посмотреть карту";
this.ButtonShowOnMap.UseVisualStyleBackColor = true;
@@ -211,17 +235,19 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(12, 329);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(14, 439);
this.maskedTextBoxPosition.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(176, 23);
this.maskedTextBoxPosition.Size = new System.Drawing.Size(201, 27);
this.maskedTextBoxPosition.TabIndex = 5;
//
// ButtonRemoveShip
//
this.ButtonRemoveShip.Location = new System.Drawing.Point(12, 358);
this.ButtonRemoveShip.Location = new System.Drawing.Point(14, 477);
this.ButtonRemoveShip.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonRemoveShip.Name = "ButtonRemoveShip";
this.ButtonRemoveShip.Size = new System.Drawing.Size(176, 25);
this.ButtonRemoveShip.Size = new System.Drawing.Size(201, 33);
this.ButtonRemoveShip.TabIndex = 3;
this.ButtonRemoveShip.Text = "Удалить корабль";
this.ButtonRemoveShip.UseVisualStyleBackColor = true;
@@ -230,19 +256,65 @@
// pictureBox1
//
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Location = new System.Drawing.Point(0, 30);
this.pictureBox1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(593, 582);
this.pictureBox1.Size = new System.Drawing.Size(677, 746);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
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.Padding = new System.Windows.Forms.Padding(7, 3, 0, 3);
this.menuStrip.Size = new System.Drawing.Size(906, 30);
this.menuStrip.TabIndex = 2;
//
// файл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(59, 24);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetWarmlyShip
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(793, 582);
this.ClientSize = new System.Drawing.Size(906, 776);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormMapWithSetWarmlyShip";
this.Text = "FormMapWithSetWarmlyShip";
this.groupBox1.ResumeLayout(false);
@@ -250,7 +322,10 @@
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -273,5 +348,11 @@
private Button buttonDeleteMap;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@@ -8,6 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.DataFormats;
using Serilog;
namespace WarmlyShip
{
@@ -25,13 +26,19 @@ namespace WarmlyShip
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetWarmlyShip()
public FormMapWithSetWarmlyShip(ILogger logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox1.Width, pictureBox1.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -69,15 +76,18 @@ namespace WarmlyShip
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Information($"Карта была не выбрана или не названа");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Information($"Нет карты с названием: {textBoxNewMapName.Text}");
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.Information($"Добавлена карта {textBoxNewMapName.Text}");
}
/// <summary>
/// Выбор карты
@@ -87,6 +97,7 @@ namespace WarmlyShip
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.Information($"Переход на карту с названием: {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
/// <summary>
@@ -103,6 +114,7 @@ namespace WarmlyShip
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.Information($"Удалена карту с названием: {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
ReloadMaps();
}
}
@@ -120,18 +132,29 @@ namespace WarmlyShip
private void AddShip(DrawningShip liner)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
}
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(liner) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.Information($"Добавлен объект");
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.Warning("Не удалось добавить объект");
}
}
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(liner) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
catch(StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("Хранилище переполнено. Ошибка: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.Warning("Хранилище переполнено. Ошибка: {ex.Message}");
}
}
/// <summary>
@@ -149,20 +172,35 @@ namespace WarmlyShip
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); ;
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
_logger.Information($"Из карты удален объект с позиции {pos}");
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); ;
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.Warning($"Не удалось удалить объект с позиции {pos}");
}
}
else
catch (WarmlyShipNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления : {ex.Message}");
_logger.Warning($"Ошибка удаления : {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка : {ex.Message}");
_logger.Warning($"Неизвестная ошибка : {ex.Message}");
}
}
@@ -226,5 +264,52 @@ namespace WarmlyShip
pictureBox1.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.Information($"Сохранение прошло успешно. Сохранено в {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Warning($"Не удалось сохранить файл {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.Information($"Загрузка файла {openFileDialog.FileName} прошла успешно");
ReloadMaps();
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Warning($"Не загрузился файл {openFileDialog.FileName}. Ошибка:{ex.Message}");
}
}
}
}
}

View File

@@ -57,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="menuStrip.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>125, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>265, 17</value>
</metadata>
</root>

View File

@@ -9,7 +9,7 @@ namespace WarmlyShip
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawningObject
internal interface IDrawningObject : IEquatable<IDrawningObject>
{
/// <summary>
/// Шаг перемещения объекта
@@ -39,5 +39,11 @@ namespace WarmlyShip
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@@ -12,7 +12,7 @@ namespace WarmlyShip
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetWarmlyShipGeneric<T, U>
where T : class, IDrawningObject
where T : class, IDrawningObject, IEnumerable<T>
where U : AbstractMap
{
/// <summary>
@@ -58,7 +58,7 @@ namespace WarmlyShip
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="car"></param>
/// <param name="ship"></param>
/// <returns></returns>
public static int operator +(MapWithSetWarmlyShipGeneric<T, U> map, T ship)
{
@@ -113,6 +113,33 @@ namespace WarmlyShip
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var ship in _setWarmlyShip.GetShip())
{
data += $"{ship.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setWarmlyShip.Insert(DrawningObjectShip.Create(rec) as T);
}
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
@@ -174,5 +201,7 @@ namespace WarmlyShip
}
}
}
}

View File

@@ -14,7 +14,7 @@ namespace WarmlyShip
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetWarmlyShipGeneric<DrawningObjectShip, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
@@ -27,6 +27,16 @@ namespace WarmlyShip
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
@@ -34,7 +44,7 @@ namespace WarmlyShip
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetWarmlyShipGeneric<DrawningObjectShip, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -46,7 +56,7 @@ namespace WarmlyShip
public void AddMap(string name, AbstractMap map)
{
if (!Keys.Contains(name))
_mapStorages.Add(name, new MapWithSetWarmlyShipGeneric<DrawningObjectShip, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
/// <summary>
/// Удаление карты
@@ -62,7 +72,7 @@ namespace WarmlyShip
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetWarmlyShipGeneric<DrawningObjectShip, AbstractMap> this[string
public MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap> this[string
ind]
{
get
@@ -72,5 +82,75 @@ namespace WarmlyShip
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("Файл не найден");
}
using (StreamReader sr = new(filename))
{
if (!sr.ReadLine().Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
throw new Exception("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
while (!sr.EndOfStream)
{
var elem = sr.ReadLine().Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "MyMap":
map = new MyMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}

View File

@@ -1,3 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
namespace WarmlyShip
{
internal static class Program
@@ -10,8 +14,26 @@ namespace WarmlyShip
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetWarmlyShip());
var services = new ServiceCollection();
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetWarmlyShip(logger));
}
}
}
}

View File

@@ -11,7 +11,7 @@ namespace WarmlyShip
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetWarmlyShipGeneric<T>
where T : class
where T : class, IEnumerable<T>
{
/// <summary>
/// Список объектов, которые храним
@@ -51,6 +51,13 @@ namespace WarmlyShip
/// <returns></returns>
public int Insert(T ship, int position)
{
//TODO проверка на уникальность
if (Count >= _maxCount)
{
throw new StorageOverflowException(Count);
}
if (position < 0 || position > Count)
{
return -1;
@@ -67,7 +74,13 @@ namespace WarmlyShip
{
if (position < 0 || position >= Count)
return null;
var result = _places[position];
if (result == null)
{
throw new WarmlyShipNotFoundException(position);
}
_places.RemoveAt(position);
return result;

View File

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

@@ -8,6 +8,39 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
<None Remove="serilog.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
<EmbeddedResource Include="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" 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.1" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Settings.Delegates" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

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

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="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

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}: {Message};{NewLine}"
}
}
]
}
}